cytoscape.cjs.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593
  1. /**
  2. * Copyright (c) 2016-2026, The Cytoscape Consortium.
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. * this software and associated documentation files (the “Software”), to deal in
  6. * the Software without restriction, including without limitation the rights to
  7. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  8. * of the Software, and to permit persons to whom the Software is furnished to do
  9. * so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in all
  12. * copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. 'use strict';
  23. function _arrayLikeToArray(r, a) {
  24. (null == a || a > r.length) && (a = r.length);
  25. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  26. return n;
  27. }
  28. function _arrayWithHoles(r) {
  29. if (Array.isArray(r)) return r;
  30. }
  31. function _arrayWithoutHoles(r) {
  32. if (Array.isArray(r)) return _arrayLikeToArray(r);
  33. }
  34. function _classCallCheck(a, n) {
  35. if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
  36. }
  37. function _defineProperties(e, r) {
  38. for (var t = 0; t < r.length; t++) {
  39. var o = r[t];
  40. o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  41. }
  42. }
  43. function _createClass(e, r, t) {
  44. return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
  45. writable: false
  46. }), e;
  47. }
  48. function _createForOfIteratorHelper(r, e) {
  49. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  50. if (!t) {
  51. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
  52. t && (r = t);
  53. var n = 0,
  54. F = function () {};
  55. return {
  56. s: F,
  57. n: function () {
  58. return n >= r.length ? {
  59. done: true
  60. } : {
  61. done: false,
  62. value: r[n++]
  63. };
  64. },
  65. e: function (r) {
  66. throw r;
  67. },
  68. f: F
  69. };
  70. }
  71. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  72. }
  73. var o,
  74. a = true,
  75. u = false;
  76. return {
  77. s: function () {
  78. t = t.call(r);
  79. },
  80. n: function () {
  81. var r = t.next();
  82. return a = r.done, r;
  83. },
  84. e: function (r) {
  85. u = true, o = r;
  86. },
  87. f: function () {
  88. try {
  89. a || null == t.return || t.return();
  90. } finally {
  91. if (u) throw o;
  92. }
  93. }
  94. };
  95. }
  96. function _defineProperty$1(e, r, t) {
  97. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  98. value: t,
  99. enumerable: true,
  100. configurable: true,
  101. writable: true
  102. }) : e[r] = t, e;
  103. }
  104. function _iterableToArray(r) {
  105. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  106. }
  107. function _iterableToArrayLimit(r, l) {
  108. var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  109. if (null != t) {
  110. var e,
  111. n,
  112. i,
  113. u,
  114. a = [],
  115. f = true,
  116. o = false;
  117. try {
  118. if (i = (t = t.call(r)).next, 0 === l) {
  119. if (Object(t) !== t) return;
  120. f = !1;
  121. } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
  122. } catch (r) {
  123. o = true, n = r;
  124. } finally {
  125. try {
  126. if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
  127. } finally {
  128. if (o) throw n;
  129. }
  130. }
  131. return a;
  132. }
  133. }
  134. function _nonIterableRest() {
  135. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  136. }
  137. function _nonIterableSpread() {
  138. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  139. }
  140. function _slicedToArray(r, e) {
  141. return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
  142. }
  143. function _toConsumableArray(r) {
  144. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  145. }
  146. function _toPrimitive(t, r) {
  147. if ("object" != typeof t || !t) return t;
  148. var e = t[Symbol.toPrimitive];
  149. if (undefined !== e) {
  150. var i = e.call(t, r);
  151. if ("object" != typeof i) return i;
  152. throw new TypeError("@@toPrimitive must return a primitive value.");
  153. }
  154. return (String )(t);
  155. }
  156. function _toPropertyKey(t) {
  157. var i = _toPrimitive(t, "string");
  158. return "symbol" == typeof i ? i : i + "";
  159. }
  160. function _typeof(o) {
  161. "@babel/helpers - typeof";
  162. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  163. return typeof o;
  164. } : function (o) {
  165. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  166. }, _typeof(o);
  167. }
  168. function _unsupportedIterableToArray(r, a) {
  169. if (r) {
  170. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  171. var t = {}.toString.call(r).slice(8, -1);
  172. return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : undefined;
  173. }
  174. }
  175. var _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef
  176. var navigator = _window ? _window.navigator : null;
  177. _window ? _window.document : null;
  178. var typeofstr = _typeof('');
  179. var typeofobj = _typeof({});
  180. var typeoffn = _typeof(function () {});
  181. var typeofhtmlele = typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement);
  182. var instanceStr = function instanceStr(obj) {
  183. return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;
  184. };
  185. var string = function string(obj) {
  186. return obj != null && _typeof(obj) == typeofstr;
  187. };
  188. var fn$6 = function fn(obj) {
  189. return obj != null && _typeof(obj) === typeoffn;
  190. };
  191. var array = function array(obj) {
  192. return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);
  193. };
  194. var plainObject = function plainObject(obj) {
  195. return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;
  196. };
  197. var object = function object(obj) {
  198. return obj != null && _typeof(obj) === typeofobj;
  199. };
  200. var number$1 = function number(obj) {
  201. return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);
  202. };
  203. var integer = function integer(obj) {
  204. return number$1(obj) && Math.floor(obj) === obj;
  205. };
  206. var htmlElement = function htmlElement(obj) {
  207. if ('undefined' === typeofhtmlele) {
  208. return undefined;
  209. } else {
  210. return null != obj && obj instanceof HTMLElement;
  211. }
  212. };
  213. var elementOrCollection = function elementOrCollection(obj) {
  214. return element(obj) || collection(obj);
  215. };
  216. var element = function element(obj) {
  217. return instanceStr(obj) === 'collection' && obj._private.single;
  218. };
  219. var collection = function collection(obj) {
  220. return instanceStr(obj) === 'collection' && !obj._private.single;
  221. };
  222. var core = function core(obj) {
  223. return instanceStr(obj) === 'core';
  224. };
  225. var stylesheet = function stylesheet(obj) {
  226. return instanceStr(obj) === 'stylesheet';
  227. };
  228. var event = function event(obj) {
  229. return instanceStr(obj) === 'event';
  230. };
  231. var emptyString = function emptyString(obj) {
  232. if (obj === undefined || obj === null) {
  233. // null is empty
  234. return true;
  235. } else if (obj === '' || obj.match(/^\s+$/)) {
  236. return true; // empty string is empty
  237. }
  238. return false; // otherwise, we don't know what we've got
  239. };
  240. var domElement = function domElement(obj) {
  241. if (typeof HTMLElement === 'undefined') {
  242. return false; // we're not in a browser so it doesn't matter
  243. } else {
  244. return obj instanceof HTMLElement;
  245. }
  246. };
  247. var boundingBox = function boundingBox(obj) {
  248. return plainObject(obj) && number$1(obj.x1) && number$1(obj.x2) && number$1(obj.y1) && number$1(obj.y2);
  249. };
  250. var promise = function promise(obj) {
  251. return object(obj) && fn$6(obj.then);
  252. };
  253. var ms = function ms() {
  254. return navigator && navigator.userAgent.match(/msie|trident|edge/i);
  255. }; // probably a better way to detect this...
  256. var memoize = function memoize(fn, keyFn) {
  257. if (!keyFn) {
  258. keyFn = function keyFn() {
  259. if (arguments.length === 1) {
  260. return arguments[0];
  261. } else if (arguments.length === 0) {
  262. return 'undefined';
  263. }
  264. var args = [];
  265. for (var i = 0; i < arguments.length; i++) {
  266. args.push(arguments[i]);
  267. }
  268. return args.join('$');
  269. };
  270. }
  271. var _memoizedFn = function memoizedFn() {
  272. var self = this;
  273. var args = arguments;
  274. var ret;
  275. var k = keyFn.apply(self, args);
  276. var cache = _memoizedFn.cache;
  277. if (!(ret = cache[k])) {
  278. ret = cache[k] = fn.apply(self, args);
  279. }
  280. return ret;
  281. };
  282. _memoizedFn.cache = {};
  283. return _memoizedFn;
  284. };
  285. var camel2dash = memoize(function (str) {
  286. return str.replace(/([A-Z])/g, function (v) {
  287. return '-' + v.toLowerCase();
  288. });
  289. });
  290. var dash2camel = memoize(function (str) {
  291. return str.replace(/(-\w)/g, function (v) {
  292. return v[1].toUpperCase();
  293. });
  294. });
  295. var prependCamel = memoize(function (prefix, str) {
  296. return prefix + str[0].toUpperCase() + str.substring(1);
  297. }, function (prefix, str) {
  298. return prefix + '$' + str;
  299. });
  300. var capitalize = function capitalize(str) {
  301. if (emptyString(str)) {
  302. return str;
  303. }
  304. return str.charAt(0).toUpperCase() + str.substring(1);
  305. };
  306. var endsWith = function endsWith(string, suffix) {
  307. return string.slice(-1 * suffix.length) === suffix;
  308. };
  309. var number = '(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))';
  310. var rgba = 'rgb[a]?\\((' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)(?:\\s*,\\s*(' + number + '))?\\)';
  311. var rgbaNoBackRefs = 'rgb[a]?\\((?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)(?:\\s*,\\s*(?:' + number + '))?\\)';
  312. var hsla = 'hsl[a]?\\((' + number + ')\\s*,\\s*(' + number + '[%])\\s*,\\s*(' + number + '[%])(?:\\s*,\\s*(' + number + '))?\\)';
  313. var hslaNoBackRefs = 'hsl[a]?\\((?:' + number + ')\\s*,\\s*(?:' + number + '[%])\\s*,\\s*(?:' + number + '[%])(?:\\s*,\\s*(?:' + number + '))?\\)';
  314. var hex3 = '\\#[0-9a-fA-F]{3}';
  315. var hex6 = '\\#[0-9a-fA-F]{6}';
  316. var ascending = function ascending(a, b) {
  317. if (a < b) {
  318. return -1;
  319. } else if (a > b) {
  320. return 1;
  321. } else {
  322. return 0;
  323. }
  324. };
  325. var descending = function descending(a, b) {
  326. return -1 * ascending(a, b);
  327. };
  328. var extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
  329. var args = arguments;
  330. for (var i = 1; i < args.length; i++) {
  331. var obj = args[i];
  332. if (obj == null) {
  333. continue;
  334. }
  335. var keys = Object.keys(obj);
  336. for (var j = 0; j < keys.length; j++) {
  337. var k = keys[j];
  338. tgt[k] = obj[k];
  339. }
  340. }
  341. return tgt;
  342. };
  343. // get [r, g, b] from #abc or #aabbcc
  344. var hex2tuple = function hex2tuple(hex) {
  345. if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {
  346. return;
  347. }
  348. var shortHex = hex.length === 4;
  349. var r, g, b;
  350. var base = 16;
  351. if (shortHex) {
  352. r = parseInt(hex[1] + hex[1], base);
  353. g = parseInt(hex[2] + hex[2], base);
  354. b = parseInt(hex[3] + hex[3], base);
  355. } else {
  356. r = parseInt(hex[1] + hex[2], base);
  357. g = parseInt(hex[3] + hex[4], base);
  358. b = parseInt(hex[5] + hex[6], base);
  359. }
  360. return [r, g, b];
  361. };
  362. // get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)
  363. var hsl2tuple = function hsl2tuple(hsl) {
  364. var ret;
  365. var h, s, l, a, r, g, b;
  366. function hue2rgb(p, q, t) {
  367. if (t < 0) t += 1;
  368. if (t > 1) t -= 1;
  369. if (t < 1 / 6) return p + (q - p) * 6 * t;
  370. if (t < 1 / 2) return q;
  371. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  372. return p;
  373. }
  374. var m = new RegExp('^' + hsla + '$').exec(hsl);
  375. if (m) {
  376. // get hue
  377. h = parseInt(m[1]);
  378. if (h < 0) {
  379. h = (360 - -1 * h % 360) % 360;
  380. } else if (h > 360) {
  381. h = h % 360;
  382. }
  383. h /= 360; // normalise on [0, 1]
  384. s = parseFloat(m[2]);
  385. if (s < 0 || s > 100) {
  386. return;
  387. } // saturation is [0, 100]
  388. s = s / 100; // normalise on [0, 1]
  389. l = parseFloat(m[3]);
  390. if (l < 0 || l > 100) {
  391. return;
  392. } // lightness is [0, 100]
  393. l = l / 100; // normalise on [0, 1]
  394. a = m[4];
  395. if (a !== undefined) {
  396. a = parseFloat(a);
  397. if (a < 0 || a > 1) {
  398. return;
  399. } // alpha is [0, 1]
  400. }
  401. // now, convert to rgb
  402. // code from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  403. if (s === 0) {
  404. r = g = b = Math.round(l * 255); // achromatic
  405. } else {
  406. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  407. var p = 2 * l - q;
  408. r = Math.round(255 * hue2rgb(p, q, h + 1 / 3));
  409. g = Math.round(255 * hue2rgb(p, q, h));
  410. b = Math.round(255 * hue2rgb(p, q, h - 1 / 3));
  411. }
  412. ret = [r, g, b, a];
  413. }
  414. return ret;
  415. };
  416. // get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)
  417. var rgb2tuple = function rgb2tuple(rgb) {
  418. var ret;
  419. var m = new RegExp('^' + rgba + '$').exec(rgb);
  420. if (m) {
  421. ret = [];
  422. var isPct = [];
  423. for (var i = 1; i <= 3; i++) {
  424. var channel = m[i];
  425. if (channel[channel.length - 1] === '%') {
  426. isPct[i] = true;
  427. }
  428. channel = parseFloat(channel);
  429. if (isPct[i]) {
  430. channel = channel / 100 * 255; // normalise to [0, 255]
  431. }
  432. if (channel < 0 || channel > 255) {
  433. return;
  434. } // invalid channel value
  435. ret.push(Math.floor(channel));
  436. }
  437. var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];
  438. var allArePct = isPct[1] && isPct[2] && isPct[3];
  439. if (atLeastOneIsPct && !allArePct) {
  440. return;
  441. } // must all be percent values if one is
  442. var alpha = m[4];
  443. if (alpha !== undefined) {
  444. alpha = parseFloat(alpha);
  445. if (alpha < 0 || alpha > 1) {
  446. return;
  447. } // invalid alpha value
  448. ret.push(alpha);
  449. }
  450. }
  451. return ret;
  452. };
  453. var colorname2tuple = function colorname2tuple(color) {
  454. return colors[color.toLowerCase()];
  455. };
  456. var color2tuple = function color2tuple(color) {
  457. return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);
  458. };
  459. var colors = {
  460. // special colour names
  461. transparent: [0, 0, 0, 0],
  462. // NB alpha === 0
  463. // regular colours
  464. aliceblue: [240, 248, 255],
  465. antiquewhite: [250, 235, 215],
  466. aqua: [0, 255, 255],
  467. aquamarine: [127, 255, 212],
  468. azure: [240, 255, 255],
  469. beige: [245, 245, 220],
  470. bisque: [255, 228, 196],
  471. black: [0, 0, 0],
  472. blanchedalmond: [255, 235, 205],
  473. blue: [0, 0, 255],
  474. blueviolet: [138, 43, 226],
  475. brown: [165, 42, 42],
  476. burlywood: [222, 184, 135],
  477. cadetblue: [95, 158, 160],
  478. chartreuse: [127, 255, 0],
  479. chocolate: [210, 105, 30],
  480. coral: [255, 127, 80],
  481. cornflowerblue: [100, 149, 237],
  482. cornsilk: [255, 248, 220],
  483. crimson: [220, 20, 60],
  484. cyan: [0, 255, 255],
  485. darkblue: [0, 0, 139],
  486. darkcyan: [0, 139, 139],
  487. darkgoldenrod: [184, 134, 11],
  488. darkgray: [169, 169, 169],
  489. darkgreen: [0, 100, 0],
  490. darkgrey: [169, 169, 169],
  491. darkkhaki: [189, 183, 107],
  492. darkmagenta: [139, 0, 139],
  493. darkolivegreen: [85, 107, 47],
  494. darkorange: [255, 140, 0],
  495. darkorchid: [153, 50, 204],
  496. darkred: [139, 0, 0],
  497. darksalmon: [233, 150, 122],
  498. darkseagreen: [143, 188, 143],
  499. darkslateblue: [72, 61, 139],
  500. darkslategray: [47, 79, 79],
  501. darkslategrey: [47, 79, 79],
  502. darkturquoise: [0, 206, 209],
  503. darkviolet: [148, 0, 211],
  504. deeppink: [255, 20, 147],
  505. deepskyblue: [0, 191, 255],
  506. dimgray: [105, 105, 105],
  507. dimgrey: [105, 105, 105],
  508. dodgerblue: [30, 144, 255],
  509. firebrick: [178, 34, 34],
  510. floralwhite: [255, 250, 240],
  511. forestgreen: [34, 139, 34],
  512. fuchsia: [255, 0, 255],
  513. gainsboro: [220, 220, 220],
  514. ghostwhite: [248, 248, 255],
  515. gold: [255, 215, 0],
  516. goldenrod: [218, 165, 32],
  517. gray: [128, 128, 128],
  518. grey: [128, 128, 128],
  519. green: [0, 128, 0],
  520. greenyellow: [173, 255, 47],
  521. honeydew: [240, 255, 240],
  522. hotpink: [255, 105, 180],
  523. indianred: [205, 92, 92],
  524. indigo: [75, 0, 130],
  525. ivory: [255, 255, 240],
  526. khaki: [240, 230, 140],
  527. lavender: [230, 230, 250],
  528. lavenderblush: [255, 240, 245],
  529. lawngreen: [124, 252, 0],
  530. lemonchiffon: [255, 250, 205],
  531. lightblue: [173, 216, 230],
  532. lightcoral: [240, 128, 128],
  533. lightcyan: [224, 255, 255],
  534. lightgoldenrodyellow: [250, 250, 210],
  535. lightgray: [211, 211, 211],
  536. lightgreen: [144, 238, 144],
  537. lightgrey: [211, 211, 211],
  538. lightpink: [255, 182, 193],
  539. lightsalmon: [255, 160, 122],
  540. lightseagreen: [32, 178, 170],
  541. lightskyblue: [135, 206, 250],
  542. lightslategray: [119, 136, 153],
  543. lightslategrey: [119, 136, 153],
  544. lightsteelblue: [176, 196, 222],
  545. lightyellow: [255, 255, 224],
  546. lime: [0, 255, 0],
  547. limegreen: [50, 205, 50],
  548. linen: [250, 240, 230],
  549. magenta: [255, 0, 255],
  550. maroon: [128, 0, 0],
  551. mediumaquamarine: [102, 205, 170],
  552. mediumblue: [0, 0, 205],
  553. mediumorchid: [186, 85, 211],
  554. mediumpurple: [147, 112, 219],
  555. mediumseagreen: [60, 179, 113],
  556. mediumslateblue: [123, 104, 238],
  557. mediumspringgreen: [0, 250, 154],
  558. mediumturquoise: [72, 209, 204],
  559. mediumvioletred: [199, 21, 133],
  560. midnightblue: [25, 25, 112],
  561. mintcream: [245, 255, 250],
  562. mistyrose: [255, 228, 225],
  563. moccasin: [255, 228, 181],
  564. navajowhite: [255, 222, 173],
  565. navy: [0, 0, 128],
  566. oldlace: [253, 245, 230],
  567. olive: [128, 128, 0],
  568. olivedrab: [107, 142, 35],
  569. orange: [255, 165, 0],
  570. orangered: [255, 69, 0],
  571. orchid: [218, 112, 214],
  572. palegoldenrod: [238, 232, 170],
  573. palegreen: [152, 251, 152],
  574. paleturquoise: [175, 238, 238],
  575. palevioletred: [219, 112, 147],
  576. papayawhip: [255, 239, 213],
  577. peachpuff: [255, 218, 185],
  578. peru: [205, 133, 63],
  579. pink: [255, 192, 203],
  580. plum: [221, 160, 221],
  581. powderblue: [176, 224, 230],
  582. purple: [128, 0, 128],
  583. red: [255, 0, 0],
  584. rosybrown: [188, 143, 143],
  585. royalblue: [65, 105, 225],
  586. saddlebrown: [139, 69, 19],
  587. salmon: [250, 128, 114],
  588. sandybrown: [244, 164, 96],
  589. seagreen: [46, 139, 87],
  590. seashell: [255, 245, 238],
  591. sienna: [160, 82, 45],
  592. silver: [192, 192, 192],
  593. skyblue: [135, 206, 235],
  594. slateblue: [106, 90, 205],
  595. slategray: [112, 128, 144],
  596. slategrey: [112, 128, 144],
  597. snow: [255, 250, 250],
  598. springgreen: [0, 255, 127],
  599. steelblue: [70, 130, 180],
  600. tan: [210, 180, 140],
  601. teal: [0, 128, 128],
  602. thistle: [216, 191, 216],
  603. tomato: [255, 99, 71],
  604. turquoise: [64, 224, 208],
  605. violet: [238, 130, 238],
  606. wheat: [245, 222, 179],
  607. white: [255, 255, 255],
  608. whitesmoke: [245, 245, 245],
  609. yellow: [255, 255, 0],
  610. yellowgreen: [154, 205, 50]
  611. };
  612. // sets the value in a map (map may not be built)
  613. var setMap = function setMap(options) {
  614. var obj = options.map;
  615. var keys = options.keys;
  616. var l = keys.length;
  617. for (var i = 0; i < l; i++) {
  618. var key = keys[i];
  619. if (plainObject(key)) {
  620. throw Error('Tried to set map with object key');
  621. }
  622. if (i < keys.length - 1) {
  623. // extend the map if necessary
  624. if (obj[key] == null) {
  625. obj[key] = {};
  626. }
  627. obj = obj[key];
  628. } else {
  629. // set the value
  630. obj[key] = options.value;
  631. }
  632. }
  633. };
  634. // gets the value in a map even if it's not built in places
  635. var getMap = function getMap(options) {
  636. var obj = options.map;
  637. var keys = options.keys;
  638. var l = keys.length;
  639. for (var i = 0; i < l; i++) {
  640. var key = keys[i];
  641. if (plainObject(key)) {
  642. throw Error('Tried to get map with object key');
  643. }
  644. obj = obj[key];
  645. if (obj == null) {
  646. return obj;
  647. }
  648. }
  649. return obj;
  650. };
  651. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  652. function getDefaultExportFromCjs (x) {
  653. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  654. }
  655. /**
  656. * Checks if `value` is the
  657. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  658. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  659. *
  660. * @static
  661. * @memberOf _
  662. * @since 0.1.0
  663. * @category Lang
  664. * @param {*} value The value to check.
  665. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  666. * @example
  667. *
  668. * _.isObject({});
  669. * // => true
  670. *
  671. * _.isObject([1, 2, 3]);
  672. * // => true
  673. *
  674. * _.isObject(_.noop);
  675. * // => true
  676. *
  677. * _.isObject(null);
  678. * // => false
  679. */
  680. var isObject_1;
  681. var hasRequiredIsObject;
  682. function requireIsObject () {
  683. if (hasRequiredIsObject) return isObject_1;
  684. hasRequiredIsObject = 1;
  685. function isObject(value) {
  686. var type = typeof value;
  687. return value != null && (type == 'object' || type == 'function');
  688. }
  689. isObject_1 = isObject;
  690. return isObject_1;
  691. }
  692. /** Detect free variable `global` from Node.js. */
  693. var _freeGlobal;
  694. var hasRequired_freeGlobal;
  695. function require_freeGlobal () {
  696. if (hasRequired_freeGlobal) return _freeGlobal;
  697. hasRequired_freeGlobal = 1;
  698. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  699. _freeGlobal = freeGlobal;
  700. return _freeGlobal;
  701. }
  702. var _root;
  703. var hasRequired_root;
  704. function require_root () {
  705. if (hasRequired_root) return _root;
  706. hasRequired_root = 1;
  707. var freeGlobal = require_freeGlobal();
  708. /** Detect free variable `self`. */
  709. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  710. /** Used as a reference to the global object. */
  711. var root = freeGlobal || freeSelf || Function('return this')();
  712. _root = root;
  713. return _root;
  714. }
  715. var now_1;
  716. var hasRequiredNow;
  717. function requireNow () {
  718. if (hasRequiredNow) return now_1;
  719. hasRequiredNow = 1;
  720. var root = require_root();
  721. /**
  722. * Gets the timestamp of the number of milliseconds that have elapsed since
  723. * the Unix epoch (1 January 1970 00:00:00 UTC).
  724. *
  725. * @static
  726. * @memberOf _
  727. * @since 2.4.0
  728. * @category Date
  729. * @returns {number} Returns the timestamp.
  730. * @example
  731. *
  732. * _.defer(function(stamp) {
  733. * console.log(_.now() - stamp);
  734. * }, _.now());
  735. * // => Logs the number of milliseconds it took for the deferred invocation.
  736. */
  737. var now = function() {
  738. return root.Date.now();
  739. };
  740. now_1 = now;
  741. return now_1;
  742. }
  743. /** Used to match a single whitespace character. */
  744. var _trimmedEndIndex;
  745. var hasRequired_trimmedEndIndex;
  746. function require_trimmedEndIndex () {
  747. if (hasRequired_trimmedEndIndex) return _trimmedEndIndex;
  748. hasRequired_trimmedEndIndex = 1;
  749. var reWhitespace = /\s/;
  750. /**
  751. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  752. * character of `string`.
  753. *
  754. * @private
  755. * @param {string} string The string to inspect.
  756. * @returns {number} Returns the index of the last non-whitespace character.
  757. */
  758. function trimmedEndIndex(string) {
  759. var index = string.length;
  760. while (index-- && reWhitespace.test(string.charAt(index))) {}
  761. return index;
  762. }
  763. _trimmedEndIndex = trimmedEndIndex;
  764. return _trimmedEndIndex;
  765. }
  766. var _baseTrim;
  767. var hasRequired_baseTrim;
  768. function require_baseTrim () {
  769. if (hasRequired_baseTrim) return _baseTrim;
  770. hasRequired_baseTrim = 1;
  771. var trimmedEndIndex = require_trimmedEndIndex();
  772. /** Used to match leading whitespace. */
  773. var reTrimStart = /^\s+/;
  774. /**
  775. * The base implementation of `_.trim`.
  776. *
  777. * @private
  778. * @param {string} string The string to trim.
  779. * @returns {string} Returns the trimmed string.
  780. */
  781. function baseTrim(string) {
  782. return string
  783. ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  784. : string;
  785. }
  786. _baseTrim = baseTrim;
  787. return _baseTrim;
  788. }
  789. var _Symbol;
  790. var hasRequired_Symbol;
  791. function require_Symbol () {
  792. if (hasRequired_Symbol) return _Symbol;
  793. hasRequired_Symbol = 1;
  794. var root = require_root();
  795. /** Built-in value references. */
  796. var Symbol = root.Symbol;
  797. _Symbol = Symbol;
  798. return _Symbol;
  799. }
  800. var _getRawTag;
  801. var hasRequired_getRawTag;
  802. function require_getRawTag () {
  803. if (hasRequired_getRawTag) return _getRawTag;
  804. hasRequired_getRawTag = 1;
  805. var Symbol = require_Symbol();
  806. /** Used for built-in method references. */
  807. var objectProto = Object.prototype;
  808. /** Used to check objects for own properties. */
  809. var hasOwnProperty = objectProto.hasOwnProperty;
  810. /**
  811. * Used to resolve the
  812. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  813. * of values.
  814. */
  815. var nativeObjectToString = objectProto.toString;
  816. /** Built-in value references. */
  817. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  818. /**
  819. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  820. *
  821. * @private
  822. * @param {*} value The value to query.
  823. * @returns {string} Returns the raw `toStringTag`.
  824. */
  825. function getRawTag(value) {
  826. var isOwn = hasOwnProperty.call(value, symToStringTag),
  827. tag = value[symToStringTag];
  828. try {
  829. value[symToStringTag] = undefined;
  830. var unmasked = true;
  831. } catch (e) {}
  832. var result = nativeObjectToString.call(value);
  833. if (unmasked) {
  834. if (isOwn) {
  835. value[symToStringTag] = tag;
  836. } else {
  837. delete value[symToStringTag];
  838. }
  839. }
  840. return result;
  841. }
  842. _getRawTag = getRawTag;
  843. return _getRawTag;
  844. }
  845. /** Used for built-in method references. */
  846. var _objectToString;
  847. var hasRequired_objectToString;
  848. function require_objectToString () {
  849. if (hasRequired_objectToString) return _objectToString;
  850. hasRequired_objectToString = 1;
  851. var objectProto = Object.prototype;
  852. /**
  853. * Used to resolve the
  854. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  855. * of values.
  856. */
  857. var nativeObjectToString = objectProto.toString;
  858. /**
  859. * Converts `value` to a string using `Object.prototype.toString`.
  860. *
  861. * @private
  862. * @param {*} value The value to convert.
  863. * @returns {string} Returns the converted string.
  864. */
  865. function objectToString(value) {
  866. return nativeObjectToString.call(value);
  867. }
  868. _objectToString = objectToString;
  869. return _objectToString;
  870. }
  871. var _baseGetTag;
  872. var hasRequired_baseGetTag;
  873. function require_baseGetTag () {
  874. if (hasRequired_baseGetTag) return _baseGetTag;
  875. hasRequired_baseGetTag = 1;
  876. var Symbol = require_Symbol(),
  877. getRawTag = require_getRawTag(),
  878. objectToString = require_objectToString();
  879. /** `Object#toString` result references. */
  880. var nullTag = '[object Null]',
  881. undefinedTag = '[object Undefined]';
  882. /** Built-in value references. */
  883. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  884. /**
  885. * The base implementation of `getTag` without fallbacks for buggy environments.
  886. *
  887. * @private
  888. * @param {*} value The value to query.
  889. * @returns {string} Returns the `toStringTag`.
  890. */
  891. function baseGetTag(value) {
  892. if (value == null) {
  893. return value === undefined ? undefinedTag : nullTag;
  894. }
  895. return (symToStringTag && symToStringTag in Object(value))
  896. ? getRawTag(value)
  897. : objectToString(value);
  898. }
  899. _baseGetTag = baseGetTag;
  900. return _baseGetTag;
  901. }
  902. /**
  903. * Checks if `value` is object-like. A value is object-like if it's not `null`
  904. * and has a `typeof` result of "object".
  905. *
  906. * @static
  907. * @memberOf _
  908. * @since 4.0.0
  909. * @category Lang
  910. * @param {*} value The value to check.
  911. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  912. * @example
  913. *
  914. * _.isObjectLike({});
  915. * // => true
  916. *
  917. * _.isObjectLike([1, 2, 3]);
  918. * // => true
  919. *
  920. * _.isObjectLike(_.noop);
  921. * // => false
  922. *
  923. * _.isObjectLike(null);
  924. * // => false
  925. */
  926. var isObjectLike_1;
  927. var hasRequiredIsObjectLike;
  928. function requireIsObjectLike () {
  929. if (hasRequiredIsObjectLike) return isObjectLike_1;
  930. hasRequiredIsObjectLike = 1;
  931. function isObjectLike(value) {
  932. return value != null && typeof value == 'object';
  933. }
  934. isObjectLike_1 = isObjectLike;
  935. return isObjectLike_1;
  936. }
  937. var isSymbol_1;
  938. var hasRequiredIsSymbol;
  939. function requireIsSymbol () {
  940. if (hasRequiredIsSymbol) return isSymbol_1;
  941. hasRequiredIsSymbol = 1;
  942. var baseGetTag = require_baseGetTag(),
  943. isObjectLike = requireIsObjectLike();
  944. /** `Object#toString` result references. */
  945. var symbolTag = '[object Symbol]';
  946. /**
  947. * Checks if `value` is classified as a `Symbol` primitive or object.
  948. *
  949. * @static
  950. * @memberOf _
  951. * @since 4.0.0
  952. * @category Lang
  953. * @param {*} value The value to check.
  954. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  955. * @example
  956. *
  957. * _.isSymbol(Symbol.iterator);
  958. * // => true
  959. *
  960. * _.isSymbol('abc');
  961. * // => false
  962. */
  963. function isSymbol(value) {
  964. return typeof value == 'symbol' ||
  965. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  966. }
  967. isSymbol_1 = isSymbol;
  968. return isSymbol_1;
  969. }
  970. var toNumber_1;
  971. var hasRequiredToNumber;
  972. function requireToNumber () {
  973. if (hasRequiredToNumber) return toNumber_1;
  974. hasRequiredToNumber = 1;
  975. var baseTrim = require_baseTrim(),
  976. isObject = requireIsObject(),
  977. isSymbol = requireIsSymbol();
  978. /** Used as references for various `Number` constants. */
  979. var NAN = 0 / 0;
  980. /** Used to detect bad signed hexadecimal string values. */
  981. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  982. /** Used to detect binary string values. */
  983. var reIsBinary = /^0b[01]+$/i;
  984. /** Used to detect octal string values. */
  985. var reIsOctal = /^0o[0-7]+$/i;
  986. /** Built-in method references without a dependency on `root`. */
  987. var freeParseInt = parseInt;
  988. /**
  989. * Converts `value` to a number.
  990. *
  991. * @static
  992. * @memberOf _
  993. * @since 4.0.0
  994. * @category Lang
  995. * @param {*} value The value to process.
  996. * @returns {number} Returns the number.
  997. * @example
  998. *
  999. * _.toNumber(3.2);
  1000. * // => 3.2
  1001. *
  1002. * _.toNumber(Number.MIN_VALUE);
  1003. * // => 5e-324
  1004. *
  1005. * _.toNumber(Infinity);
  1006. * // => Infinity
  1007. *
  1008. * _.toNumber('3.2');
  1009. * // => 3.2
  1010. */
  1011. function toNumber(value) {
  1012. if (typeof value == 'number') {
  1013. return value;
  1014. }
  1015. if (isSymbol(value)) {
  1016. return NAN;
  1017. }
  1018. if (isObject(value)) {
  1019. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1020. value = isObject(other) ? (other + '') : other;
  1021. }
  1022. if (typeof value != 'string') {
  1023. return value === 0 ? value : +value;
  1024. }
  1025. value = baseTrim(value);
  1026. var isBinary = reIsBinary.test(value);
  1027. return (isBinary || reIsOctal.test(value))
  1028. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1029. : (reIsBadHex.test(value) ? NAN : +value);
  1030. }
  1031. toNumber_1 = toNumber;
  1032. return toNumber_1;
  1033. }
  1034. var debounce_1;
  1035. var hasRequiredDebounce;
  1036. function requireDebounce () {
  1037. if (hasRequiredDebounce) return debounce_1;
  1038. hasRequiredDebounce = 1;
  1039. var isObject = requireIsObject(),
  1040. now = requireNow(),
  1041. toNumber = requireToNumber();
  1042. /** Error message constants. */
  1043. var FUNC_ERROR_TEXT = 'Expected a function';
  1044. /* Built-in method references for those with the same name as other `lodash` methods. */
  1045. var nativeMax = Math.max,
  1046. nativeMin = Math.min;
  1047. /**
  1048. * Creates a debounced function that delays invoking `func` until after `wait`
  1049. * milliseconds have elapsed since the last time the debounced function was
  1050. * invoked. The debounced function comes with a `cancel` method to cancel
  1051. * delayed `func` invocations and a `flush` method to immediately invoke them.
  1052. * Provide `options` to indicate whether `func` should be invoked on the
  1053. * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
  1054. * with the last arguments provided to the debounced function. Subsequent
  1055. * calls to the debounced function return the result of the last `func`
  1056. * invocation.
  1057. *
  1058. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  1059. * invoked on the trailing edge of the timeout only if the debounced function
  1060. * is invoked more than once during the `wait` timeout.
  1061. *
  1062. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  1063. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  1064. *
  1065. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  1066. * for details over the differences between `_.debounce` and `_.throttle`.
  1067. *
  1068. * @static
  1069. * @memberOf _
  1070. * @since 0.1.0
  1071. * @category Function
  1072. * @param {Function} func The function to debounce.
  1073. * @param {number} [wait=0] The number of milliseconds to delay.
  1074. * @param {Object} [options={}] The options object.
  1075. * @param {boolean} [options.leading=false]
  1076. * Specify invoking on the leading edge of the timeout.
  1077. * @param {number} [options.maxWait]
  1078. * The maximum time `func` is allowed to be delayed before it's invoked.
  1079. * @param {boolean} [options.trailing=true]
  1080. * Specify invoking on the trailing edge of the timeout.
  1081. * @returns {Function} Returns the new debounced function.
  1082. * @example
  1083. *
  1084. * // Avoid costly calculations while the window size is in flux.
  1085. * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  1086. *
  1087. * // Invoke `sendMail` when clicked, debouncing subsequent calls.
  1088. * jQuery(element).on('click', _.debounce(sendMail, 300, {
  1089. * 'leading': true,
  1090. * 'trailing': false
  1091. * }));
  1092. *
  1093. * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
  1094. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
  1095. * var source = new EventSource('/stream');
  1096. * jQuery(source).on('message', debounced);
  1097. *
  1098. * // Cancel the trailing debounced invocation.
  1099. * jQuery(window).on('popstate', debounced.cancel);
  1100. */
  1101. function debounce(func, wait, options) {
  1102. var lastArgs,
  1103. lastThis,
  1104. maxWait,
  1105. result,
  1106. timerId,
  1107. lastCallTime,
  1108. lastInvokeTime = 0,
  1109. leading = false,
  1110. maxing = false,
  1111. trailing = true;
  1112. if (typeof func != 'function') {
  1113. throw new TypeError(FUNC_ERROR_TEXT);
  1114. }
  1115. wait = toNumber(wait) || 0;
  1116. if (isObject(options)) {
  1117. leading = !!options.leading;
  1118. maxing = 'maxWait' in options;
  1119. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  1120. trailing = 'trailing' in options ? !!options.trailing : trailing;
  1121. }
  1122. function invokeFunc(time) {
  1123. var args = lastArgs,
  1124. thisArg = lastThis;
  1125. lastArgs = lastThis = undefined;
  1126. lastInvokeTime = time;
  1127. result = func.apply(thisArg, args);
  1128. return result;
  1129. }
  1130. function leadingEdge(time) {
  1131. // Reset any `maxWait` timer.
  1132. lastInvokeTime = time;
  1133. // Start the timer for the trailing edge.
  1134. timerId = setTimeout(timerExpired, wait);
  1135. // Invoke the leading edge.
  1136. return leading ? invokeFunc(time) : result;
  1137. }
  1138. function remainingWait(time) {
  1139. var timeSinceLastCall = time - lastCallTime,
  1140. timeSinceLastInvoke = time - lastInvokeTime,
  1141. timeWaiting = wait - timeSinceLastCall;
  1142. return maxing
  1143. ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
  1144. : timeWaiting;
  1145. }
  1146. function shouldInvoke(time) {
  1147. var timeSinceLastCall = time - lastCallTime,
  1148. timeSinceLastInvoke = time - lastInvokeTime;
  1149. // Either this is the first call, activity has stopped and we're at the
  1150. // trailing edge, the system time has gone backwards and we're treating
  1151. // it as the trailing edge, or we've hit the `maxWait` limit.
  1152. return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
  1153. (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  1154. }
  1155. function timerExpired() {
  1156. var time = now();
  1157. if (shouldInvoke(time)) {
  1158. return trailingEdge(time);
  1159. }
  1160. // Restart the timer.
  1161. timerId = setTimeout(timerExpired, remainingWait(time));
  1162. }
  1163. function trailingEdge(time) {
  1164. timerId = undefined;
  1165. // Only invoke if we have `lastArgs` which means `func` has been
  1166. // debounced at least once.
  1167. if (trailing && lastArgs) {
  1168. return invokeFunc(time);
  1169. }
  1170. lastArgs = lastThis = undefined;
  1171. return result;
  1172. }
  1173. function cancel() {
  1174. if (timerId !== undefined) {
  1175. clearTimeout(timerId);
  1176. }
  1177. lastInvokeTime = 0;
  1178. lastArgs = lastCallTime = lastThis = timerId = undefined;
  1179. }
  1180. function flush() {
  1181. return timerId === undefined ? result : trailingEdge(now());
  1182. }
  1183. function debounced() {
  1184. var time = now(),
  1185. isInvoking = shouldInvoke(time);
  1186. lastArgs = arguments;
  1187. lastThis = this;
  1188. lastCallTime = time;
  1189. if (isInvoking) {
  1190. if (timerId === undefined) {
  1191. return leadingEdge(lastCallTime);
  1192. }
  1193. if (maxing) {
  1194. // Handle invocations in a tight loop.
  1195. clearTimeout(timerId);
  1196. timerId = setTimeout(timerExpired, wait);
  1197. return invokeFunc(lastCallTime);
  1198. }
  1199. }
  1200. if (timerId === undefined) {
  1201. timerId = setTimeout(timerExpired, wait);
  1202. }
  1203. return result;
  1204. }
  1205. debounced.cancel = cancel;
  1206. debounced.flush = flush;
  1207. return debounced;
  1208. }
  1209. debounce_1 = debounce;
  1210. return debounce_1;
  1211. }
  1212. var debounceExports = requireDebounce();
  1213. var debounce = /*@__PURE__*/getDefaultExportFromCjs(debounceExports);
  1214. var performance$1 = _window ? _window.performance : null;
  1215. var pnow = performance$1 && performance$1.now ? function () {
  1216. return performance$1.now();
  1217. } : function () {
  1218. return Date.now();
  1219. };
  1220. var raf = function () {
  1221. if (_window) {
  1222. if (_window.requestAnimationFrame) {
  1223. return function (fn) {
  1224. _window.requestAnimationFrame(fn);
  1225. };
  1226. } else if (_window.mozRequestAnimationFrame) {
  1227. return function (fn) {
  1228. _window.mozRequestAnimationFrame(fn);
  1229. };
  1230. } else if (_window.webkitRequestAnimationFrame) {
  1231. return function (fn) {
  1232. _window.webkitRequestAnimationFrame(fn);
  1233. };
  1234. } else if (_window.msRequestAnimationFrame) {
  1235. return function (fn) {
  1236. _window.msRequestAnimationFrame(fn);
  1237. };
  1238. }
  1239. }
  1240. return function (fn) {
  1241. if (fn) {
  1242. setTimeout(function () {
  1243. fn(pnow());
  1244. }, 1000 / 60);
  1245. }
  1246. };
  1247. }();
  1248. var requestAnimationFrame = function requestAnimationFrame(fn) {
  1249. return raf(fn);
  1250. };
  1251. var performanceNow = pnow;
  1252. var DEFAULT_HASH_SEED = 9261;
  1253. var K = 65599; // 37 also works pretty well
  1254. var DEFAULT_HASH_SEED_ALT = 5381;
  1255. var hashIterableInts = function hashIterableInts(iterator) {
  1256. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  1257. // sdbm/string-hash
  1258. var hash = seed;
  1259. var entry;
  1260. for (;;) {
  1261. entry = iterator.next();
  1262. if (entry.done) {
  1263. break;
  1264. }
  1265. hash = hash * K + entry.value | 0;
  1266. }
  1267. return hash;
  1268. };
  1269. var hashInt = function hashInt(num) {
  1270. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  1271. // sdbm/string-hash
  1272. return seed * K + num | 0;
  1273. };
  1274. var hashIntAlt = function hashIntAlt(num) {
  1275. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED_ALT;
  1276. // djb2/string-hash
  1277. return (seed << 5) + seed + num | 0;
  1278. };
  1279. var combineHashes = function combineHashes(hash1, hash2) {
  1280. return hash1 * 0x200000 + hash2;
  1281. };
  1282. var combineHashesArray = function combineHashesArray(hashes) {
  1283. return hashes[0] * 0x200000 + hashes[1];
  1284. };
  1285. var hashArrays = function hashArrays(hashes1, hashes2) {
  1286. return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];
  1287. };
  1288. var hashIntsArray = function hashIntsArray(ints, seed) {
  1289. var entry = {
  1290. value: 0,
  1291. done: false
  1292. };
  1293. var i = 0;
  1294. var length = ints.length;
  1295. var iterator = {
  1296. next: function next() {
  1297. if (i < length) {
  1298. entry.value = ints[i++];
  1299. } else {
  1300. entry.done = true;
  1301. }
  1302. return entry;
  1303. }
  1304. };
  1305. return hashIterableInts(iterator, seed);
  1306. };
  1307. var hashString = function hashString(str, seed) {
  1308. var entry = {
  1309. value: 0,
  1310. done: false
  1311. };
  1312. var i = 0;
  1313. var length = str.length;
  1314. var iterator = {
  1315. next: function next() {
  1316. if (i < length) {
  1317. entry.value = str.charCodeAt(i++);
  1318. } else {
  1319. entry.done = true;
  1320. }
  1321. return entry;
  1322. }
  1323. };
  1324. return hashIterableInts(iterator, seed);
  1325. };
  1326. var hashStrings = function hashStrings() {
  1327. return hashStringsArray(arguments);
  1328. };
  1329. var hashStringsArray = function hashStringsArray(strs) {
  1330. var hash;
  1331. for (var i = 0; i < strs.length; i++) {
  1332. var str = strs[i];
  1333. if (i === 0) {
  1334. hash = hashString(str);
  1335. } else {
  1336. hash = hashString(str, hash);
  1337. }
  1338. }
  1339. return hash;
  1340. };
  1341. function rotatePoint(x, y, centerX, centerY, angleDegrees) {
  1342. var angleRadians = angleDegrees * Math.PI / 180;
  1343. var rotatedX = Math.cos(angleRadians) * (x - centerX) - Math.sin(angleRadians) * (y - centerY) + centerX;
  1344. var rotatedY = Math.sin(angleRadians) * (x - centerX) + Math.cos(angleRadians) * (y - centerY) + centerY;
  1345. return {
  1346. x: rotatedX,
  1347. y: rotatedY
  1348. };
  1349. }
  1350. var movePointByBoxAspect = function movePointByBoxAspect(x, y, boxX, boxY, skewX, skewY) {
  1351. return {
  1352. x: (x - boxX) * skewX + boxX,
  1353. y: (y - boxY) * skewY + boxY
  1354. };
  1355. };
  1356. function rotatePosAndSkewByBox(pos, box, angleDegrees) {
  1357. if (angleDegrees === 0) return pos;
  1358. var centerX = (box.x1 + box.x2) / 2;
  1359. var centerY = (box.y1 + box.y2) / 2;
  1360. var skewX = box.w / box.h;
  1361. var skewY = 1 / skewX;
  1362. var rotated = rotatePoint(pos.x, pos.y, centerX, centerY, angleDegrees);
  1363. var skewed = movePointByBoxAspect(rotated.x, rotated.y, centerX, centerY, skewX, skewY);
  1364. return {
  1365. x: skewed.x,
  1366. y: skewed.y
  1367. };
  1368. }
  1369. var warningsEnabled = true;
  1370. var warnSupported = console.warn != null;
  1371. var traceSupported = console.trace != null;
  1372. var MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;
  1373. var trueify = function trueify() {
  1374. return true;
  1375. };
  1376. var falsify = function falsify() {
  1377. return false;
  1378. };
  1379. var zeroify = function zeroify() {
  1380. return 0;
  1381. };
  1382. var noop$1 = function noop() {};
  1383. var error = function error(msg) {
  1384. throw new Error(msg);
  1385. };
  1386. var warnings = function warnings(enabled) {
  1387. if (enabled !== undefined) {
  1388. warningsEnabled = !!enabled;
  1389. } else {
  1390. return warningsEnabled;
  1391. }
  1392. };
  1393. var warn = function warn(msg) {
  1394. if (!warnings()) {
  1395. return;
  1396. }
  1397. if (warnSupported) {
  1398. console.warn(msg);
  1399. } else {
  1400. console.log(msg);
  1401. if (traceSupported) {
  1402. console.trace();
  1403. }
  1404. }
  1405. };
  1406. var clone = function clone(obj) {
  1407. return extend({}, obj);
  1408. };
  1409. // gets a shallow copy of the argument
  1410. var copy = function copy(obj) {
  1411. if (obj == null) {
  1412. return obj;
  1413. }
  1414. if (array(obj)) {
  1415. return obj.slice();
  1416. } else if (plainObject(obj)) {
  1417. return clone(obj);
  1418. } else {
  1419. return obj;
  1420. }
  1421. };
  1422. var copyArray = function copyArray(arr) {
  1423. return arr.slice();
  1424. };
  1425. var uuid = function uuid(a, b /* placeholders */) {
  1426. for (
  1427. // loop :)
  1428. b = a = '';
  1429. // b - result , a - numeric letiable
  1430. a++ < 36;
  1431. //
  1432. b += a * 51 & 52 // if "a" is not 9 or 14 or 19 or 24
  1433. ?
  1434. // return a random number or 4
  1435. (a ^ 15 // if "a" is not 15
  1436. ?
  1437. // generate a random number from 0 to 15
  1438. 8 ^ Math.random() * (a ^ 20 ? 16 : 4) // unless "a" is 20, in which case a random number from 8 to 11
  1439. : 4 // otherwise 4
  1440. ).toString(16) : '-' // in other cases (if "a" is 9,14,19,24) insert "-"
  1441. );
  1442. return b;
  1443. };
  1444. var _staticEmptyObject = {};
  1445. var staticEmptyObject = function staticEmptyObject() {
  1446. return _staticEmptyObject;
  1447. };
  1448. var defaults$g = function defaults(_defaults) {
  1449. var keys = Object.keys(_defaults);
  1450. return function (opts) {
  1451. var filledOpts = {};
  1452. for (var i = 0; i < keys.length; i++) {
  1453. var key = keys[i];
  1454. var optVal = opts == null ? undefined : opts[key];
  1455. filledOpts[key] = optVal === undefined ? _defaults[key] : optVal;
  1456. }
  1457. return filledOpts;
  1458. };
  1459. };
  1460. var removeFromArray = function removeFromArray(arr, ele, oneCopy) {
  1461. for (var i = arr.length - 1; i >= 0; i--) {
  1462. if (arr[i] === ele) {
  1463. arr.splice(i, 1);
  1464. }
  1465. }
  1466. };
  1467. var clearArray = function clearArray(arr) {
  1468. arr.splice(0, arr.length);
  1469. };
  1470. var push = function push(arr, otherArr) {
  1471. for (var i = 0; i < otherArr.length; i++) {
  1472. var el = otherArr[i];
  1473. arr.push(el);
  1474. }
  1475. };
  1476. var getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {
  1477. if (prefix) {
  1478. propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  1479. }
  1480. return obj[propName];
  1481. };
  1482. var setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {
  1483. if (prefix) {
  1484. propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  1485. }
  1486. obj[propName] = value;
  1487. };
  1488. /* global Map */
  1489. var ObjectMap = /*#__PURE__*/function () {
  1490. function ObjectMap() {
  1491. _classCallCheck(this, ObjectMap);
  1492. this._obj = {};
  1493. }
  1494. return _createClass(ObjectMap, [{
  1495. key: "set",
  1496. value: function set(key, val) {
  1497. this._obj[key] = val;
  1498. return this;
  1499. }
  1500. }, {
  1501. key: "delete",
  1502. value: function _delete(key) {
  1503. this._obj[key] = undefined;
  1504. return this;
  1505. }
  1506. }, {
  1507. key: "clear",
  1508. value: function clear() {
  1509. this._obj = {};
  1510. }
  1511. }, {
  1512. key: "has",
  1513. value: function has(key) {
  1514. return this._obj[key] !== undefined;
  1515. }
  1516. }, {
  1517. key: "get",
  1518. value: function get(key) {
  1519. return this._obj[key];
  1520. }
  1521. }]);
  1522. }();
  1523. var Map$1 = typeof Map !== 'undefined' ? Map : ObjectMap;
  1524. /* global Set */
  1525. var undef = "undefined" ;
  1526. var ObjectSet = /*#__PURE__*/function () {
  1527. function ObjectSet(arrayOrObjectSet) {
  1528. _classCallCheck(this, ObjectSet);
  1529. this._obj = Object.create(null);
  1530. this.size = 0;
  1531. if (arrayOrObjectSet != null) {
  1532. var arr;
  1533. if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {
  1534. arr = arrayOrObjectSet.toArray();
  1535. } else {
  1536. arr = arrayOrObjectSet;
  1537. }
  1538. for (var i = 0; i < arr.length; i++) {
  1539. this.add(arr[i]);
  1540. }
  1541. }
  1542. }
  1543. return _createClass(ObjectSet, [{
  1544. key: "instanceString",
  1545. value: function instanceString() {
  1546. return 'set';
  1547. }
  1548. }, {
  1549. key: "add",
  1550. value: function add(val) {
  1551. var o = this._obj;
  1552. if (o[val] !== 1) {
  1553. o[val] = 1;
  1554. this.size++;
  1555. }
  1556. }
  1557. }, {
  1558. key: "delete",
  1559. value: function _delete(val) {
  1560. var o = this._obj;
  1561. if (o[val] === 1) {
  1562. o[val] = 0;
  1563. this.size--;
  1564. }
  1565. }
  1566. }, {
  1567. key: "clear",
  1568. value: function clear() {
  1569. this._obj = Object.create(null);
  1570. }
  1571. }, {
  1572. key: "has",
  1573. value: function has(val) {
  1574. return this._obj[val] === 1;
  1575. }
  1576. }, {
  1577. key: "toArray",
  1578. value: function toArray() {
  1579. var _this = this;
  1580. return Object.keys(this._obj).filter(function (key) {
  1581. return _this.has(key);
  1582. });
  1583. }
  1584. }, {
  1585. key: "forEach",
  1586. value: function forEach(callback, thisArg) {
  1587. return this.toArray().forEach(callback, thisArg);
  1588. }
  1589. }]);
  1590. }();
  1591. var Set$1 = (typeof Set === "undefined" ? "undefined" : _typeof(Set)) !== undef ? Set : ObjectSet;
  1592. // represents a node or an edge
  1593. var Element = function Element(cy, params) {
  1594. var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  1595. if (cy === undefined || params === undefined || !core(cy)) {
  1596. error('An element must have a core reference and parameters set');
  1597. return;
  1598. }
  1599. var group = params.group;
  1600. // try to automatically infer the group if unspecified
  1601. if (group == null) {
  1602. if (params.data && params.data.source != null && params.data.target != null) {
  1603. group = 'edges';
  1604. } else {
  1605. group = 'nodes';
  1606. }
  1607. }
  1608. // validate group
  1609. if (group !== 'nodes' && group !== 'edges') {
  1610. error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');
  1611. return;
  1612. }
  1613. // make the element array-like, just like a collection
  1614. this.length = 1;
  1615. this[0] = this;
  1616. // NOTE: when something is added here, add also to ele.json()
  1617. var _p = this._private = {
  1618. cy: cy,
  1619. single: true,
  1620. // indicates this is an element
  1621. data: params.data || {},
  1622. // data object
  1623. position: params.position || {
  1624. x: 0,
  1625. y: 0
  1626. },
  1627. // (x, y) position pair
  1628. autoWidth: undefined,
  1629. // width and height of nodes calculated by the renderer when set to special 'auto' value
  1630. autoHeight: undefined,
  1631. autoPadding: undefined,
  1632. compoundBoundsClean: false,
  1633. // whether the compound dimensions need to be recalculated the next time dimensions are read
  1634. listeners: [],
  1635. // array of bound listeners
  1636. group: group,
  1637. // string; 'nodes' or 'edges'
  1638. style: {},
  1639. // properties as set by the style
  1640. rstyle: {},
  1641. // properties for style sent from the renderer to the core
  1642. styleCxts: [],
  1643. // applied style contexts from the styler
  1644. styleKeys: {},
  1645. // per-group keys of style property values
  1646. removed: true,
  1647. // whether it's inside the vis; true if removed (set true here since we call restore)
  1648. selected: params.selected ? true : false,
  1649. // whether it's selected
  1650. selectable: params.selectable === undefined ? true : params.selectable ? true : false,
  1651. // whether it's selectable
  1652. locked: params.locked ? true : false,
  1653. // whether the element is locked (cannot be moved)
  1654. grabbed: false,
  1655. // whether the element is grabbed by the mouse; renderer sets this privately
  1656. grabbable: params.grabbable === undefined ? true : params.grabbable ? true : false,
  1657. // whether the element can be grabbed
  1658. pannable: params.pannable === undefined ? group === 'edges' ? true : false : params.pannable ? true : false,
  1659. // whether the element has passthrough panning enabled
  1660. active: false,
  1661. // whether the element is active from user interaction
  1662. classes: new Set$1(),
  1663. // map ( className => true )
  1664. animation: {
  1665. // object for currently-running animations
  1666. current: [],
  1667. queue: []
  1668. },
  1669. rscratch: {},
  1670. // object in which the renderer can store information
  1671. scratch: params.scratch || {},
  1672. // scratch objects
  1673. edges: [],
  1674. // array of connected edges
  1675. children: [],
  1676. // array of children
  1677. parent: params.parent && params.parent.isNode() ? params.parent : null,
  1678. // parent ref
  1679. traversalCache: {},
  1680. // cache of output of traversal functions
  1681. backgrounding: false,
  1682. // whether background images are loading
  1683. bbCache: null,
  1684. // cache of the current bounding box
  1685. bbCacheShift: {
  1686. x: 0,
  1687. y: 0
  1688. },
  1689. // shift applied to cached bb to be applied on next get
  1690. bodyBounds: null,
  1691. // bounds cache of element body, w/o overlay
  1692. overlayBounds: null,
  1693. // bounds cache of element body, including overlay
  1694. labelBounds: {
  1695. // bounds cache of labels
  1696. all: null,
  1697. source: null,
  1698. target: null,
  1699. main: null
  1700. },
  1701. arrowBounds: {
  1702. // bounds cache of edge arrows
  1703. source: null,
  1704. target: null,
  1705. 'mid-source': null,
  1706. 'mid-target': null
  1707. }
  1708. };
  1709. if (_p.position.x == null) {
  1710. _p.position.x = 0;
  1711. }
  1712. if (_p.position.y == null) {
  1713. _p.position.y = 0;
  1714. }
  1715. // renderedPosition overrides if specified
  1716. if (params.renderedPosition) {
  1717. var rpos = params.renderedPosition;
  1718. var pan = cy.pan();
  1719. var zoom = cy.zoom();
  1720. _p.position = {
  1721. x: (rpos.x - pan.x) / zoom,
  1722. y: (rpos.y - pan.y) / zoom
  1723. };
  1724. }
  1725. var classes = [];
  1726. if (array(params.classes)) {
  1727. classes = params.classes;
  1728. } else if (string(params.classes)) {
  1729. classes = params.classes.split(/\s+/);
  1730. }
  1731. for (var i = 0, l = classes.length; i < l; i++) {
  1732. var cls = classes[i];
  1733. if (!cls || cls === '') {
  1734. continue;
  1735. }
  1736. _p.classes.add(cls);
  1737. }
  1738. this.createEmitter();
  1739. if (restore === undefined || restore) {
  1740. this.restore();
  1741. }
  1742. var bypass = params.style || params.css;
  1743. if (bypass) {
  1744. warn('Setting a `style` bypass at element creation should be done only when absolutely necessary. Try to use the stylesheet instead.');
  1745. this.style(bypass);
  1746. }
  1747. };
  1748. var defineSearch = function defineSearch(params) {
  1749. params = {
  1750. bfs: params.bfs || !params.dfs,
  1751. dfs: params.dfs || !params.bfs
  1752. };
  1753. // from pseudocode on wikipedia
  1754. return function searchFn(roots, fn, directed) {
  1755. var options;
  1756. if (plainObject(roots) && !elementOrCollection(roots)) {
  1757. options = roots;
  1758. roots = options.roots || options.root;
  1759. fn = options.visit;
  1760. directed = options.directed;
  1761. }
  1762. directed = arguments.length === 2 && !fn$6(fn) ? fn : directed;
  1763. fn = fn$6(fn) ? fn : function () {};
  1764. var cy = this._private.cy;
  1765. var v = roots = string(roots) ? this.filter(roots) : roots;
  1766. var Q = [];
  1767. var connectedNodes = [];
  1768. var connectedBy = {};
  1769. var id2depth = {};
  1770. var V = {};
  1771. var j = 0;
  1772. var found;
  1773. var _this$byGroup = this.byGroup(),
  1774. nodes = _this$byGroup.nodes,
  1775. edges = _this$byGroup.edges;
  1776. // enqueue v
  1777. for (var i = 0; i < v.length; i++) {
  1778. var vi = v[i];
  1779. var viId = vi.id();
  1780. if (vi.isNode()) {
  1781. Q.unshift(vi);
  1782. if (params.bfs) {
  1783. V[viId] = true;
  1784. connectedNodes.push(vi);
  1785. }
  1786. id2depth[viId] = 0;
  1787. }
  1788. }
  1789. var _loop = function _loop() {
  1790. var v = params.bfs ? Q.shift() : Q.pop();
  1791. var vId = v.id();
  1792. if (params.dfs) {
  1793. if (V[vId]) {
  1794. return 0; // continue
  1795. }
  1796. V[vId] = true;
  1797. connectedNodes.push(v);
  1798. }
  1799. var depth = id2depth[vId];
  1800. var prevEdge = connectedBy[vId];
  1801. var src = prevEdge != null ? prevEdge.source() : null;
  1802. var tgt = prevEdge != null ? prevEdge.target() : null;
  1803. var prevNode = prevEdge == null ? undefined : v.same(src) ? tgt[0] : src[0];
  1804. var ret;
  1805. ret = fn(v, prevEdge, prevNode, j++, depth);
  1806. if (ret === true) {
  1807. found = v;
  1808. return 1; // break
  1809. }
  1810. if (ret === false) {
  1811. return 1; // break
  1812. }
  1813. var vwEdges = v.connectedEdges().filter(function (e) {
  1814. return (!directed || e.source().same(v)) && edges.has(e);
  1815. });
  1816. for (var _i2 = 0; _i2 < vwEdges.length; _i2++) {
  1817. var e = vwEdges[_i2];
  1818. var w = e.connectedNodes().filter(function (n) {
  1819. return !n.same(v) && nodes.has(n);
  1820. });
  1821. var wId = w.id();
  1822. if (w.length !== 0 && !V[wId]) {
  1823. w = w[0];
  1824. Q.push(w);
  1825. if (params.bfs) {
  1826. V[wId] = true;
  1827. connectedNodes.push(w);
  1828. }
  1829. connectedBy[wId] = e;
  1830. id2depth[wId] = id2depth[vId] + 1;
  1831. }
  1832. }
  1833. },
  1834. _ret;
  1835. while (Q.length !== 0) {
  1836. _ret = _loop();
  1837. if (_ret === 0) continue;
  1838. if (_ret === 1) break;
  1839. }
  1840. var connectedEles = cy.collection();
  1841. for (var _i = 0; _i < connectedNodes.length; _i++) {
  1842. var node = connectedNodes[_i];
  1843. var edge = connectedBy[node.id()];
  1844. if (edge != null) {
  1845. connectedEles.push(edge);
  1846. }
  1847. connectedEles.push(node);
  1848. }
  1849. return {
  1850. path: cy.collection(connectedEles),
  1851. found: cy.collection(found)
  1852. };
  1853. };
  1854. };
  1855. // search, spanning trees, etc
  1856. var elesfn$v = {
  1857. breadthFirstSearch: defineSearch({
  1858. bfs: true
  1859. }),
  1860. depthFirstSearch: defineSearch({
  1861. dfs: true
  1862. })
  1863. };
  1864. // nice, short mathematical alias
  1865. elesfn$v.bfs = elesfn$v.breadthFirstSearch;
  1866. elesfn$v.dfs = elesfn$v.depthFirstSearch;
  1867. var heap$2 = {exports: {}};
  1868. var heap$1 = heap$2.exports;
  1869. var hasRequiredHeap$1;
  1870. function requireHeap$1 () {
  1871. if (hasRequiredHeap$1) return heap$2.exports;
  1872. hasRequiredHeap$1 = 1;
  1873. (function (module, exports) {
  1874. // Generated by CoffeeScript 1.8.0
  1875. (function() {
  1876. var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
  1877. floor = Math.floor, min = Math.min;
  1878. /*
  1879. Default comparison function to be used
  1880. */
  1881. defaultCmp = function(x, y) {
  1882. if (x < y) {
  1883. return -1;
  1884. }
  1885. if (x > y) {
  1886. return 1;
  1887. }
  1888. return 0;
  1889. };
  1890. /*
  1891. Insert item x in list a, and keep it sorted assuming a is sorted.
  1892. If x is already in a, insert it to the right of the rightmost x.
  1893. Optional args lo (default 0) and hi (default a.length) bound the slice
  1894. of a to be searched.
  1895. */
  1896. insort = function(a, x, lo, hi, cmp) {
  1897. var mid;
  1898. if (lo == null) {
  1899. lo = 0;
  1900. }
  1901. if (cmp == null) {
  1902. cmp = defaultCmp;
  1903. }
  1904. if (lo < 0) {
  1905. throw new Error('lo must be non-negative');
  1906. }
  1907. if (hi == null) {
  1908. hi = a.length;
  1909. }
  1910. while (lo < hi) {
  1911. mid = floor((lo + hi) / 2);
  1912. if (cmp(x, a[mid]) < 0) {
  1913. hi = mid;
  1914. } else {
  1915. lo = mid + 1;
  1916. }
  1917. }
  1918. return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
  1919. };
  1920. /*
  1921. Push item onto heap, maintaining the heap invariant.
  1922. */
  1923. heappush = function(array, item, cmp) {
  1924. if (cmp == null) {
  1925. cmp = defaultCmp;
  1926. }
  1927. array.push(item);
  1928. return _siftdown(array, 0, array.length - 1, cmp);
  1929. };
  1930. /*
  1931. Pop the smallest item off the heap, maintaining the heap invariant.
  1932. */
  1933. heappop = function(array, cmp) {
  1934. var lastelt, returnitem;
  1935. if (cmp == null) {
  1936. cmp = defaultCmp;
  1937. }
  1938. lastelt = array.pop();
  1939. if (array.length) {
  1940. returnitem = array[0];
  1941. array[0] = lastelt;
  1942. _siftup(array, 0, cmp);
  1943. } else {
  1944. returnitem = lastelt;
  1945. }
  1946. return returnitem;
  1947. };
  1948. /*
  1949. Pop and return the current smallest value, and add the new item.
  1950. This is more efficient than heappop() followed by heappush(), and can be
  1951. more appropriate when using a fixed size heap. Note that the value
  1952. returned may be larger than item! That constrains reasonable use of
  1953. this routine unless written as part of a conditional replacement:
  1954. if item > array[0]
  1955. item = heapreplace(array, item)
  1956. */
  1957. heapreplace = function(array, item, cmp) {
  1958. var returnitem;
  1959. if (cmp == null) {
  1960. cmp = defaultCmp;
  1961. }
  1962. returnitem = array[0];
  1963. array[0] = item;
  1964. _siftup(array, 0, cmp);
  1965. return returnitem;
  1966. };
  1967. /*
  1968. Fast version of a heappush followed by a heappop.
  1969. */
  1970. heappushpop = function(array, item, cmp) {
  1971. var _ref;
  1972. if (cmp == null) {
  1973. cmp = defaultCmp;
  1974. }
  1975. if (array.length && cmp(array[0], item) < 0) {
  1976. _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
  1977. _siftup(array, 0, cmp);
  1978. }
  1979. return item;
  1980. };
  1981. /*
  1982. Transform list into a heap, in-place, in O(array.length) time.
  1983. */
  1984. heapify = function(array, cmp) {
  1985. var i, _i, _len, _ref1, _results, _results1;
  1986. if (cmp == null) {
  1987. cmp = defaultCmp;
  1988. }
  1989. _ref1 = (function() {
  1990. _results1 = [];
  1991. for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
  1992. return _results1;
  1993. }).apply(this).reverse();
  1994. _results = [];
  1995. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  1996. i = _ref1[_i];
  1997. _results.push(_siftup(array, i, cmp));
  1998. }
  1999. return _results;
  2000. };
  2001. /*
  2002. Update the position of the given item in the heap.
  2003. This function should be called every time the item is being modified.
  2004. */
  2005. updateItem = function(array, item, cmp) {
  2006. var pos;
  2007. if (cmp == null) {
  2008. cmp = defaultCmp;
  2009. }
  2010. pos = array.indexOf(item);
  2011. if (pos === -1) {
  2012. return;
  2013. }
  2014. _siftdown(array, 0, pos, cmp);
  2015. return _siftup(array, pos, cmp);
  2016. };
  2017. /*
  2018. Find the n largest elements in a dataset.
  2019. */
  2020. nlargest = function(array, n, cmp) {
  2021. var elem, result, _i, _len, _ref;
  2022. if (cmp == null) {
  2023. cmp = defaultCmp;
  2024. }
  2025. result = array.slice(0, n);
  2026. if (!result.length) {
  2027. return result;
  2028. }
  2029. heapify(result, cmp);
  2030. _ref = array.slice(n);
  2031. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2032. elem = _ref[_i];
  2033. heappushpop(result, elem, cmp);
  2034. }
  2035. return result.sort(cmp).reverse();
  2036. };
  2037. /*
  2038. Find the n smallest elements in a dataset.
  2039. */
  2040. nsmallest = function(array, n, cmp) {
  2041. var elem, los, result, _i, _j, _len, _ref, _ref1, _results;
  2042. if (cmp == null) {
  2043. cmp = defaultCmp;
  2044. }
  2045. if (n * 10 <= array.length) {
  2046. result = array.slice(0, n).sort(cmp);
  2047. if (!result.length) {
  2048. return result;
  2049. }
  2050. los = result[result.length - 1];
  2051. _ref = array.slice(n);
  2052. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2053. elem = _ref[_i];
  2054. if (cmp(elem, los) < 0) {
  2055. insort(result, elem, 0, null, cmp);
  2056. result.pop();
  2057. los = result[result.length - 1];
  2058. }
  2059. }
  2060. return result;
  2061. }
  2062. heapify(array, cmp);
  2063. _results = [];
  2064. for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {
  2065. _results.push(heappop(array, cmp));
  2066. }
  2067. return _results;
  2068. };
  2069. _siftdown = function(array, startpos, pos, cmp) {
  2070. var newitem, parent, parentpos;
  2071. if (cmp == null) {
  2072. cmp = defaultCmp;
  2073. }
  2074. newitem = array[pos];
  2075. while (pos > startpos) {
  2076. parentpos = (pos - 1) >> 1;
  2077. parent = array[parentpos];
  2078. if (cmp(newitem, parent) < 0) {
  2079. array[pos] = parent;
  2080. pos = parentpos;
  2081. continue;
  2082. }
  2083. break;
  2084. }
  2085. return array[pos] = newitem;
  2086. };
  2087. _siftup = function(array, pos, cmp) {
  2088. var childpos, endpos, newitem, rightpos, startpos;
  2089. if (cmp == null) {
  2090. cmp = defaultCmp;
  2091. }
  2092. endpos = array.length;
  2093. startpos = pos;
  2094. newitem = array[pos];
  2095. childpos = 2 * pos + 1;
  2096. while (childpos < endpos) {
  2097. rightpos = childpos + 1;
  2098. if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
  2099. childpos = rightpos;
  2100. }
  2101. array[pos] = array[childpos];
  2102. pos = childpos;
  2103. childpos = 2 * pos + 1;
  2104. }
  2105. array[pos] = newitem;
  2106. return _siftdown(array, startpos, pos, cmp);
  2107. };
  2108. Heap = (function() {
  2109. Heap.push = heappush;
  2110. Heap.pop = heappop;
  2111. Heap.replace = heapreplace;
  2112. Heap.pushpop = heappushpop;
  2113. Heap.heapify = heapify;
  2114. Heap.updateItem = updateItem;
  2115. Heap.nlargest = nlargest;
  2116. Heap.nsmallest = nsmallest;
  2117. function Heap(cmp) {
  2118. this.cmp = cmp != null ? cmp : defaultCmp;
  2119. this.nodes = [];
  2120. }
  2121. Heap.prototype.push = function(x) {
  2122. return heappush(this.nodes, x, this.cmp);
  2123. };
  2124. Heap.prototype.pop = function() {
  2125. return heappop(this.nodes, this.cmp);
  2126. };
  2127. Heap.prototype.peek = function() {
  2128. return this.nodes[0];
  2129. };
  2130. Heap.prototype.contains = function(x) {
  2131. return this.nodes.indexOf(x) !== -1;
  2132. };
  2133. Heap.prototype.replace = function(x) {
  2134. return heapreplace(this.nodes, x, this.cmp);
  2135. };
  2136. Heap.prototype.pushpop = function(x) {
  2137. return heappushpop(this.nodes, x, this.cmp);
  2138. };
  2139. Heap.prototype.heapify = function() {
  2140. return heapify(this.nodes, this.cmp);
  2141. };
  2142. Heap.prototype.updateItem = function(x) {
  2143. return updateItem(this.nodes, x, this.cmp);
  2144. };
  2145. Heap.prototype.clear = function() {
  2146. return this.nodes = [];
  2147. };
  2148. Heap.prototype.empty = function() {
  2149. return this.nodes.length === 0;
  2150. };
  2151. Heap.prototype.size = function() {
  2152. return this.nodes.length;
  2153. };
  2154. Heap.prototype.clone = function() {
  2155. var heap;
  2156. heap = new Heap();
  2157. heap.nodes = this.nodes.slice(0);
  2158. return heap;
  2159. };
  2160. Heap.prototype.toArray = function() {
  2161. return this.nodes.slice(0);
  2162. };
  2163. Heap.prototype.insert = Heap.prototype.push;
  2164. Heap.prototype.top = Heap.prototype.peek;
  2165. Heap.prototype.front = Heap.prototype.peek;
  2166. Heap.prototype.has = Heap.prototype.contains;
  2167. Heap.prototype.copy = Heap.prototype.clone;
  2168. return Heap;
  2169. })();
  2170. (function(root, factory) {
  2171. {
  2172. return module.exports = factory();
  2173. }
  2174. })(this, function() {
  2175. return Heap;
  2176. });
  2177. }).call(heap$1);
  2178. } (heap$2));
  2179. return heap$2.exports;
  2180. }
  2181. var heap;
  2182. var hasRequiredHeap;
  2183. function requireHeap () {
  2184. if (hasRequiredHeap) return heap;
  2185. hasRequiredHeap = 1;
  2186. heap = requireHeap$1();
  2187. return heap;
  2188. }
  2189. var heapExports = requireHeap();
  2190. var Heap = /*@__PURE__*/getDefaultExportFromCjs(heapExports);
  2191. var dijkstraDefaults = defaults$g({
  2192. root: null,
  2193. weight: function weight(edge) {
  2194. return 1;
  2195. },
  2196. directed: false
  2197. });
  2198. var elesfn$u = {
  2199. dijkstra: function dijkstra(options) {
  2200. if (!plainObject(options)) {
  2201. var args = arguments;
  2202. options = {
  2203. root: args[0],
  2204. weight: args[1],
  2205. directed: args[2]
  2206. };
  2207. }
  2208. var _dijkstraDefaults = dijkstraDefaults(options),
  2209. root = _dijkstraDefaults.root,
  2210. weight = _dijkstraDefaults.weight,
  2211. directed = _dijkstraDefaults.directed;
  2212. var eles = this;
  2213. var weightFn = weight;
  2214. var source = string(root) ? this.filter(root)[0] : root[0];
  2215. var dist = {};
  2216. var prev = {};
  2217. var knownDist = {};
  2218. var _this$byGroup = this.byGroup(),
  2219. nodes = _this$byGroup.nodes,
  2220. edges = _this$byGroup.edges;
  2221. edges.unmergeBy(function (ele) {
  2222. return ele.isLoop();
  2223. });
  2224. var getDist = function getDist(node) {
  2225. return dist[node.id()];
  2226. };
  2227. var setDist = function setDist(node, d) {
  2228. dist[node.id()] = d;
  2229. Q.updateItem(node);
  2230. };
  2231. var Q = new Heap(function (a, b) {
  2232. return getDist(a) - getDist(b);
  2233. });
  2234. for (var i = 0; i < nodes.length; i++) {
  2235. var node = nodes[i];
  2236. dist[node.id()] = node.same(source) ? 0 : Infinity;
  2237. Q.push(node);
  2238. }
  2239. var distBetween = function distBetween(u, v) {
  2240. var uvs = (directed ? u.edgesTo(v) : u.edgesWith(v)).intersect(edges);
  2241. var smallestDistance = Infinity;
  2242. var smallestEdge;
  2243. for (var _i = 0; _i < uvs.length; _i++) {
  2244. var edge = uvs[_i];
  2245. var _weight = weightFn(edge);
  2246. if (_weight < smallestDistance || !smallestEdge) {
  2247. smallestDistance = _weight;
  2248. smallestEdge = edge;
  2249. }
  2250. }
  2251. return {
  2252. edge: smallestEdge,
  2253. dist: smallestDistance
  2254. };
  2255. };
  2256. while (Q.size() > 0) {
  2257. var u = Q.pop();
  2258. var smalletsDist = getDist(u);
  2259. var uid = u.id();
  2260. knownDist[uid] = smalletsDist;
  2261. if (smalletsDist === Infinity) {
  2262. continue;
  2263. }
  2264. var neighbors = u.neighborhood().intersect(nodes);
  2265. for (var _i2 = 0; _i2 < neighbors.length; _i2++) {
  2266. var v = neighbors[_i2];
  2267. var vid = v.id();
  2268. var vDist = distBetween(u, v);
  2269. var alt = smalletsDist + vDist.dist;
  2270. if (alt < getDist(v)) {
  2271. setDist(v, alt);
  2272. prev[vid] = {
  2273. node: u,
  2274. edge: vDist.edge
  2275. };
  2276. }
  2277. } // for
  2278. } // while
  2279. return {
  2280. distanceTo: function distanceTo(node) {
  2281. var target = string(node) ? nodes.filter(node)[0] : node[0];
  2282. return knownDist[target.id()];
  2283. },
  2284. pathTo: function pathTo(node) {
  2285. var target = string(node) ? nodes.filter(node)[0] : node[0];
  2286. var S = [];
  2287. var u = target;
  2288. var uid = u.id();
  2289. if (target.length > 0) {
  2290. S.unshift(target);
  2291. while (prev[uid]) {
  2292. var p = prev[uid];
  2293. S.unshift(p.edge);
  2294. S.unshift(p.node);
  2295. u = p.node;
  2296. uid = u.id();
  2297. }
  2298. }
  2299. return eles.spawn(S);
  2300. }
  2301. };
  2302. }
  2303. };
  2304. var elesfn$t = {
  2305. // kruskal's algorithm (finds min spanning tree, assuming undirected graph)
  2306. // implemented from pseudocode from wikipedia
  2307. kruskal: function kruskal(weightFn) {
  2308. weightFn = weightFn || function (edge) {
  2309. return 1;
  2310. };
  2311. var _this$byGroup = this.byGroup(),
  2312. nodes = _this$byGroup.nodes,
  2313. edges = _this$byGroup.edges;
  2314. var numNodes = nodes.length;
  2315. var forest = new Array(numNodes);
  2316. var A = nodes; // assumes byGroup() creates new collections that can be safely mutated
  2317. var findSetIndex = function findSetIndex(ele) {
  2318. for (var i = 0; i < forest.length; i++) {
  2319. var eles = forest[i];
  2320. if (eles.has(ele)) {
  2321. return i;
  2322. }
  2323. }
  2324. };
  2325. // start with one forest per node
  2326. for (var i = 0; i < numNodes; i++) {
  2327. forest[i] = this.spawn(nodes[i]);
  2328. }
  2329. var S = edges.sort(function (a, b) {
  2330. return weightFn(a) - weightFn(b);
  2331. });
  2332. for (var _i = 0; _i < S.length; _i++) {
  2333. var edge = S[_i];
  2334. var u = edge.source()[0];
  2335. var v = edge.target()[0];
  2336. var setUIndex = findSetIndex(u);
  2337. var setVIndex = findSetIndex(v);
  2338. var setU = forest[setUIndex];
  2339. var setV = forest[setVIndex];
  2340. if (setUIndex !== setVIndex) {
  2341. A.merge(edge);
  2342. // combine forests for u and v
  2343. setU.merge(setV);
  2344. forest.splice(setVIndex, 1);
  2345. }
  2346. }
  2347. return A;
  2348. }
  2349. };
  2350. var aStarDefaults = defaults$g({
  2351. root: null,
  2352. goal: null,
  2353. weight: function weight(edge) {
  2354. return 1;
  2355. },
  2356. heuristic: function heuristic(edge) {
  2357. return 0;
  2358. },
  2359. directed: false
  2360. });
  2361. var elesfn$s = {
  2362. // Implemented from pseudocode from wikipedia
  2363. aStar: function aStar(options) {
  2364. var cy = this.cy();
  2365. var _aStarDefaults = aStarDefaults(options),
  2366. root = _aStarDefaults.root,
  2367. goal = _aStarDefaults.goal,
  2368. heuristic = _aStarDefaults.heuristic,
  2369. directed = _aStarDefaults.directed,
  2370. weight = _aStarDefaults.weight;
  2371. root = cy.collection(root)[0];
  2372. goal = cy.collection(goal)[0];
  2373. var sid = root.id();
  2374. var tid = goal.id();
  2375. var gScore = {};
  2376. var fScore = {};
  2377. var closedSetIds = {};
  2378. var openSet = new Heap(function (a, b) {
  2379. return fScore[a.id()] - fScore[b.id()];
  2380. });
  2381. var openSetIds = new Set$1();
  2382. var cameFrom = {};
  2383. var cameFromEdge = {};
  2384. var addToOpenSet = function addToOpenSet(ele, id) {
  2385. openSet.push(ele);
  2386. openSetIds.add(id);
  2387. };
  2388. var cMin, cMinId;
  2389. var popFromOpenSet = function popFromOpenSet() {
  2390. cMin = openSet.pop();
  2391. cMinId = cMin.id();
  2392. openSetIds["delete"](cMinId);
  2393. };
  2394. var isInOpenSet = function isInOpenSet(id) {
  2395. return openSetIds.has(id);
  2396. };
  2397. addToOpenSet(root, sid);
  2398. gScore[sid] = 0;
  2399. fScore[sid] = heuristic(root);
  2400. // Counter
  2401. var steps = 0;
  2402. // Main loop
  2403. while (openSet.size() > 0) {
  2404. popFromOpenSet();
  2405. steps++;
  2406. // If we've found our goal, then we are done
  2407. if (cMinId === tid) {
  2408. var path = [];
  2409. var pathNode = goal;
  2410. var pathNodeId = tid;
  2411. var pathEdge = cameFromEdge[pathNodeId];
  2412. for (;;) {
  2413. path.unshift(pathNode);
  2414. if (pathEdge != null) {
  2415. path.unshift(pathEdge);
  2416. }
  2417. pathNode = cameFrom[pathNodeId];
  2418. if (pathNode == null) {
  2419. break;
  2420. }
  2421. pathNodeId = pathNode.id();
  2422. pathEdge = cameFromEdge[pathNodeId];
  2423. }
  2424. return {
  2425. found: true,
  2426. distance: gScore[cMinId],
  2427. path: this.spawn(path),
  2428. steps: steps
  2429. };
  2430. }
  2431. // Add cMin to processed nodes
  2432. closedSetIds[cMinId] = true;
  2433. // Update scores for neighbors of cMin
  2434. // Take into account if graph is directed or not
  2435. var vwEdges = cMin._private.edges;
  2436. for (var i = 0; i < vwEdges.length; i++) {
  2437. var e = vwEdges[i];
  2438. // edge must be in set of calling eles
  2439. if (!this.hasElementWithId(e.id())) {
  2440. continue;
  2441. }
  2442. // cMin must be the source of edge if directed
  2443. if (directed && e.data('source') !== cMinId) {
  2444. continue;
  2445. }
  2446. var wSrc = e.source();
  2447. var wTgt = e.target();
  2448. var w = wSrc.id() !== cMinId ? wSrc : wTgt;
  2449. var wid = w.id();
  2450. // node must be in set of calling eles
  2451. if (!this.hasElementWithId(wid)) {
  2452. continue;
  2453. }
  2454. // if node is in closedSet, ignore it
  2455. if (closedSetIds[wid]) {
  2456. continue;
  2457. }
  2458. // New tentative score for node w
  2459. var tempScore = gScore[cMinId] + weight(e);
  2460. // Update gScore for node w if:
  2461. // w not present in openSet
  2462. // OR
  2463. // tentative gScore is less than previous value
  2464. // w not in openSet
  2465. if (!isInOpenSet(wid)) {
  2466. gScore[wid] = tempScore;
  2467. fScore[wid] = tempScore + heuristic(w);
  2468. addToOpenSet(w, wid);
  2469. cameFrom[wid] = cMin;
  2470. cameFromEdge[wid] = e;
  2471. continue;
  2472. }
  2473. // w already in openSet, but with greater gScore
  2474. if (tempScore < gScore[wid]) {
  2475. gScore[wid] = tempScore;
  2476. fScore[wid] = tempScore + heuristic(w);
  2477. cameFrom[wid] = cMin;
  2478. cameFromEdge[wid] = e;
  2479. }
  2480. } // End of neighbors update
  2481. } // End of main loop
  2482. // If we've reached here, then we've not reached our goal
  2483. return {
  2484. found: false,
  2485. distance: undefined,
  2486. path: undefined,
  2487. steps: steps
  2488. };
  2489. }
  2490. }; // elesfn
  2491. var floydWarshallDefaults = defaults$g({
  2492. weight: function weight(edge) {
  2493. return 1;
  2494. },
  2495. directed: false
  2496. });
  2497. var elesfn$r = {
  2498. // Implemented from pseudocode from wikipedia
  2499. floydWarshall: function floydWarshall(options) {
  2500. var cy = this.cy();
  2501. var _floydWarshallDefault = floydWarshallDefaults(options),
  2502. weight = _floydWarshallDefault.weight,
  2503. directed = _floydWarshallDefault.directed;
  2504. var weightFn = weight;
  2505. var _this$byGroup = this.byGroup(),
  2506. nodes = _this$byGroup.nodes,
  2507. edges = _this$byGroup.edges;
  2508. var N = nodes.length;
  2509. var Nsq = N * N;
  2510. var indexOf = function indexOf(node) {
  2511. return nodes.indexOf(node);
  2512. };
  2513. var atIndex = function atIndex(i) {
  2514. return nodes[i];
  2515. };
  2516. // Initialize distance matrix
  2517. var dist = new Array(Nsq);
  2518. for (var n = 0; n < Nsq; n++) {
  2519. var j = n % N;
  2520. var i = (n - j) / N;
  2521. if (i === j) {
  2522. dist[n] = 0;
  2523. } else {
  2524. dist[n] = Infinity;
  2525. }
  2526. }
  2527. // Initialize matrix used for path reconstruction
  2528. // Initialize distance matrix
  2529. var next = new Array(Nsq);
  2530. var edgeNext = new Array(Nsq);
  2531. // Process edges
  2532. for (var _i = 0; _i < edges.length; _i++) {
  2533. var edge = edges[_i];
  2534. var src = edge.source()[0];
  2535. var tgt = edge.target()[0];
  2536. if (src === tgt) {
  2537. continue;
  2538. } // exclude loops
  2539. var s = indexOf(src);
  2540. var t = indexOf(tgt);
  2541. var st = s * N + t; // source to target index
  2542. var _weight = weightFn(edge);
  2543. // Check if already process another edge between same 2 nodes
  2544. if (dist[st] > _weight) {
  2545. dist[st] = _weight;
  2546. next[st] = t;
  2547. edgeNext[st] = edge;
  2548. }
  2549. // If undirected graph, process 'reversed' edge
  2550. if (!directed) {
  2551. var ts = t * N + s; // target to source index
  2552. if (!directed && dist[ts] > _weight) {
  2553. dist[ts] = _weight;
  2554. next[ts] = s;
  2555. edgeNext[ts] = edge;
  2556. }
  2557. }
  2558. }
  2559. // Main loop
  2560. for (var k = 0; k < N; k++) {
  2561. for (var _i2 = 0; _i2 < N; _i2++) {
  2562. var ik = _i2 * N + k;
  2563. for (var _j = 0; _j < N; _j++) {
  2564. var ij = _i2 * N + _j;
  2565. var kj = k * N + _j;
  2566. if (dist[ik] + dist[kj] < dist[ij]) {
  2567. dist[ij] = dist[ik] + dist[kj];
  2568. next[ij] = next[ik];
  2569. }
  2570. }
  2571. }
  2572. }
  2573. var getArgEle = function getArgEle(ele) {
  2574. return (string(ele) ? cy.filter(ele) : ele)[0];
  2575. };
  2576. var indexOfArgEle = function indexOfArgEle(ele) {
  2577. return indexOf(getArgEle(ele));
  2578. };
  2579. var res = {
  2580. distance: function distance(from, to) {
  2581. var i = indexOfArgEle(from);
  2582. var j = indexOfArgEle(to);
  2583. return dist[i * N + j];
  2584. },
  2585. path: function path(from, to) {
  2586. var i = indexOfArgEle(from);
  2587. var j = indexOfArgEle(to);
  2588. var fromNode = atIndex(i);
  2589. if (i === j) {
  2590. return fromNode.collection();
  2591. }
  2592. if (next[i * N + j] == null) {
  2593. return cy.collection();
  2594. }
  2595. var path = cy.collection();
  2596. var prev = i;
  2597. var edge;
  2598. path.merge(fromNode);
  2599. while (i !== j) {
  2600. prev = i;
  2601. i = next[i * N + j];
  2602. edge = edgeNext[prev * N + i];
  2603. path.merge(edge);
  2604. path.merge(atIndex(i));
  2605. }
  2606. return path;
  2607. }
  2608. };
  2609. return res;
  2610. } // floydWarshall
  2611. }; // elesfn
  2612. var bellmanFordDefaults = defaults$g({
  2613. weight: function weight(edge) {
  2614. return 1;
  2615. },
  2616. directed: false,
  2617. root: null
  2618. });
  2619. var elesfn$q = {
  2620. // Implemented from pseudocode from wikipedia
  2621. bellmanFord: function bellmanFord(options) {
  2622. var _this = this;
  2623. var _bellmanFordDefaults = bellmanFordDefaults(options),
  2624. weight = _bellmanFordDefaults.weight,
  2625. directed = _bellmanFordDefaults.directed,
  2626. root = _bellmanFordDefaults.root;
  2627. var weightFn = weight;
  2628. var eles = this;
  2629. var cy = this.cy();
  2630. var _this$byGroup = this.byGroup(),
  2631. edges = _this$byGroup.edges,
  2632. nodes = _this$byGroup.nodes;
  2633. var numNodes = nodes.length;
  2634. var infoMap = new Map$1();
  2635. var hasNegativeWeightCycle = false;
  2636. var negativeWeightCycles = [];
  2637. root = cy.collection(root)[0]; // in case selector passed
  2638. edges.unmergeBy(function (edge) {
  2639. return edge.isLoop();
  2640. });
  2641. var numEdges = edges.length;
  2642. var getInfo = function getInfo(node) {
  2643. var obj = infoMap.get(node.id());
  2644. if (!obj) {
  2645. obj = {};
  2646. infoMap.set(node.id(), obj);
  2647. }
  2648. return obj;
  2649. };
  2650. var getNodeFromTo = function getNodeFromTo(to) {
  2651. return (string(to) ? cy.$(to) : to)[0];
  2652. };
  2653. var distanceTo = function distanceTo(to) {
  2654. return getInfo(getNodeFromTo(to)).dist;
  2655. };
  2656. var pathTo = function pathTo(to) {
  2657. var thisStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;
  2658. var end = getNodeFromTo(to);
  2659. var path = [];
  2660. var node = end;
  2661. for (;;) {
  2662. if (node == null) {
  2663. return _this.spawn();
  2664. }
  2665. var _getInfo = getInfo(node),
  2666. edge = _getInfo.edge,
  2667. pred = _getInfo.pred;
  2668. path.unshift(node[0]);
  2669. if (node.same(thisStart) && path.length > 0) {
  2670. break;
  2671. }
  2672. if (edge != null) {
  2673. path.unshift(edge);
  2674. }
  2675. node = pred;
  2676. }
  2677. return eles.spawn(path);
  2678. };
  2679. // Initializations { dist, pred, edge }
  2680. for (var i = 0; i < numNodes; i++) {
  2681. var node = nodes[i];
  2682. var info = getInfo(node);
  2683. if (node.same(root)) {
  2684. info.dist = 0;
  2685. } else {
  2686. info.dist = Infinity;
  2687. }
  2688. info.pred = null;
  2689. info.edge = null;
  2690. }
  2691. // Edges relaxation
  2692. var replacedEdge = false;
  2693. var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {
  2694. var dist = info1.dist + weight;
  2695. if (dist < info2.dist && !edge.same(info1.edge)) {
  2696. info2.dist = dist;
  2697. info2.pred = node1;
  2698. info2.edge = edge;
  2699. replacedEdge = true;
  2700. }
  2701. };
  2702. for (var _i = 1; _i < numNodes; _i++) {
  2703. replacedEdge = false;
  2704. for (var e = 0; e < numEdges; e++) {
  2705. var edge = edges[e];
  2706. var src = edge.source();
  2707. var tgt = edge.target();
  2708. var _weight = weightFn(edge);
  2709. var srcInfo = getInfo(src);
  2710. var tgtInfo = getInfo(tgt);
  2711. checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight);
  2712. // If undirected graph, we need to take into account the 'reverse' edge
  2713. if (!directed) {
  2714. checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);
  2715. }
  2716. }
  2717. if (!replacedEdge) {
  2718. break;
  2719. }
  2720. }
  2721. if (replacedEdge) {
  2722. // Check for negative weight cycles
  2723. var negativeWeightCycleIds = [];
  2724. for (var _e = 0; _e < numEdges; _e++) {
  2725. var _edge = edges[_e];
  2726. var _src = _edge.source();
  2727. var _tgt = _edge.target();
  2728. var _weight2 = weightFn(_edge);
  2729. var srcDist = getInfo(_src).dist;
  2730. var tgtDist = getInfo(_tgt).dist;
  2731. if (srcDist + _weight2 < tgtDist || !directed && tgtDist + _weight2 < srcDist) {
  2732. if (!hasNegativeWeightCycle) {
  2733. warn('Graph contains a negative weight cycle for Bellman-Ford');
  2734. hasNegativeWeightCycle = true;
  2735. }
  2736. if (options.findNegativeWeightCycles !== false) {
  2737. var negativeNodes = [];
  2738. if (srcDist + _weight2 < tgtDist) {
  2739. negativeNodes.push(_src);
  2740. }
  2741. if (!directed && tgtDist + _weight2 < srcDist) {
  2742. negativeNodes.push(_tgt);
  2743. }
  2744. var numNegativeNodes = negativeNodes.length;
  2745. for (var n = 0; n < numNegativeNodes; n++) {
  2746. var start = negativeNodes[n];
  2747. var cycle = [start];
  2748. cycle.push(getInfo(start).edge);
  2749. var _node = getInfo(start).pred;
  2750. while (cycle.indexOf(_node) === -1) {
  2751. cycle.push(_node);
  2752. cycle.push(getInfo(_node).edge);
  2753. _node = getInfo(_node).pred;
  2754. }
  2755. cycle = cycle.slice(cycle.indexOf(_node));
  2756. var smallestId = cycle[0].id();
  2757. var smallestIndex = 0;
  2758. for (var c = 2; c < cycle.length; c += 2) {
  2759. if (cycle[c].id() < smallestId) {
  2760. smallestId = cycle[c].id();
  2761. smallestIndex = c;
  2762. }
  2763. }
  2764. cycle = cycle.slice(smallestIndex).concat(cycle.slice(0, smallestIndex));
  2765. cycle.push(cycle[0]);
  2766. var cycleId = cycle.map(function (el) {
  2767. return el.id();
  2768. }).join(",");
  2769. if (negativeWeightCycleIds.indexOf(cycleId) === -1) {
  2770. negativeWeightCycles.push(eles.spawn(cycle));
  2771. negativeWeightCycleIds.push(cycleId);
  2772. }
  2773. }
  2774. } else {
  2775. break;
  2776. }
  2777. }
  2778. }
  2779. }
  2780. return {
  2781. distanceTo: distanceTo,
  2782. pathTo: pathTo,
  2783. hasNegativeWeightCycle: hasNegativeWeightCycle,
  2784. negativeWeightCycles: negativeWeightCycles
  2785. };
  2786. } // bellmanFord
  2787. }; // elesfn
  2788. var sqrt2 = Math.sqrt(2);
  2789. // Function which colapses 2 (meta) nodes into one
  2790. // Updates the remaining edge lists
  2791. // Receives as a paramater the edge which causes the collapse
  2792. var collapse = function collapse(edgeIndex, nodeMap, remainingEdges) {
  2793. if (remainingEdges.length === 0) {
  2794. error("Karger-Stein must be run on a connected (sub)graph");
  2795. }
  2796. var edgeInfo = remainingEdges[edgeIndex];
  2797. var sourceIn = edgeInfo[1];
  2798. var targetIn = edgeInfo[2];
  2799. var partition1 = nodeMap[sourceIn];
  2800. var partition2 = nodeMap[targetIn];
  2801. var newEdges = remainingEdges; // re-use array
  2802. // Delete all edges between partition1 and partition2
  2803. for (var i = newEdges.length - 1; i >= 0; i--) {
  2804. var edge = newEdges[i];
  2805. var src = edge[1];
  2806. var tgt = edge[2];
  2807. if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {
  2808. newEdges.splice(i, 1);
  2809. }
  2810. }
  2811. // All edges pointing to partition2 should now point to partition1
  2812. for (var _i = 0; _i < newEdges.length; _i++) {
  2813. var _edge = newEdges[_i];
  2814. if (_edge[1] === partition2) {
  2815. // Check source
  2816. newEdges[_i] = _edge.slice(); // copy
  2817. newEdges[_i][1] = partition1;
  2818. } else if (_edge[2] === partition2) {
  2819. // Check target
  2820. newEdges[_i] = _edge.slice(); // copy
  2821. newEdges[_i][2] = partition1;
  2822. }
  2823. }
  2824. // Move all nodes from partition2 to partition1
  2825. for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {
  2826. if (nodeMap[_i2] === partition2) {
  2827. nodeMap[_i2] = partition1;
  2828. }
  2829. }
  2830. return newEdges;
  2831. };
  2832. // Contracts a graph until we reach a certain number of meta nodes
  2833. var contractUntil = function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {
  2834. while (size > sizeLimit) {
  2835. // Choose an edge randomly
  2836. var edgeIndex = Math.floor(Math.random() * remainingEdges.length);
  2837. // Collapse graph based on edge
  2838. remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);
  2839. size--;
  2840. }
  2841. return remainingEdges;
  2842. };
  2843. var elesfn$p = {
  2844. // Computes the minimum cut of an undirected graph
  2845. // Returns the correct answer with high probability
  2846. kargerStein: function kargerStein() {
  2847. var _this = this;
  2848. var _this$byGroup = this.byGroup(),
  2849. nodes = _this$byGroup.nodes,
  2850. edges = _this$byGroup.edges;
  2851. edges.unmergeBy(function (edge) {
  2852. return edge.isLoop();
  2853. });
  2854. var numNodes = nodes.length;
  2855. var numEdges = edges.length;
  2856. var numIter = Math.ceil(Math.pow(Math.log(numNodes) / Math.LN2, 2));
  2857. var stopSize = Math.floor(numNodes / sqrt2);
  2858. if (numNodes < 2) {
  2859. error('At least 2 nodes are required for Karger-Stein algorithm');
  2860. return undefined;
  2861. }
  2862. // Now store edge destination as indexes
  2863. // Format for each edge (edge index, source node index, target node index)
  2864. var edgeIndexes = [];
  2865. for (var i = 0; i < numEdges; i++) {
  2866. var e = edges[i];
  2867. edgeIndexes.push([i, nodes.indexOf(e.source()), nodes.indexOf(e.target())]);
  2868. }
  2869. // We will store the best cut found here
  2870. var minCutSize = Infinity;
  2871. var minCutEdgeIndexes = [];
  2872. var minCutNodeMap = new Array(numNodes);
  2873. // Initial meta node partition
  2874. var metaNodeMap = new Array(numNodes);
  2875. var metaNodeMap2 = new Array(numNodes);
  2876. var copyNodesMap = function copyNodesMap(from, to) {
  2877. for (var _i3 = 0; _i3 < numNodes; _i3++) {
  2878. to[_i3] = from[_i3];
  2879. }
  2880. };
  2881. // Main loop
  2882. for (var iter = 0; iter <= numIter; iter++) {
  2883. // Reset meta node partition
  2884. for (var _i4 = 0; _i4 < numNodes; _i4++) {
  2885. metaNodeMap[_i4] = _i4;
  2886. }
  2887. // Contract until stop point (stopSize nodes)
  2888. var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);
  2889. var edgesState2 = edgesState.slice(); // copy
  2890. // Create a copy of the colapsed nodes state
  2891. copyNodesMap(metaNodeMap, metaNodeMap2);
  2892. // Run 2 iterations starting in the stop state
  2893. var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);
  2894. var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2);
  2895. // Is any of the 2 results the best cut so far?
  2896. if (res1.length <= res2.length && res1.length < minCutSize) {
  2897. minCutSize = res1.length;
  2898. minCutEdgeIndexes = res1;
  2899. copyNodesMap(metaNodeMap, minCutNodeMap);
  2900. } else if (res2.length <= res1.length && res2.length < minCutSize) {
  2901. minCutSize = res2.length;
  2902. minCutEdgeIndexes = res2;
  2903. copyNodesMap(metaNodeMap2, minCutNodeMap);
  2904. }
  2905. } // end of main loop
  2906. // Construct result
  2907. var cut = this.spawn(minCutEdgeIndexes.map(function (e) {
  2908. return edges[e[0]];
  2909. }));
  2910. var partition1 = this.spawn();
  2911. var partition2 = this.spawn();
  2912. // traverse metaNodeMap for best cut
  2913. var witnessNodePartition = minCutNodeMap[0];
  2914. for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {
  2915. var partitionId = minCutNodeMap[_i5];
  2916. var node = nodes[_i5];
  2917. if (partitionId === witnessNodePartition) {
  2918. partition1.merge(node);
  2919. } else {
  2920. partition2.merge(node);
  2921. }
  2922. }
  2923. // construct components corresponding to each disjoint subset of nodes
  2924. var constructComponent = function constructComponent(subset) {
  2925. var component = _this.spawn();
  2926. subset.forEach(function (node) {
  2927. component.merge(node);
  2928. node.connectedEdges().forEach(function (edge) {
  2929. // ensure edge is within calling collection and edge is not in cut
  2930. if (_this.contains(edge) && !cut.contains(edge)) {
  2931. component.merge(edge);
  2932. }
  2933. });
  2934. });
  2935. return component;
  2936. };
  2937. var components = [constructComponent(partition1), constructComponent(partition2)];
  2938. var ret = {
  2939. cut: cut,
  2940. components: components,
  2941. // n.b. partitions are included to be compatible with the old api spec
  2942. // (could be removed in a future major version)
  2943. partition1: partition1,
  2944. partition2: partition2
  2945. };
  2946. return ret;
  2947. }
  2948. }; // elesfn
  2949. var _Math$hypot;
  2950. var copyPosition = function copyPosition(p) {
  2951. return {
  2952. x: p.x,
  2953. y: p.y
  2954. };
  2955. };
  2956. var modelToRenderedPosition$1 = function modelToRenderedPosition(p, zoom, pan) {
  2957. return {
  2958. x: p.x * zoom + pan.x,
  2959. y: p.y * zoom + pan.y
  2960. };
  2961. };
  2962. var renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {
  2963. return {
  2964. x: (p.x - pan.x) / zoom,
  2965. y: (p.y - pan.y) / zoom
  2966. };
  2967. };
  2968. var array2point = function array2point(arr) {
  2969. return {
  2970. x: arr[0],
  2971. y: arr[1]
  2972. };
  2973. };
  2974. var min = function min(arr) {
  2975. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2976. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  2977. var min = Infinity;
  2978. for (var i = begin; i < end; i++) {
  2979. var val = arr[i];
  2980. if (isFinite(val)) {
  2981. min = Math.min(val, min);
  2982. }
  2983. }
  2984. return min;
  2985. };
  2986. var max = function max(arr) {
  2987. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2988. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  2989. var max = -Infinity;
  2990. for (var i = begin; i < end; i++) {
  2991. var val = arr[i];
  2992. if (isFinite(val)) {
  2993. max = Math.max(val, max);
  2994. }
  2995. }
  2996. return max;
  2997. };
  2998. var mean = function mean(arr) {
  2999. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3000. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  3001. var total = 0;
  3002. var n = 0;
  3003. for (var i = begin; i < end; i++) {
  3004. var val = arr[i];
  3005. if (isFinite(val)) {
  3006. total += val;
  3007. n++;
  3008. }
  3009. }
  3010. return total / n;
  3011. };
  3012. var median = function median(arr) {
  3013. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3014. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  3015. var copy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  3016. var sort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  3017. var includeHoles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  3018. if (copy) {
  3019. arr = arr.slice(begin, end);
  3020. } else {
  3021. if (end < arr.length) {
  3022. arr.splice(end, arr.length - end);
  3023. }
  3024. if (begin > 0) {
  3025. arr.splice(0, begin);
  3026. }
  3027. }
  3028. // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start
  3029. var off = 0; // offset from non-finite values
  3030. for (var i = arr.length - 1; i >= 0; i--) {
  3031. var v = arr[i];
  3032. if (includeHoles) {
  3033. if (!isFinite(v)) {
  3034. arr[i] = -Infinity;
  3035. off++;
  3036. }
  3037. } else {
  3038. // just remove it if we don't want to consider holes
  3039. arr.splice(i, 1);
  3040. }
  3041. }
  3042. if (sort) {
  3043. arr.sort(function (a, b) {
  3044. return a - b;
  3045. }); // requires copy = true if you don't want to change the orig
  3046. }
  3047. var len = arr.length;
  3048. var mid = Math.floor(len / 2);
  3049. if (len % 2 !== 0) {
  3050. return arr[mid + 1 + off];
  3051. } else {
  3052. return (arr[mid - 1 + off] + arr[mid + off]) / 2;
  3053. }
  3054. };
  3055. var deg2rad = function deg2rad(deg) {
  3056. return Math.PI * deg / 180;
  3057. };
  3058. var getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {
  3059. return Math.atan2(dispY, dispX) - Math.PI / 2;
  3060. };
  3061. var log2 = Math.log2 || function (n) {
  3062. return Math.log(n) / Math.log(2);
  3063. };
  3064. var signum = function signum(x) {
  3065. if (x > 0) {
  3066. return 1;
  3067. } else if (x < 0) {
  3068. return -1;
  3069. } else {
  3070. return 0;
  3071. }
  3072. };
  3073. var dist = function dist(p1, p2) {
  3074. return Math.sqrt(sqdist(p1, p2));
  3075. };
  3076. var sqdist = function sqdist(p1, p2) {
  3077. var dx = p2.x - p1.x;
  3078. var dy = p2.y - p1.y;
  3079. return dx * dx + dy * dy;
  3080. };
  3081. var inPlaceSumNormalize = function inPlaceSumNormalize(v) {
  3082. var length = v.length;
  3083. // First, get sum of all elements
  3084. var total = 0;
  3085. for (var i = 0; i < length; i++) {
  3086. total += v[i];
  3087. }
  3088. // Now, divide each by the sum of all elements
  3089. for (var _i = 0; _i < length; _i++) {
  3090. v[_i] = v[_i] / total;
  3091. }
  3092. return v;
  3093. };
  3094. // from http://en.wikipedia.org/wiki/Bézier_curve#Quadratic_curves
  3095. var qbezierAt = function qbezierAt(p0, p1, p2, t) {
  3096. return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;
  3097. };
  3098. var qbezierPtAt = function qbezierPtAt(p0, p1, p2, t) {
  3099. return {
  3100. x: qbezierAt(p0.x, p1.x, p2.x, t),
  3101. y: qbezierAt(p0.y, p1.y, p2.y, t)
  3102. };
  3103. };
  3104. var lineAt = function lineAt(p0, p1, t, d) {
  3105. var vec = {
  3106. x: p1.x - p0.x,
  3107. y: p1.y - p0.y
  3108. };
  3109. var vecDist = dist(p0, p1);
  3110. var normVec = {
  3111. x: vec.x / vecDist,
  3112. y: vec.y / vecDist
  3113. };
  3114. t = t == null ? 0 : t;
  3115. d = d != null ? d : t * vecDist;
  3116. return {
  3117. x: p0.x + normVec.x * d,
  3118. y: p0.y + normVec.y * d
  3119. };
  3120. };
  3121. var bound = function bound(min, val, max) {
  3122. return Math.max(min, Math.min(max, val));
  3123. };
  3124. // makes a full bb (x1, y1, x2, y2, w, h) from implicit params
  3125. var makeBoundingBox = function makeBoundingBox(bb) {
  3126. if (bb == null) {
  3127. return {
  3128. x1: Infinity,
  3129. y1: Infinity,
  3130. x2: -Infinity,
  3131. y2: -Infinity,
  3132. w: 0,
  3133. h: 0
  3134. };
  3135. } else if (bb.x1 != null && bb.y1 != null) {
  3136. if (bb.x2 != null && bb.y2 != null && bb.x2 >= bb.x1 && bb.y2 >= bb.y1) {
  3137. return {
  3138. x1: bb.x1,
  3139. y1: bb.y1,
  3140. x2: bb.x2,
  3141. y2: bb.y2,
  3142. w: bb.x2 - bb.x1,
  3143. h: bb.y2 - bb.y1
  3144. };
  3145. } else if (bb.w != null && bb.h != null && bb.w >= 0 && bb.h >= 0) {
  3146. return {
  3147. x1: bb.x1,
  3148. y1: bb.y1,
  3149. x2: bb.x1 + bb.w,
  3150. y2: bb.y1 + bb.h,
  3151. w: bb.w,
  3152. h: bb.h
  3153. };
  3154. }
  3155. }
  3156. };
  3157. var copyBoundingBox = function copyBoundingBox(bb) {
  3158. return {
  3159. x1: bb.x1,
  3160. x2: bb.x2,
  3161. w: bb.w,
  3162. y1: bb.y1,
  3163. y2: bb.y2,
  3164. h: bb.h
  3165. };
  3166. };
  3167. var clearBoundingBox = function clearBoundingBox(bb) {
  3168. bb.x1 = Infinity;
  3169. bb.y1 = Infinity;
  3170. bb.x2 = -Infinity;
  3171. bb.y2 = -Infinity;
  3172. bb.w = 0;
  3173. bb.h = 0;
  3174. };
  3175. var updateBoundingBox = function updateBoundingBox(bb1, bb2) {
  3176. // update bb1 with bb2 bounds
  3177. bb1.x1 = Math.min(bb1.x1, bb2.x1);
  3178. bb1.x2 = Math.max(bb1.x2, bb2.x2);
  3179. bb1.w = bb1.x2 - bb1.x1;
  3180. bb1.y1 = Math.min(bb1.y1, bb2.y1);
  3181. bb1.y2 = Math.max(bb1.y2, bb2.y2);
  3182. bb1.h = bb1.y2 - bb1.y1;
  3183. };
  3184. var expandBoundingBoxByPoint = function expandBoundingBoxByPoint(bb, x, y) {
  3185. bb.x1 = Math.min(bb.x1, x);
  3186. bb.x2 = Math.max(bb.x2, x);
  3187. bb.w = bb.x2 - bb.x1;
  3188. bb.y1 = Math.min(bb.y1, y);
  3189. bb.y2 = Math.max(bb.y2, y);
  3190. bb.h = bb.y2 - bb.y1;
  3191. };
  3192. var expandBoundingBox = function expandBoundingBox(bb) {
  3193. var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3194. bb.x1 -= padding;
  3195. bb.x2 += padding;
  3196. bb.y1 -= padding;
  3197. bb.y2 += padding;
  3198. bb.w = bb.x2 - bb.x1;
  3199. bb.h = bb.y2 - bb.y1;
  3200. return bb;
  3201. };
  3202. var expandBoundingBoxSides = function expandBoundingBoxSides(bb) {
  3203. var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];
  3204. var top, right, bottom, left;
  3205. if (padding.length === 1) {
  3206. top = right = bottom = left = padding[0];
  3207. } else if (padding.length === 2) {
  3208. top = bottom = padding[0];
  3209. left = right = padding[1];
  3210. } else if (padding.length === 4) {
  3211. var _padding = _slicedToArray(padding, 4);
  3212. top = _padding[0];
  3213. right = _padding[1];
  3214. bottom = _padding[2];
  3215. left = _padding[3];
  3216. }
  3217. bb.x1 -= left;
  3218. bb.x2 += right;
  3219. bb.y1 -= top;
  3220. bb.y2 += bottom;
  3221. bb.w = bb.x2 - bb.x1;
  3222. bb.h = bb.y2 - bb.y1;
  3223. return bb;
  3224. };
  3225. // assign the values of bb2 into bb1
  3226. var assignBoundingBox = function assignBoundingBox(bb1, bb2) {
  3227. bb1.x1 = bb2.x1;
  3228. bb1.y1 = bb2.y1;
  3229. bb1.x2 = bb2.x2;
  3230. bb1.y2 = bb2.y2;
  3231. bb1.w = bb1.x2 - bb1.x1;
  3232. bb1.h = bb1.y2 - bb1.y1;
  3233. };
  3234. var boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {
  3235. // case: one bb to right of other
  3236. if (bb1.x1 > bb2.x2) {
  3237. return false;
  3238. }
  3239. if (bb2.x1 > bb1.x2) {
  3240. return false;
  3241. }
  3242. // case: one bb to left of other
  3243. if (bb1.x2 < bb2.x1) {
  3244. return false;
  3245. }
  3246. if (bb2.x2 < bb1.x1) {
  3247. return false;
  3248. }
  3249. // case: one bb above other
  3250. if (bb1.y2 < bb2.y1) {
  3251. return false;
  3252. }
  3253. if (bb2.y2 < bb1.y1) {
  3254. return false;
  3255. }
  3256. // case: one bb below other
  3257. if (bb1.y1 > bb2.y2) {
  3258. return false;
  3259. }
  3260. if (bb2.y1 > bb1.y2) {
  3261. return false;
  3262. }
  3263. // otherwise, must have some overlap
  3264. return true;
  3265. };
  3266. var inBoundingBox = function inBoundingBox(bb, x, y) {
  3267. return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;
  3268. };
  3269. var pointInBoundingBox = function pointInBoundingBox(bb, pt) {
  3270. return inBoundingBox(bb, pt.x, pt.y);
  3271. };
  3272. var boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {
  3273. return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);
  3274. };
  3275. var hypot = (_Math$hypot = Math.hypot) !== null && _Math$hypot !== undefined ? _Math$hypot : function (x, y) {
  3276. return Math.sqrt(x * x + y * y);
  3277. };
  3278. function inflatePolygon(polygon, d) {
  3279. if (polygon.length < 3) {
  3280. throw new Error('Need at least 3 vertices');
  3281. }
  3282. // Helpers
  3283. var add = function add(a, b) {
  3284. return {
  3285. x: a.x + b.x,
  3286. y: a.y + b.y
  3287. };
  3288. };
  3289. var sub = function sub(a, b) {
  3290. return {
  3291. x: a.x - b.x,
  3292. y: a.y - b.y
  3293. };
  3294. };
  3295. var scale = function scale(v, s) {
  3296. return {
  3297. x: v.x * s,
  3298. y: v.y * s
  3299. };
  3300. };
  3301. var cross = function cross(u, v) {
  3302. return u.x * v.y - u.y * v.x;
  3303. };
  3304. var normalize = function normalize(v) {
  3305. var len = hypot(v.x, v.y);
  3306. return len === 0 ? {
  3307. x: 0,
  3308. y: 0
  3309. } : {
  3310. x: v.x / len,
  3311. y: v.y / len
  3312. };
  3313. };
  3314. // Signed area (positive = CCW)
  3315. var signedArea = function signedArea(pts) {
  3316. var A = 0;
  3317. for (var i = 0; i < pts.length; i++) {
  3318. var p = pts[i],
  3319. q = pts[(i + 1) % pts.length];
  3320. A += p.x * q.y - q.x * p.y;
  3321. }
  3322. return A / 2;
  3323. };
  3324. // Line–line intersection (infinite lines)
  3325. var intersectLines = function intersectLines(p1, p2, p3, p4) {
  3326. var r = sub(p2, p1);
  3327. var s = sub(p4, p3);
  3328. var denom = cross(r, s);
  3329. if (Math.abs(denom) < 1e-9) {
  3330. // Parallel or nearly so — fallback to midpoint
  3331. return add(p1, scale(r, 0.5));
  3332. }
  3333. var t = cross(sub(p3, p1), s) / denom;
  3334. return add(p1, scale(r, t));
  3335. };
  3336. // Make a shallow copy and enforce CCW
  3337. var pts = polygon.map(function (p) {
  3338. return {
  3339. x: p.x,
  3340. y: p.y
  3341. };
  3342. });
  3343. if (signedArea(pts) < 0) pts.reverse();
  3344. var n = pts.length;
  3345. // Compute outward normals for each edge
  3346. var normals = [];
  3347. for (var i = 0; i < n; i++) {
  3348. var p = pts[i],
  3349. q = pts[(i + 1) % n];
  3350. var edge = sub(q, p);
  3351. // For CCW polygon, inward normal = (-edge.y, edge.x)
  3352. // so outward normal = (edge.y, -edge.x)
  3353. var out = normalize({
  3354. x: edge.y,
  3355. y: -edge.x
  3356. });
  3357. normals.push(out);
  3358. }
  3359. // Build offset edges
  3360. var offsetEdges = normals.map(function (nrm, i) {
  3361. var p1 = add(pts[i], scale(nrm, d));
  3362. var p2 = add(pts[(i + 1) % n], scale(nrm, d));
  3363. return {
  3364. p1: p1,
  3365. p2: p2
  3366. };
  3367. });
  3368. // Intersect consecutive offset edges
  3369. var inflated = [];
  3370. for (var _i2 = 0; _i2 < n; _i2++) {
  3371. var prevEdge = offsetEdges[(_i2 - 1 + n) % n];
  3372. var currEdge = offsetEdges[_i2];
  3373. var ip = intersectLines(prevEdge.p1, prevEdge.p2, currEdge.p1, currEdge.p2);
  3374. inflated.push(ip);
  3375. }
  3376. return inflated;
  3377. }
  3378. function miterBox(pts, centerX, centerY, width, height, strokeWidth) {
  3379. var tpts = transformPoints(pts, centerX, centerY, width, height);
  3380. var offsetPoints = inflatePolygon(tpts, strokeWidth);
  3381. var bb = makeBoundingBox();
  3382. offsetPoints.forEach(function (pt) {
  3383. return expandBoundingBoxByPoint(bb, pt.x, pt.y);
  3384. });
  3385. return bb;
  3386. }
  3387. var roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {
  3388. var radius = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'auto';
  3389. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  3390. var halfWidth = width / 2;
  3391. var halfHeight = height / 2;
  3392. cornerRadius = Math.min(cornerRadius, halfWidth, halfHeight);
  3393. var doWidth = cornerRadius !== halfWidth,
  3394. doHeight = cornerRadius !== halfHeight;
  3395. // Check intersections with straight line segments
  3396. var straightLineIntersections;
  3397. // Top segment, left to right
  3398. if (doWidth) {
  3399. var topStartX = nodeX - halfWidth + cornerRadius - padding;
  3400. var topStartY = nodeY - halfHeight - padding;
  3401. var topEndX = nodeX + halfWidth - cornerRadius + padding;
  3402. var topEndY = topStartY;
  3403. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
  3404. if (straightLineIntersections.length > 0) {
  3405. return straightLineIntersections;
  3406. }
  3407. }
  3408. // Right segment, top to bottom
  3409. if (doHeight) {
  3410. var rightStartX = nodeX + halfWidth + padding;
  3411. var rightStartY = nodeY - halfHeight + cornerRadius - padding;
  3412. var rightEndX = rightStartX;
  3413. var rightEndY = nodeY + halfHeight - cornerRadius + padding;
  3414. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, rightStartX, rightStartY, rightEndX, rightEndY, false);
  3415. if (straightLineIntersections.length > 0) {
  3416. return straightLineIntersections;
  3417. }
  3418. }
  3419. // Bottom segment, left to right
  3420. if (doWidth) {
  3421. var bottomStartX = nodeX - halfWidth + cornerRadius - padding;
  3422. var bottomStartY = nodeY + halfHeight + padding;
  3423. var bottomEndX = nodeX + halfWidth - cornerRadius + padding;
  3424. var bottomEndY = bottomStartY;
  3425. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, bottomStartX, bottomStartY, bottomEndX, bottomEndY, false);
  3426. if (straightLineIntersections.length > 0) {
  3427. return straightLineIntersections;
  3428. }
  3429. }
  3430. // Left segment, top to bottom
  3431. if (doHeight) {
  3432. var leftStartX = nodeX - halfWidth - padding;
  3433. var leftStartY = nodeY - halfHeight + cornerRadius - padding;
  3434. var leftEndX = leftStartX;
  3435. var leftEndY = nodeY + halfHeight - cornerRadius + padding;
  3436. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, leftStartX, leftStartY, leftEndX, leftEndY, false);
  3437. if (straightLineIntersections.length > 0) {
  3438. return straightLineIntersections;
  3439. }
  3440. }
  3441. // Check intersections with arc segments
  3442. var arcIntersections;
  3443. // Top Left
  3444. {
  3445. var topLeftCenterX = nodeX - halfWidth + cornerRadius;
  3446. var topLeftCenterY = nodeY - halfHeight + cornerRadius;
  3447. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding);
  3448. // Ensure the intersection is on the desired quarter of the circle
  3449. if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {
  3450. return [arcIntersections[0], arcIntersections[1]];
  3451. }
  3452. }
  3453. // Top Right
  3454. {
  3455. var topRightCenterX = nodeX + halfWidth - cornerRadius;
  3456. var topRightCenterY = nodeY - halfHeight + cornerRadius;
  3457. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding);
  3458. // Ensure the intersection is on the desired quarter of the circle
  3459. if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {
  3460. return [arcIntersections[0], arcIntersections[1]];
  3461. }
  3462. }
  3463. // Bottom Right
  3464. {
  3465. var bottomRightCenterX = nodeX + halfWidth - cornerRadius;
  3466. var bottomRightCenterY = nodeY + halfHeight - cornerRadius;
  3467. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding);
  3468. // Ensure the intersection is on the desired quarter of the circle
  3469. if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {
  3470. return [arcIntersections[0], arcIntersections[1]];
  3471. }
  3472. }
  3473. // Bottom Left
  3474. {
  3475. var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;
  3476. var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;
  3477. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding);
  3478. // Ensure the intersection is on the desired quarter of the circle
  3479. if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {
  3480. return [arcIntersections[0], arcIntersections[1]];
  3481. }
  3482. }
  3483. return []; // if nothing
  3484. };
  3485. var inLineVicinity = function inLineVicinity(x, y, lx1, ly1, lx2, ly2, tolerance) {
  3486. var t = tolerance;
  3487. var x1 = Math.min(lx1, lx2);
  3488. var x2 = Math.max(lx1, lx2);
  3489. var y1 = Math.min(ly1, ly2);
  3490. var y2 = Math.max(ly1, ly2);
  3491. return x1 - t <= x && x <= x2 + t && y1 - t <= y && y <= y2 + t;
  3492. };
  3493. var inBezierVicinity = function inBezierVicinity(x, y, x1, y1, x2, y2, x3, y3, tolerance) {
  3494. var bb = {
  3495. x1: Math.min(x1, x3, x2) - tolerance,
  3496. x2: Math.max(x1, x3, x2) + tolerance,
  3497. y1: Math.min(y1, y3, y2) - tolerance,
  3498. y2: Math.max(y1, y3, y2) + tolerance
  3499. };
  3500. // if outside the rough bounding box for the bezier, then it can't be a hit
  3501. if (x < bb.x1 || x > bb.x2 || y < bb.y1 || y > bb.y2) {
  3502. // console.log('bezier out of rough bb')
  3503. return false;
  3504. } else {
  3505. // console.log('do more expensive check');
  3506. return true;
  3507. }
  3508. };
  3509. var solveQuadratic = function solveQuadratic(a, b, c, val) {
  3510. c -= val;
  3511. var r = b * b - 4 * a * c;
  3512. if (r < 0) {
  3513. return [];
  3514. }
  3515. var sqrtR = Math.sqrt(r);
  3516. var denom = 2 * a;
  3517. var root1 = (-b + sqrtR) / denom;
  3518. var root2 = (-b - sqrtR) / denom;
  3519. return [root1, root2];
  3520. };
  3521. var solveCubic = function solveCubic(a, b, c, d, result) {
  3522. // Solves a cubic function, returns root in form [r1, i1, r2, i2, r3, i3], where
  3523. // r is the real component, i is the imaginary component
  3524. // An implementation of the Cardano method from the year 1545
  3525. // http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots
  3526. var epsilon = 0.00001;
  3527. // avoid division by zero while keeping the overall expression close in value
  3528. if (a === 0) {
  3529. a = epsilon;
  3530. }
  3531. b /= a;
  3532. c /= a;
  3533. d /= a;
  3534. var discriminant, q, r, dum1, s, t, term1, r13;
  3535. q = (3.0 * c - b * b) / 9.0;
  3536. r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b));
  3537. r /= 54.0;
  3538. discriminant = q * q * q + r * r;
  3539. result[1] = 0;
  3540. term1 = b / 3.0;
  3541. if (discriminant > 0) {
  3542. s = r + Math.sqrt(discriminant);
  3543. s = s < 0 ? -Math.pow(-s, 1.0 / 3.0) : Math.pow(s, 1.0 / 3.0);
  3544. t = r - Math.sqrt(discriminant);
  3545. t = t < 0 ? -Math.pow(-t, 1.0 / 3.0) : Math.pow(t, 1.0 / 3.0);
  3546. result[0] = -term1 + s + t;
  3547. term1 += (s + t) / 2.0;
  3548. result[4] = result[2] = -term1;
  3549. term1 = Math.sqrt(3.0) * (-t + s) / 2;
  3550. result[3] = term1;
  3551. result[5] = -term1;
  3552. return;
  3553. }
  3554. result[5] = result[3] = 0;
  3555. if (discriminant === 0) {
  3556. r13 = r < 0 ? -Math.pow(-r, 1.0 / 3.0) : Math.pow(r, 1.0 / 3.0);
  3557. result[0] = -term1 + 2.0 * r13;
  3558. result[4] = result[2] = -(r13 + term1);
  3559. return;
  3560. }
  3561. q = -q;
  3562. dum1 = q * q * q;
  3563. dum1 = Math.acos(r / Math.sqrt(dum1));
  3564. r13 = 2.0 * Math.sqrt(q);
  3565. result[0] = -term1 + r13 * Math.cos(dum1 / 3.0);
  3566. result[2] = -term1 + r13 * Math.cos((dum1 + 2.0 * Math.PI) / 3.0);
  3567. result[4] = -term1 + r13 * Math.cos((dum1 + 4.0 * Math.PI) / 3.0);
  3568. return;
  3569. };
  3570. var sqdistToQuadraticBezier = function sqdistToQuadraticBezier(x, y, x1, y1, x2, y2, x3, y3) {
  3571. // Find minimum distance by using the minimum of the distance
  3572. // function between the given point and the curve
  3573. // This gives the coefficients of the resulting cubic equation
  3574. // whose roots tell us where a possible minimum is
  3575. // (Coefficients are divided by 4)
  3576. var a = 1.0 * x1 * x1 - 4 * x1 * x2 + 2 * x1 * x3 + 4 * x2 * x2 - 4 * x2 * x3 + x3 * x3 + y1 * y1 - 4 * y1 * y2 + 2 * y1 * y3 + 4 * y2 * y2 - 4 * y2 * y3 + y3 * y3;
  3577. var b = 1.0 * 9 * x1 * x2 - 3 * x1 * x1 - 3 * x1 * x3 - 6 * x2 * x2 + 3 * x2 * x3 + 9 * y1 * y2 - 3 * y1 * y1 - 3 * y1 * y3 - 6 * y2 * y2 + 3 * y2 * y3;
  3578. var c = 1.0 * 3 * x1 * x1 - 6 * x1 * x2 + x1 * x3 - x1 * x + 2 * x2 * x2 + 2 * x2 * x - x3 * x + 3 * y1 * y1 - 6 * y1 * y2 + y1 * y3 - y1 * y + 2 * y2 * y2 + 2 * y2 * y - y3 * y;
  3579. var d = 1.0 * x1 * x2 - x1 * x1 + x1 * x - x2 * x + y1 * y2 - y1 * y1 + y1 * y - y2 * y;
  3580. // debug("coefficients: " + a / a + ", " + b / a + ", " + c / a + ", " + d / a);
  3581. var roots = [];
  3582. // Use the cubic solving algorithm
  3583. solveCubic(a, b, c, d, roots);
  3584. var zeroThreshold = 0.0000001;
  3585. var params = [];
  3586. for (var index = 0; index < 6; index += 2) {
  3587. if (Math.abs(roots[index + 1]) < zeroThreshold && roots[index] >= 0 && roots[index] <= 1.0) {
  3588. params.push(roots[index]);
  3589. }
  3590. }
  3591. params.push(1.0);
  3592. params.push(0.0);
  3593. var minDistanceSquared = -1;
  3594. var curX, curY, distSquared;
  3595. for (var i = 0; i < params.length; i++) {
  3596. curX = Math.pow(1.0 - params[i], 2.0) * x1 + 2.0 * (1 - params[i]) * params[i] * x2 + params[i] * params[i] * x3;
  3597. curY = Math.pow(1 - params[i], 2.0) * y1 + 2 * (1.0 - params[i]) * params[i] * y2 + params[i] * params[i] * y3;
  3598. distSquared = Math.pow(curX - x, 2) + Math.pow(curY - y, 2);
  3599. // debug('distance for param ' + params[i] + ": " + Math.sqrt(distSquared));
  3600. if (minDistanceSquared >= 0) {
  3601. if (distSquared < minDistanceSquared) {
  3602. minDistanceSquared = distSquared;
  3603. }
  3604. } else {
  3605. minDistanceSquared = distSquared;
  3606. }
  3607. }
  3608. return minDistanceSquared;
  3609. };
  3610. var sqdistToFiniteLine = function sqdistToFiniteLine(x, y, x1, y1, x2, y2) {
  3611. var offset = [x - x1, y - y1];
  3612. var line = [x2 - x1, y2 - y1];
  3613. var lineSq = line[0] * line[0] + line[1] * line[1];
  3614. var hypSq = offset[0] * offset[0] + offset[1] * offset[1];
  3615. var dotProduct = offset[0] * line[0] + offset[1] * line[1];
  3616. var adjSq = dotProduct * dotProduct / lineSq;
  3617. if (dotProduct < 0) {
  3618. return hypSq;
  3619. }
  3620. if (adjSq > lineSq) {
  3621. return (x - x2) * (x - x2) + (y - y2) * (y - y2);
  3622. }
  3623. return hypSq - adjSq;
  3624. };
  3625. var pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {
  3626. var x1, y1, x2, y2;
  3627. var y3;
  3628. // Intersect with vertical line through (x, y)
  3629. var up = 0;
  3630. // let down = 0;
  3631. for (var i = 0; i < points.length / 2; i++) {
  3632. x1 = points[i * 2];
  3633. y1 = points[i * 2 + 1];
  3634. if (i + 1 < points.length / 2) {
  3635. x2 = points[(i + 1) * 2];
  3636. y2 = points[(i + 1) * 2 + 1];
  3637. } else {
  3638. x2 = points[(i + 1 - points.length / 2) * 2];
  3639. y2 = points[(i + 1 - points.length / 2) * 2 + 1];
  3640. }
  3641. if (x1 == x && x2 == x) ; else if (x1 >= x && x >= x2 || x1 <= x && x <= x2) {
  3642. y3 = (x - x1) / (x2 - x1) * (y2 - y1) + y1;
  3643. if (y3 > y) {
  3644. up++;
  3645. }
  3646. // if( y3 < y ){
  3647. // down++;
  3648. // }
  3649. } else {
  3650. continue;
  3651. }
  3652. }
  3653. if (up % 2 === 0) {
  3654. return false;
  3655. } else {
  3656. return true;
  3657. }
  3658. };
  3659. var pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {
  3660. var transformedPoints = new Array(basePoints.length);
  3661. // Gives negative angle
  3662. var angle;
  3663. if (direction[0] != null) {
  3664. angle = Math.atan(direction[1] / direction[0]);
  3665. if (direction[0] < 0) {
  3666. angle = angle + Math.PI / 2;
  3667. } else {
  3668. angle = -angle - Math.PI / 2;
  3669. }
  3670. } else {
  3671. angle = direction;
  3672. }
  3673. var cos = Math.cos(-angle);
  3674. var sin = Math.sin(-angle);
  3675. // console.log("base: " + basePoints);
  3676. for (var i = 0; i < transformedPoints.length / 2; i++) {
  3677. transformedPoints[i * 2] = width / 2 * (basePoints[i * 2] * cos - basePoints[i * 2 + 1] * sin);
  3678. transformedPoints[i * 2 + 1] = height / 2 * (basePoints[i * 2 + 1] * cos + basePoints[i * 2] * sin);
  3679. transformedPoints[i * 2] += centerX;
  3680. transformedPoints[i * 2 + 1] += centerY;
  3681. }
  3682. var points;
  3683. if (padding > 0) {
  3684. var expandedLineSet = expandPolygon(transformedPoints, -padding);
  3685. points = joinLines(expandedLineSet);
  3686. } else {
  3687. points = transformedPoints;
  3688. }
  3689. return pointInsidePolygonPoints(x, y, points);
  3690. };
  3691. var pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height, corners) {
  3692. var cutPolygonPoints = new Array(basePoints.length * 2);
  3693. for (var i = 0; i < corners.length; i++) {
  3694. var corner = corners[i];
  3695. cutPolygonPoints[i * 4 + 0] = corner.startX;
  3696. cutPolygonPoints[i * 4 + 1] = corner.startY;
  3697. cutPolygonPoints[i * 4 + 2] = corner.stopX;
  3698. cutPolygonPoints[i * 4 + 3] = corner.stopY;
  3699. var squaredDistance = Math.pow(corner.cx - x, 2) + Math.pow(corner.cy - y, 2);
  3700. if (squaredDistance <= Math.pow(corner.radius, 2)) {
  3701. return true;
  3702. }
  3703. }
  3704. return pointInsidePolygonPoints(x, y, cutPolygonPoints);
  3705. };
  3706. var joinLines = function joinLines(lineSet) {
  3707. var vertices = new Array(lineSet.length / 2);
  3708. var currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY;
  3709. var nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY;
  3710. for (var i = 0; i < lineSet.length / 4; i++) {
  3711. currentLineStartX = lineSet[i * 4];
  3712. currentLineStartY = lineSet[i * 4 + 1];
  3713. currentLineEndX = lineSet[i * 4 + 2];
  3714. currentLineEndY = lineSet[i * 4 + 3];
  3715. if (i < lineSet.length / 4 - 1) {
  3716. nextLineStartX = lineSet[(i + 1) * 4];
  3717. nextLineStartY = lineSet[(i + 1) * 4 + 1];
  3718. nextLineEndX = lineSet[(i + 1) * 4 + 2];
  3719. nextLineEndY = lineSet[(i + 1) * 4 + 3];
  3720. } else {
  3721. nextLineStartX = lineSet[0];
  3722. nextLineStartY = lineSet[1];
  3723. nextLineEndX = lineSet[2];
  3724. nextLineEndY = lineSet[3];
  3725. }
  3726. var intersection = finiteLinesIntersect(currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY, nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY, true);
  3727. vertices[i * 2] = intersection[0];
  3728. vertices[i * 2 + 1] = intersection[1];
  3729. }
  3730. return vertices;
  3731. };
  3732. var expandPolygon = function expandPolygon(points, pad) {
  3733. var expandedLineSet = new Array(points.length * 2);
  3734. var currentPointX, currentPointY, nextPointX, nextPointY;
  3735. for (var i = 0; i < points.length / 2; i++) {
  3736. currentPointX = points[i * 2];
  3737. currentPointY = points[i * 2 + 1];
  3738. if (i < points.length / 2 - 1) {
  3739. nextPointX = points[(i + 1) * 2];
  3740. nextPointY = points[(i + 1) * 2 + 1];
  3741. } else {
  3742. nextPointX = points[0];
  3743. nextPointY = points[1];
  3744. }
  3745. // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]
  3746. // Assume CCW polygon winding
  3747. var offsetX = nextPointY - currentPointY;
  3748. var offsetY = -(nextPointX - currentPointX);
  3749. // Normalize
  3750. var offsetLength = Math.sqrt(offsetX * offsetX + offsetY * offsetY);
  3751. var normalizedOffsetX = offsetX / offsetLength;
  3752. var normalizedOffsetY = offsetY / offsetLength;
  3753. expandedLineSet[i * 4] = currentPointX + normalizedOffsetX * pad;
  3754. expandedLineSet[i * 4 + 1] = currentPointY + normalizedOffsetY * pad;
  3755. expandedLineSet[i * 4 + 2] = nextPointX + normalizedOffsetX * pad;
  3756. expandedLineSet[i * 4 + 3] = nextPointY + normalizedOffsetY * pad;
  3757. }
  3758. return expandedLineSet;
  3759. };
  3760. var intersectLineEllipse = function intersectLineEllipse(x, y, centerX, centerY, ellipseWradius, ellipseHradius) {
  3761. var dispX = centerX - x;
  3762. var dispY = centerY - y;
  3763. dispX /= ellipseWradius;
  3764. dispY /= ellipseHradius;
  3765. var len = Math.sqrt(dispX * dispX + dispY * dispY);
  3766. var newLength = len - 1;
  3767. if (newLength < 0) {
  3768. return [];
  3769. }
  3770. var lenProportion = newLength / len;
  3771. return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];
  3772. };
  3773. var checkInEllipse = function checkInEllipse(x, y, width, height, centerX, centerY, padding) {
  3774. x -= centerX;
  3775. y -= centerY;
  3776. x /= width / 2 + padding;
  3777. y /= height / 2 + padding;
  3778. return x * x + y * y <= 1;
  3779. };
  3780. // Returns intersections of increasing distance from line's start point
  3781. var intersectLineCircle = function intersectLineCircle(x1, y1, x2, y2, centerX, centerY, radius) {
  3782. // Calculate d, direction vector of line
  3783. var d = [x2 - x1, y2 - y1]; // Direction vector of line
  3784. var f = [x1 - centerX, y1 - centerY];
  3785. var a = d[0] * d[0] + d[1] * d[1];
  3786. var b = 2 * (f[0] * d[0] + f[1] * d[1]);
  3787. var c = f[0] * f[0] + f[1] * f[1] - radius * radius;
  3788. var discriminant = b * b - 4 * a * c;
  3789. if (discriminant < 0) {
  3790. return [];
  3791. }
  3792. var t1 = (-b + Math.sqrt(discriminant)) / (2 * a);
  3793. var t2 = (-b - Math.sqrt(discriminant)) / (2 * a);
  3794. var tMin = Math.min(t1, t2);
  3795. var tMax = Math.max(t1, t2);
  3796. var inRangeParams = [];
  3797. if (tMin >= 0 && tMin <= 1) {
  3798. inRangeParams.push(tMin);
  3799. }
  3800. if (tMax >= 0 && tMax <= 1) {
  3801. inRangeParams.push(tMax);
  3802. }
  3803. if (inRangeParams.length === 0) {
  3804. return [];
  3805. }
  3806. var nearIntersectionX = inRangeParams[0] * d[0] + x1;
  3807. var nearIntersectionY = inRangeParams[0] * d[1] + y1;
  3808. if (inRangeParams.length > 1) {
  3809. if (inRangeParams[0] == inRangeParams[1]) {
  3810. return [nearIntersectionX, nearIntersectionY];
  3811. } else {
  3812. var farIntersectionX = inRangeParams[1] * d[0] + x1;
  3813. var farIntersectionY = inRangeParams[1] * d[1] + y1;
  3814. return [nearIntersectionX, nearIntersectionY, farIntersectionX, farIntersectionY];
  3815. }
  3816. } else {
  3817. return [nearIntersectionX, nearIntersectionY];
  3818. }
  3819. };
  3820. var midOfThree = function midOfThree(a, b, c) {
  3821. if (b <= a && a <= c || c <= a && a <= b) {
  3822. return a;
  3823. } else if (a <= b && b <= c || c <= b && b <= a) {
  3824. return b;
  3825. } else {
  3826. return c;
  3827. }
  3828. };
  3829. // (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)
  3830. var finiteLinesIntersect = function finiteLinesIntersect(x1, y1, x2, y2, x3, y3, x4, y4, infiniteLines) {
  3831. var dx13 = x1 - x3;
  3832. var dx21 = x2 - x1;
  3833. var dx43 = x4 - x3;
  3834. var dy13 = y1 - y3;
  3835. var dy21 = y2 - y1;
  3836. var dy43 = y4 - y3;
  3837. var ua_t = dx43 * dy13 - dy43 * dx13;
  3838. var ub_t = dx21 * dy13 - dy21 * dx13;
  3839. var u_b = dy43 * dx21 - dx43 * dy21;
  3840. if (u_b !== 0) {
  3841. var ua = ua_t / u_b;
  3842. var ub = ub_t / u_b;
  3843. var flptThreshold = 0.001;
  3844. var _min = 0 - flptThreshold;
  3845. var _max = 1 + flptThreshold;
  3846. if (_min <= ua && ua <= _max && _min <= ub && ub <= _max) {
  3847. return [x1 + ua * dx21, y1 + ua * dy21];
  3848. } else {
  3849. if (!infiniteLines) {
  3850. return [];
  3851. } else {
  3852. return [x1 + ua * dx21, y1 + ua * dy21];
  3853. }
  3854. }
  3855. } else {
  3856. if (ua_t === 0 || ub_t === 0) {
  3857. // Parallel, coincident lines. Check if overlap
  3858. // Check endpoint of second line
  3859. if (midOfThree(x1, x2, x4) === x4) {
  3860. return [x4, y4];
  3861. }
  3862. // Check start point of second line
  3863. if (midOfThree(x1, x2, x3) === x3) {
  3864. return [x3, y3];
  3865. }
  3866. // Endpoint of first line
  3867. if (midOfThree(x3, x4, x2) === x2) {
  3868. return [x2, y2];
  3869. }
  3870. return [];
  3871. } else {
  3872. // Parallel, non-coincident
  3873. return [];
  3874. }
  3875. }
  3876. };
  3877. var transformPoints = function transformPoints(points, centerX, centerY, width, height) {
  3878. var ret = [];
  3879. var halfW = width / 2;
  3880. var halfH = height / 2;
  3881. var x = centerX;
  3882. var y = centerY;
  3883. ret.push({
  3884. x: x + halfW * points[0],
  3885. y: y + halfH * points[1]
  3886. });
  3887. for (var i = 1; i < points.length / 2; i++) {
  3888. ret.push({
  3889. x: x + halfW * points[i * 2],
  3890. y: y + halfH * points[i * 2 + 1]
  3891. });
  3892. }
  3893. return ret;
  3894. };
  3895. // math.polygonIntersectLine( x, y, basePoints, centerX, centerY, width, height, padding )
  3896. // intersect a node polygon (pts transformed)
  3897. //
  3898. // math.polygonIntersectLine( x, y, basePoints, centerX, centerY )
  3899. // intersect the points (no transform)
  3900. var polygonIntersectLine = function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {
  3901. var intersections = [];
  3902. var intersection;
  3903. var transformedPoints = new Array(basePoints.length);
  3904. var doTransform = true;
  3905. if (width == null) {
  3906. doTransform = false;
  3907. }
  3908. var points;
  3909. if (doTransform) {
  3910. for (var i = 0; i < transformedPoints.length / 2; i++) {
  3911. transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;
  3912. transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;
  3913. }
  3914. if (padding > 0) {
  3915. var expandedLineSet = expandPolygon(transformedPoints, -padding);
  3916. points = joinLines(expandedLineSet);
  3917. } else {
  3918. points = transformedPoints;
  3919. }
  3920. } else {
  3921. points = basePoints;
  3922. }
  3923. var currentX, currentY, nextX, nextY;
  3924. for (var _i3 = 0; _i3 < points.length / 2; _i3++) {
  3925. currentX = points[_i3 * 2];
  3926. currentY = points[_i3 * 2 + 1];
  3927. if (_i3 < points.length / 2 - 1) {
  3928. nextX = points[(_i3 + 1) * 2];
  3929. nextY = points[(_i3 + 1) * 2 + 1];
  3930. } else {
  3931. nextX = points[0];
  3932. nextY = points[1];
  3933. }
  3934. intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);
  3935. if (intersection.length !== 0) {
  3936. intersections.push(intersection[0], intersection[1]);
  3937. }
  3938. }
  3939. return intersections;
  3940. };
  3941. var roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding, corners) {
  3942. var intersections = [];
  3943. var intersection;
  3944. var lines = new Array(basePoints.length * 2);
  3945. corners.forEach(function (corner, i) {
  3946. if (i === 0) {
  3947. lines[lines.length - 2] = corner.startX;
  3948. lines[lines.length - 1] = corner.startY;
  3949. } else {
  3950. lines[i * 4 - 2] = corner.startX;
  3951. lines[i * 4 - 1] = corner.startY;
  3952. }
  3953. lines[i * 4] = corner.stopX;
  3954. lines[i * 4 + 1] = corner.stopY;
  3955. intersection = intersectLineCircle(x, y, centerX, centerY, corner.cx, corner.cy, corner.radius);
  3956. if (intersection.length !== 0) {
  3957. intersections.push(intersection[0], intersection[1]);
  3958. }
  3959. });
  3960. for (var i = 0; i < lines.length / 4; i++) {
  3961. intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[i * 4], lines[i * 4 + 1], lines[i * 4 + 2], lines[i * 4 + 3], false);
  3962. if (intersection.length !== 0) {
  3963. intersections.push(intersection[0], intersection[1]);
  3964. }
  3965. }
  3966. if (intersections.length > 2) {
  3967. var lowestIntersection = [intersections[0], intersections[1]];
  3968. var lowestSquaredDistance = Math.pow(lowestIntersection[0] - x, 2) + Math.pow(lowestIntersection[1] - y, 2);
  3969. for (var _i4 = 1; _i4 < intersections.length / 2; _i4++) {
  3970. var squaredDistance = Math.pow(intersections[_i4 * 2] - x, 2) + Math.pow(intersections[_i4 * 2 + 1] - y, 2);
  3971. if (squaredDistance <= lowestSquaredDistance) {
  3972. lowestIntersection[0] = intersections[_i4 * 2];
  3973. lowestIntersection[1] = intersections[_i4 * 2 + 1];
  3974. lowestSquaredDistance = squaredDistance;
  3975. }
  3976. }
  3977. return lowestIntersection;
  3978. }
  3979. return intersections;
  3980. };
  3981. var shortenIntersection = function shortenIntersection(intersection, offset, amount) {
  3982. var disp = [intersection[0] - offset[0], intersection[1] - offset[1]];
  3983. var length = Math.sqrt(disp[0] * disp[0] + disp[1] * disp[1]);
  3984. var lenRatio = (length - amount) / length;
  3985. if (lenRatio < 0) {
  3986. lenRatio = 0.00001;
  3987. }
  3988. return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];
  3989. };
  3990. var generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {
  3991. var points = generateUnitNgonPoints(sides, rotationRadians);
  3992. points = fitPolygonToSquare(points);
  3993. return points;
  3994. };
  3995. var fitPolygonToSquare = function fitPolygonToSquare(points) {
  3996. var x, y;
  3997. var sides = points.length / 2;
  3998. var minX = Infinity,
  3999. minY = Infinity,
  4000. maxX = -Infinity,
  4001. maxY = -Infinity;
  4002. for (var i = 0; i < sides; i++) {
  4003. x = points[2 * i];
  4004. y = points[2 * i + 1];
  4005. minX = Math.min(minX, x);
  4006. maxX = Math.max(maxX, x);
  4007. minY = Math.min(minY, y);
  4008. maxY = Math.max(maxY, y);
  4009. }
  4010. // stretch factors
  4011. var sx = 2 / (maxX - minX);
  4012. var sy = 2 / (maxY - minY);
  4013. for (var _i5 = 0; _i5 < sides; _i5++) {
  4014. x = points[2 * _i5] = points[2 * _i5] * sx;
  4015. y = points[2 * _i5 + 1] = points[2 * _i5 + 1] * sy;
  4016. minX = Math.min(minX, x);
  4017. maxX = Math.max(maxX, x);
  4018. minY = Math.min(minY, y);
  4019. maxY = Math.max(maxY, y);
  4020. }
  4021. if (minY < -1) {
  4022. for (var _i6 = 0; _i6 < sides; _i6++) {
  4023. y = points[2 * _i6 + 1] = points[2 * _i6 + 1] + (-1 - minY);
  4024. }
  4025. }
  4026. return points;
  4027. };
  4028. var generateUnitNgonPoints = function generateUnitNgonPoints(sides, rotationRadians) {
  4029. var increment = 1.0 / sides * 2 * Math.PI;
  4030. var startAngle = sides % 2 === 0 ? Math.PI / 2.0 + increment / 2.0 : Math.PI / 2.0;
  4031. startAngle += rotationRadians;
  4032. var points = new Array(sides * 2);
  4033. var currentAngle;
  4034. for (var i = 0; i < sides; i++) {
  4035. currentAngle = i * increment + startAngle;
  4036. points[2 * i] = Math.cos(currentAngle); // x
  4037. points[2 * i + 1] = Math.sin(-currentAngle); // y
  4038. }
  4039. return points;
  4040. };
  4041. // Set the default radius, unless half of width or height is smaller than default
  4042. var getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {
  4043. return Math.min(width / 4, height / 4, 8);
  4044. };
  4045. // Set the default radius
  4046. var getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {
  4047. return Math.min(width / 10, height / 10, 8);
  4048. };
  4049. var getCutRectangleCornerLength = function getCutRectangleCornerLength() {
  4050. return 8;
  4051. };
  4052. var bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {
  4053. return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];
  4054. };
  4055. // get curve width, height, and control point position offsets as a percentage of node height / width
  4056. var getBarrelCurveConstants = function getBarrelCurveConstants(width, height) {
  4057. return {
  4058. heightOffset: Math.min(15, 0.05 * height),
  4059. widthOffset: Math.min(100, 0.25 * width),
  4060. ctrlPtOffsetPct: 0.05
  4061. };
  4062. };
  4063. // Separating Axis Theorem (SAT) to determine if two polygons intersect.
  4064. // The function takes two polygons as input and returns a boolean value indicating
  4065. // whether the two polygons intersect.
  4066. function satPolygonIntersection(poly1, poly2) {
  4067. function getAxes(polygon) {
  4068. var axes = [];
  4069. for (var i = 0; i < polygon.length; i++) {
  4070. var p1 = polygon[i];
  4071. var p2 = polygon[(i + 1) % polygon.length];
  4072. var edge = {
  4073. x: p2.x - p1.x,
  4074. y: p2.y - p1.y
  4075. };
  4076. var normal = {
  4077. x: -edge.y,
  4078. y: edge.x
  4079. };
  4080. var length = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
  4081. axes.push({
  4082. x: normal.x / length,
  4083. y: normal.y / length
  4084. });
  4085. }
  4086. return axes;
  4087. }
  4088. function project(polygon, axis) {
  4089. var min = Infinity;
  4090. var max = -Infinity;
  4091. var _iterator = _createForOfIteratorHelper(polygon),
  4092. _step;
  4093. try {
  4094. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  4095. var point = _step.value;
  4096. var projection = point.x * axis.x + point.y * axis.y;
  4097. min = Math.min(min, projection);
  4098. max = Math.max(max, projection);
  4099. }
  4100. } catch (err) {
  4101. _iterator.e(err);
  4102. } finally {
  4103. _iterator.f();
  4104. }
  4105. return {
  4106. min: min,
  4107. max: max
  4108. };
  4109. }
  4110. function overlaps(proj1, proj2) {
  4111. return !(proj1.max < proj2.min || proj2.max < proj1.min);
  4112. }
  4113. var axes = [].concat(_toConsumableArray(getAxes(poly1)), _toConsumableArray(getAxes(poly2)));
  4114. var _iterator2 = _createForOfIteratorHelper(axes),
  4115. _step2;
  4116. try {
  4117. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  4118. var axis = _step2.value;
  4119. var proj1 = project(poly1, axis);
  4120. var proj2 = project(poly2, axis);
  4121. if (!overlaps(proj1, proj2)) {
  4122. return false; // No overlap, so the polygons do not intersect
  4123. }
  4124. }
  4125. } catch (err) {
  4126. _iterator2.e(err);
  4127. } finally {
  4128. _iterator2.f();
  4129. }
  4130. return true; // polygons intersect
  4131. }
  4132. var pageRankDefaults = defaults$g({
  4133. dampingFactor: 0.8,
  4134. precision: 0.000001,
  4135. iterations: 200,
  4136. weight: function weight(edge) {
  4137. return 1;
  4138. }
  4139. });
  4140. var elesfn$o = {
  4141. pageRank: function pageRank(options) {
  4142. var _pageRankDefaults = pageRankDefaults(options),
  4143. dampingFactor = _pageRankDefaults.dampingFactor,
  4144. precision = _pageRankDefaults.precision,
  4145. iterations = _pageRankDefaults.iterations,
  4146. weight = _pageRankDefaults.weight;
  4147. var cy = this._private.cy;
  4148. var _this$byGroup = this.byGroup(),
  4149. nodes = _this$byGroup.nodes,
  4150. edges = _this$byGroup.edges;
  4151. var numNodes = nodes.length;
  4152. var numNodesSqd = numNodes * numNodes;
  4153. var numEdges = edges.length;
  4154. // Construct transposed adjacency matrix
  4155. // First lets have a zeroed matrix of the right size
  4156. // We'll also keep track of the sum of each column
  4157. var matrix = new Array(numNodesSqd);
  4158. var columnSum = new Array(numNodes);
  4159. var additionalProb = (1 - dampingFactor) / numNodes;
  4160. // Create null matrix
  4161. for (var i = 0; i < numNodes; i++) {
  4162. for (var j = 0; j < numNodes; j++) {
  4163. var n = i * numNodes + j;
  4164. matrix[n] = 0;
  4165. }
  4166. columnSum[i] = 0;
  4167. }
  4168. // Now, process edges
  4169. for (var _i = 0; _i < numEdges; _i++) {
  4170. var edge = edges[_i];
  4171. var srcId = edge.data('source');
  4172. var tgtId = edge.data('target');
  4173. // Don't include loops in the matrix
  4174. if (srcId === tgtId) {
  4175. continue;
  4176. }
  4177. var s = nodes.indexOfId(srcId);
  4178. var t = nodes.indexOfId(tgtId);
  4179. var w = weight(edge);
  4180. var _n = t * numNodes + s;
  4181. // Update matrix
  4182. matrix[_n] += w;
  4183. // Update column sum
  4184. columnSum[s] += w;
  4185. }
  4186. // Add additional probability based on damping factor
  4187. // Also, take into account columns that have sum = 0
  4188. var p = 1.0 / numNodes + additionalProb; // Shorthand
  4189. // Traverse matrix, column by column
  4190. for (var _j = 0; _j < numNodes; _j++) {
  4191. if (columnSum[_j] === 0) {
  4192. // No 'links' out from node jth, assume equal probability for each possible node
  4193. for (var _i2 = 0; _i2 < numNodes; _i2++) {
  4194. var _n2 = _i2 * numNodes + _j;
  4195. matrix[_n2] = p;
  4196. }
  4197. } else {
  4198. // Node jth has outgoing link, compute normalized probabilities
  4199. for (var _i3 = 0; _i3 < numNodes; _i3++) {
  4200. var _n3 = _i3 * numNodes + _j;
  4201. matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;
  4202. }
  4203. }
  4204. }
  4205. // Compute dominant eigenvector using power method
  4206. var eigenvector = new Array(numNodes);
  4207. var temp = new Array(numNodes);
  4208. var previous;
  4209. // Start with a vector of all 1's
  4210. // Also, initialize a null vector which will be used as shorthand
  4211. for (var _i4 = 0; _i4 < numNodes; _i4++) {
  4212. eigenvector[_i4] = 1;
  4213. }
  4214. for (var iter = 0; iter < iterations; iter++) {
  4215. // Temp array with all 0's
  4216. for (var _i5 = 0; _i5 < numNodes; _i5++) {
  4217. temp[_i5] = 0;
  4218. }
  4219. // Multiply matrix with previous result
  4220. for (var _i6 = 0; _i6 < numNodes; _i6++) {
  4221. for (var _j2 = 0; _j2 < numNodes; _j2++) {
  4222. var _n4 = _i6 * numNodes + _j2;
  4223. temp[_i6] += matrix[_n4] * eigenvector[_j2];
  4224. }
  4225. }
  4226. inPlaceSumNormalize(temp);
  4227. previous = eigenvector;
  4228. eigenvector = temp;
  4229. temp = previous;
  4230. var diff = 0;
  4231. // Compute difference (squared module) of both vectors
  4232. for (var _i7 = 0; _i7 < numNodes; _i7++) {
  4233. var delta = previous[_i7] - eigenvector[_i7];
  4234. diff += delta * delta;
  4235. }
  4236. // If difference is less than the desired threshold, stop iterating
  4237. if (diff < precision) {
  4238. break;
  4239. }
  4240. }
  4241. // Construct result
  4242. var res = {
  4243. rank: function rank(node) {
  4244. node = cy.collection(node)[0];
  4245. return eigenvector[nodes.indexOf(node)];
  4246. }
  4247. };
  4248. return res;
  4249. } // pageRank
  4250. }; // elesfn
  4251. var defaults$f = defaults$g({
  4252. root: null,
  4253. weight: function weight(edge) {
  4254. return 1;
  4255. },
  4256. directed: false,
  4257. alpha: 0
  4258. });
  4259. var elesfn$n = {
  4260. degreeCentralityNormalized: function degreeCentralityNormalized(options) {
  4261. options = defaults$f(options);
  4262. var cy = this.cy();
  4263. var nodes = this.nodes();
  4264. var numNodes = nodes.length;
  4265. if (!options.directed) {
  4266. var degrees = {};
  4267. var maxDegree = 0;
  4268. for (var i = 0; i < numNodes; i++) {
  4269. var node = nodes[i];
  4270. // add current node to the current options object and call degreeCentrality
  4271. options.root = node;
  4272. var currDegree = this.degreeCentrality(options);
  4273. if (maxDegree < currDegree.degree) {
  4274. maxDegree = currDegree.degree;
  4275. }
  4276. degrees[node.id()] = currDegree.degree;
  4277. }
  4278. return {
  4279. degree: function degree(node) {
  4280. if (maxDegree === 0) {
  4281. return 0;
  4282. }
  4283. if (string(node)) {
  4284. // from is a selector string
  4285. node = cy.filter(node);
  4286. }
  4287. return degrees[node.id()] / maxDegree;
  4288. }
  4289. };
  4290. } else {
  4291. var indegrees = {};
  4292. var outdegrees = {};
  4293. var maxIndegree = 0;
  4294. var maxOutdegree = 0;
  4295. for (var _i = 0; _i < numNodes; _i++) {
  4296. var _node = nodes[_i];
  4297. var id = _node.id();
  4298. // add current node to the current options object and call degreeCentrality
  4299. options.root = _node;
  4300. var _currDegree = this.degreeCentrality(options);
  4301. if (maxIndegree < _currDegree.indegree) maxIndegree = _currDegree.indegree;
  4302. if (maxOutdegree < _currDegree.outdegree) maxOutdegree = _currDegree.outdegree;
  4303. indegrees[id] = _currDegree.indegree;
  4304. outdegrees[id] = _currDegree.outdegree;
  4305. }
  4306. return {
  4307. indegree: function indegree(node) {
  4308. if (maxIndegree == 0) {
  4309. return 0;
  4310. }
  4311. if (string(node)) {
  4312. // from is a selector string
  4313. node = cy.filter(node);
  4314. }
  4315. return indegrees[node.id()] / maxIndegree;
  4316. },
  4317. outdegree: function outdegree(node) {
  4318. if (maxOutdegree === 0) {
  4319. return 0;
  4320. }
  4321. if (string(node)) {
  4322. // from is a selector string
  4323. node = cy.filter(node);
  4324. }
  4325. return outdegrees[node.id()] / maxOutdegree;
  4326. }
  4327. };
  4328. }
  4329. },
  4330. // degreeCentralityNormalized
  4331. // Implemented from the algorithm in Opsahl's paper
  4332. // "Node centrality in weighted networks: Generalizing degree and shortest paths"
  4333. // check the heading 2 "Degree"
  4334. degreeCentrality: function degreeCentrality(options) {
  4335. options = defaults$f(options);
  4336. var cy = this.cy();
  4337. var callingEles = this;
  4338. var _options = options,
  4339. root = _options.root,
  4340. weight = _options.weight,
  4341. directed = _options.directed,
  4342. alpha = _options.alpha;
  4343. root = cy.collection(root)[0];
  4344. if (!directed) {
  4345. var connEdges = root.connectedEdges().intersection(callingEles);
  4346. var k = connEdges.length;
  4347. var s = 0;
  4348. // Now, sum edge weights
  4349. for (var i = 0; i < connEdges.length; i++) {
  4350. s += weight(connEdges[i]);
  4351. }
  4352. return {
  4353. degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha)
  4354. };
  4355. } else {
  4356. var edges = root.connectedEdges();
  4357. var incoming = edges.filter(function (edge) {
  4358. return edge.target().same(root) && callingEles.has(edge);
  4359. });
  4360. var outgoing = edges.filter(function (edge) {
  4361. return edge.source().same(root) && callingEles.has(edge);
  4362. });
  4363. var k_in = incoming.length;
  4364. var k_out = outgoing.length;
  4365. var s_in = 0;
  4366. var s_out = 0;
  4367. // Now, sum incoming edge weights
  4368. for (var _i2 = 0; _i2 < incoming.length; _i2++) {
  4369. s_in += weight(incoming[_i2]);
  4370. }
  4371. // Now, sum outgoing edge weights
  4372. for (var _i3 = 0; _i3 < outgoing.length; _i3++) {
  4373. s_out += weight(outgoing[_i3]);
  4374. }
  4375. return {
  4376. indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha),
  4377. outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha)
  4378. };
  4379. }
  4380. } // degreeCentrality
  4381. }; // elesfn
  4382. // nice, short mathematical alias
  4383. elesfn$n.dc = elesfn$n.degreeCentrality;
  4384. elesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;
  4385. var defaults$e = defaults$g({
  4386. harmonic: true,
  4387. weight: function weight() {
  4388. return 1;
  4389. },
  4390. directed: false,
  4391. root: null
  4392. });
  4393. var elesfn$m = {
  4394. closenessCentralityNormalized: function closenessCentralityNormalized(options) {
  4395. var _defaults = defaults$e(options),
  4396. harmonic = _defaults.harmonic,
  4397. weight = _defaults.weight,
  4398. directed = _defaults.directed;
  4399. var cy = this.cy();
  4400. var closenesses = {};
  4401. var maxCloseness = 0;
  4402. var nodes = this.nodes();
  4403. var fw = this.floydWarshall({
  4404. weight: weight,
  4405. directed: directed
  4406. });
  4407. // Compute closeness for every node and find the maximum closeness
  4408. for (var i = 0; i < nodes.length; i++) {
  4409. var currCloseness = 0;
  4410. var node_i = nodes[i];
  4411. for (var j = 0; j < nodes.length; j++) {
  4412. if (i !== j) {
  4413. var d = fw.distance(node_i, nodes[j]);
  4414. if (harmonic) {
  4415. currCloseness += 1 / d;
  4416. } else {
  4417. currCloseness += d;
  4418. }
  4419. }
  4420. }
  4421. if (!harmonic) {
  4422. currCloseness = 1 / currCloseness;
  4423. }
  4424. if (maxCloseness < currCloseness) {
  4425. maxCloseness = currCloseness;
  4426. }
  4427. closenesses[node_i.id()] = currCloseness;
  4428. }
  4429. return {
  4430. closeness: function closeness(node) {
  4431. if (maxCloseness == 0) {
  4432. return 0;
  4433. }
  4434. if (string(node)) {
  4435. // from is a selector string
  4436. node = cy.filter(node)[0].id();
  4437. } else {
  4438. // from is a node
  4439. node = node.id();
  4440. }
  4441. return closenesses[node] / maxCloseness;
  4442. }
  4443. };
  4444. },
  4445. // Implemented from pseudocode from wikipedia
  4446. closenessCentrality: function closenessCentrality(options) {
  4447. var _defaults2 = defaults$e(options),
  4448. root = _defaults2.root,
  4449. weight = _defaults2.weight,
  4450. directed = _defaults2.directed,
  4451. harmonic = _defaults2.harmonic;
  4452. root = this.filter(root)[0];
  4453. // we need distance from this node to every other node
  4454. var dijkstra = this.dijkstra({
  4455. root: root,
  4456. weight: weight,
  4457. directed: directed
  4458. });
  4459. var totalDistance = 0;
  4460. var nodes = this.nodes();
  4461. for (var i = 0; i < nodes.length; i++) {
  4462. var n = nodes[i];
  4463. if (!n.same(root)) {
  4464. var d = dijkstra.distanceTo(n);
  4465. if (harmonic) {
  4466. totalDistance += 1 / d;
  4467. } else {
  4468. totalDistance += d;
  4469. }
  4470. }
  4471. }
  4472. return harmonic ? totalDistance : 1 / totalDistance;
  4473. } // closenessCentrality
  4474. }; // elesfn
  4475. // nice, short mathematical alias
  4476. elesfn$m.cc = elesfn$m.closenessCentrality;
  4477. elesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;
  4478. var defaults$d = defaults$g({
  4479. weight: null,
  4480. directed: false
  4481. });
  4482. var elesfn$l = {
  4483. // Implemented from the algorithm in the paper "On Variants of Shortest-Path Betweenness Centrality and their Generic Computation" by Ulrik Brandes
  4484. betweennessCentrality: function betweennessCentrality(options) {
  4485. var _defaults = defaults$d(options),
  4486. directed = _defaults.directed,
  4487. weight = _defaults.weight;
  4488. var weighted = weight != null;
  4489. var cy = this.cy();
  4490. // starting
  4491. var V = this.nodes();
  4492. var A = {};
  4493. var _C = {};
  4494. var max = 0;
  4495. var C = {
  4496. set: function set(key, val) {
  4497. _C[key] = val;
  4498. if (val > max) {
  4499. max = val;
  4500. }
  4501. },
  4502. get: function get(key) {
  4503. return _C[key];
  4504. }
  4505. };
  4506. // A contains the neighborhoods of every node
  4507. for (var i = 0; i < V.length; i++) {
  4508. var v = V[i];
  4509. var vid = v.id();
  4510. if (directed) {
  4511. A[vid] = v.outgoers().nodes(); // get outgoers of every node
  4512. } else {
  4513. A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node
  4514. }
  4515. C.set(vid, 0);
  4516. }
  4517. var _loop = function _loop() {
  4518. var sid = V[s].id();
  4519. var S = []; // stack
  4520. var P = {};
  4521. var g = {};
  4522. var d = {};
  4523. var Q = new Heap(function (a, b) {
  4524. return d[a] - d[b];
  4525. }); // queue
  4526. // init dictionaries
  4527. for (var _i = 0; _i < V.length; _i++) {
  4528. var _vid = V[_i].id();
  4529. P[_vid] = [];
  4530. g[_vid] = 0;
  4531. d[_vid] = Infinity;
  4532. }
  4533. g[sid] = 1; // sigma
  4534. d[sid] = 0; // distance to s
  4535. Q.push(sid);
  4536. while (!Q.empty()) {
  4537. var _v = Q.pop();
  4538. S.push(_v);
  4539. if (weighted) {
  4540. for (var j = 0; j < A[_v].length; j++) {
  4541. var w = A[_v][j];
  4542. var vEle = cy.getElementById(_v);
  4543. var edge = undefined;
  4544. if (vEle.edgesTo(w).length > 0) {
  4545. edge = vEle.edgesTo(w)[0];
  4546. } else {
  4547. edge = w.edgesTo(vEle)[0];
  4548. }
  4549. var edgeWeight = weight(edge);
  4550. w = w.id();
  4551. if (d[w] > d[_v] + edgeWeight) {
  4552. d[w] = d[_v] + edgeWeight;
  4553. if (Q.nodes.indexOf(w) < 0) {
  4554. //if w is not in Q
  4555. Q.push(w);
  4556. } else {
  4557. // update position if w is in Q
  4558. Q.updateItem(w);
  4559. }
  4560. g[w] = 0;
  4561. P[w] = [];
  4562. }
  4563. if (d[w] == d[_v] + edgeWeight) {
  4564. g[w] = g[w] + g[_v];
  4565. P[w].push(_v);
  4566. }
  4567. }
  4568. } else {
  4569. for (var _j = 0; _j < A[_v].length; _j++) {
  4570. var _w = A[_v][_j].id();
  4571. if (d[_w] == Infinity) {
  4572. Q.push(_w);
  4573. d[_w] = d[_v] + 1;
  4574. }
  4575. if (d[_w] == d[_v] + 1) {
  4576. g[_w] = g[_w] + g[_v];
  4577. P[_w].push(_v);
  4578. }
  4579. }
  4580. }
  4581. }
  4582. var e = {};
  4583. for (var _i2 = 0; _i2 < V.length; _i2++) {
  4584. e[V[_i2].id()] = 0;
  4585. }
  4586. while (S.length > 0) {
  4587. var _w2 = S.pop();
  4588. for (var _j2 = 0; _j2 < P[_w2].length; _j2++) {
  4589. var _v2 = P[_w2][_j2];
  4590. e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]);
  4591. }
  4592. if (_w2 != V[s].id()) {
  4593. C.set(_w2, C.get(_w2) + e[_w2]);
  4594. }
  4595. }
  4596. };
  4597. for (var s = 0; s < V.length; s++) {
  4598. _loop();
  4599. }
  4600. var ret = {
  4601. betweenness: function betweenness(node) {
  4602. var id = cy.collection(node).id();
  4603. return C.get(id);
  4604. },
  4605. betweennessNormalized: function betweennessNormalized(node) {
  4606. if (max == 0) {
  4607. return 0;
  4608. }
  4609. var id = cy.collection(node).id();
  4610. return C.get(id) / max;
  4611. }
  4612. };
  4613. // alias
  4614. ret.betweennessNormalised = ret.betweennessNormalized;
  4615. return ret;
  4616. } // betweennessCentrality
  4617. }; // elesfn
  4618. // nice, short mathematical alias
  4619. elesfn$l.bc = elesfn$l.betweennessCentrality;
  4620. // Implemented by Zoe Xi @zoexi for GSOC 2016
  4621. // https://github.com/cytoscape/cytoscape.js-markov-cluster
  4622. /* eslint-disable no-unused-vars */
  4623. var defaults$c = defaults$g({
  4624. expandFactor: 2,
  4625. // affects time of computation and cluster granularity to some extent: M * M
  4626. inflateFactor: 2,
  4627. // affects cluster granularity (the greater the value, the more clusters): M(i,j) / E(j)
  4628. multFactor: 1,
  4629. // optional self loops for each node. Use a neutral value to improve cluster computations.
  4630. maxIterations: 20,
  4631. // maximum number of iterations of the MCL algorithm in a single run
  4632. attributes: [
  4633. // attributes/features used to group nodes, ie. similarity values between nodes
  4634. function (edge) {
  4635. return 1;
  4636. }]
  4637. });
  4638. /* eslint-enable */
  4639. var setOptions$3 = function setOptions(options) {
  4640. return defaults$c(options);
  4641. };
  4642. /* eslint-enable */
  4643. var getSimilarity$1 = function getSimilarity(edge, attributes) {
  4644. var total = 0;
  4645. for (var i = 0; i < attributes.length; i++) {
  4646. total += attributes[i](edge);
  4647. }
  4648. return total;
  4649. };
  4650. var addLoops = function addLoops(M, n, val) {
  4651. for (var i = 0; i < n; i++) {
  4652. M[i * n + i] = val;
  4653. }
  4654. };
  4655. var normalize = function normalize(M, n) {
  4656. var sum;
  4657. for (var col = 0; col < n; col++) {
  4658. sum = 0;
  4659. for (var row = 0; row < n; row++) {
  4660. sum += M[row * n + col];
  4661. }
  4662. for (var _row = 0; _row < n; _row++) {
  4663. M[_row * n + col] = M[_row * n + col] / sum;
  4664. }
  4665. }
  4666. };
  4667. // TODO: blocked matrix multiplication?
  4668. var mmult = function mmult(A, B, n) {
  4669. var C = new Array(n * n);
  4670. for (var i = 0; i < n; i++) {
  4671. for (var j = 0; j < n; j++) {
  4672. C[i * n + j] = 0;
  4673. }
  4674. for (var k = 0; k < n; k++) {
  4675. for (var _j = 0; _j < n; _j++) {
  4676. C[i * n + _j] += A[i * n + k] * B[k * n + _j];
  4677. }
  4678. }
  4679. }
  4680. return C;
  4681. };
  4682. var expand = function expand(M, n, expandFactor /** power **/) {
  4683. var _M = M.slice(0);
  4684. for (var p = 1; p < expandFactor; p++) {
  4685. M = mmult(M, _M, n);
  4686. }
  4687. return M;
  4688. };
  4689. var inflate = function inflate(M, n, inflateFactor /** r **/) {
  4690. var _M = new Array(n * n);
  4691. // M(i,j) ^ inflatePower
  4692. for (var i = 0; i < n * n; i++) {
  4693. _M[i] = Math.pow(M[i], inflateFactor);
  4694. }
  4695. normalize(_M, n);
  4696. return _M;
  4697. };
  4698. var hasConverged = function hasConverged(M, _M, n2, roundFactor) {
  4699. // Check that both matrices have the same elements (i,j)
  4700. for (var i = 0; i < n2; i++) {
  4701. var v1 = Math.round(M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor); // truncate to 'roundFactor' decimal places
  4702. var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);
  4703. if (v1 !== v2) {
  4704. return false;
  4705. }
  4706. }
  4707. return true;
  4708. };
  4709. var assign$2 = function assign(M, n, nodes, cy) {
  4710. var clusters = [];
  4711. for (var i = 0; i < n; i++) {
  4712. var cluster = [];
  4713. for (var j = 0; j < n; j++) {
  4714. // Row-wise attractors and elements that they attract belong in same cluster
  4715. if (Math.round(M[i * n + j] * 1000) / 1000 > 0) {
  4716. cluster.push(nodes[j]);
  4717. }
  4718. }
  4719. if (cluster.length !== 0) {
  4720. clusters.push(cy.collection(cluster));
  4721. }
  4722. }
  4723. return clusters;
  4724. };
  4725. var isDuplicate = function isDuplicate(c1, c2) {
  4726. for (var i = 0; i < c1.length; i++) {
  4727. if (!c2[i] || c1[i].id() !== c2[i].id()) {
  4728. return false;
  4729. }
  4730. }
  4731. return true;
  4732. };
  4733. var removeDuplicates = function removeDuplicates(clusters) {
  4734. for (var i = 0; i < clusters.length; i++) {
  4735. for (var j = 0; j < clusters.length; j++) {
  4736. if (i != j && isDuplicate(clusters[i], clusters[j])) {
  4737. clusters.splice(j, 1);
  4738. }
  4739. }
  4740. }
  4741. return clusters;
  4742. };
  4743. var markovClustering = function markovClustering(options) {
  4744. var nodes = this.nodes();
  4745. var edges = this.edges();
  4746. var cy = this.cy();
  4747. // Set parameters of algorithm:
  4748. var opts = setOptions$3(options);
  4749. // Map each node to its position in node array
  4750. var id2position = {};
  4751. for (var i = 0; i < nodes.length; i++) {
  4752. id2position[nodes[i].id()] = i;
  4753. }
  4754. // Generate stochastic matrix M from input graph G (should be symmetric/undirected)
  4755. var n = nodes.length,
  4756. n2 = n * n;
  4757. var M = new Array(n2),
  4758. _M;
  4759. for (var _i = 0; _i < n2; _i++) {
  4760. M[_i] = 0;
  4761. }
  4762. for (var e = 0; e < edges.length; e++) {
  4763. var edge = edges[e];
  4764. var _i2 = id2position[edge.source().id()];
  4765. var j = id2position[edge.target().id()];
  4766. var sim = getSimilarity$1(edge, opts.attributes);
  4767. M[_i2 * n + j] += sim; // G should be symmetric and undirected
  4768. M[j * n + _i2] += sim;
  4769. }
  4770. // Begin Markov cluster algorithm
  4771. // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal
  4772. addLoops(M, n, opts.multFactor);
  4773. // Step 2: M = normalize( M );
  4774. normalize(M, n);
  4775. var isStillMoving = true;
  4776. var iterations = 0;
  4777. while (isStillMoving && iterations < opts.maxIterations) {
  4778. isStillMoving = false;
  4779. // Step 3:
  4780. _M = expand(M, n, opts.expandFactor);
  4781. // Step 4:
  4782. M = inflate(_M, n, opts.inflateFactor);
  4783. // Step 5: check to see if ~steady state has been reached
  4784. if (!hasConverged(M, _M, n2, 4)) {
  4785. isStillMoving = true;
  4786. }
  4787. iterations++;
  4788. }
  4789. // Build clusters from matrix
  4790. var clusters = assign$2(M, n, nodes, cy);
  4791. // Remove duplicate clusters due to symmetry of graph and M matrix
  4792. clusters = removeDuplicates(clusters);
  4793. return clusters;
  4794. };
  4795. var markovClustering$1 = {
  4796. markovClustering: markovClustering,
  4797. mcl: markovClustering
  4798. };
  4799. // Common distance metrics for clustering algorithms
  4800. // https://en.wikipedia.org/wiki/Hierarchical_clustering#Metric
  4801. var identity$1 = function identity(x) {
  4802. return x;
  4803. };
  4804. var absDiff = function absDiff(p, q) {
  4805. return Math.abs(q - p);
  4806. };
  4807. var addAbsDiff = function addAbsDiff(total, p, q) {
  4808. return total + absDiff(p, q);
  4809. };
  4810. var addSquaredDiff = function addSquaredDiff(total, p, q) {
  4811. return total + Math.pow(q - p, 2);
  4812. };
  4813. var sqrt = function sqrt(x) {
  4814. return Math.sqrt(x);
  4815. };
  4816. var maxAbsDiff = function maxAbsDiff(currentMax, p, q) {
  4817. return Math.max(currentMax, absDiff(p, q));
  4818. };
  4819. var getDistance = function getDistance(length, getP, getQ, init, visit) {
  4820. var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity$1;
  4821. var ret = init;
  4822. var p, q;
  4823. for (var dim = 0; dim < length; dim++) {
  4824. p = getP(dim);
  4825. q = getQ(dim);
  4826. ret = visit(ret, p, q);
  4827. }
  4828. return post(ret);
  4829. };
  4830. var distances = {
  4831. euclidean: function euclidean(length, getP, getQ) {
  4832. if (length >= 2) {
  4833. return getDistance(length, getP, getQ, 0, addSquaredDiff, sqrt);
  4834. } else {
  4835. // for single attr case, more efficient to avoid sqrt
  4836. return getDistance(length, getP, getQ, 0, addAbsDiff);
  4837. }
  4838. },
  4839. squaredEuclidean: function squaredEuclidean(length, getP, getQ) {
  4840. return getDistance(length, getP, getQ, 0, addSquaredDiff);
  4841. },
  4842. manhattan: function manhattan(length, getP, getQ) {
  4843. return getDistance(length, getP, getQ, 0, addAbsDiff);
  4844. },
  4845. max: function max(length, getP, getQ) {
  4846. return getDistance(length, getP, getQ, -Infinity, maxAbsDiff);
  4847. }
  4848. };
  4849. // in case the user accidentally doesn't use camel case
  4850. distances['squared-euclidean'] = distances['squaredEuclidean'];
  4851. distances['squaredeuclidean'] = distances['squaredEuclidean'];
  4852. function clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {
  4853. var impl;
  4854. if (fn$6(method)) {
  4855. impl = method;
  4856. } else {
  4857. impl = distances[method] || distances.euclidean;
  4858. }
  4859. if (length === 0 && fn$6(method)) {
  4860. return impl(nodeP, nodeQ);
  4861. } else {
  4862. return impl(length, getP, getQ, nodeP, nodeQ);
  4863. }
  4864. }
  4865. var defaults$b = defaults$g({
  4866. k: 2,
  4867. m: 2,
  4868. sensitivityThreshold: 0.0001,
  4869. distance: 'euclidean',
  4870. maxIterations: 10,
  4871. attributes: [],
  4872. testMode: false,
  4873. testCentroids: null
  4874. });
  4875. var setOptions$2 = function setOptions(options) {
  4876. return defaults$b(options);
  4877. };
  4878. var getDist = function getDist(type, node, centroid, attributes, mode) {
  4879. var noNodeP = mode !== 'kMedoids';
  4880. var getP = noNodeP ? function (i) {
  4881. return centroid[i];
  4882. } : function (i) {
  4883. return attributes[i](centroid);
  4884. };
  4885. var getQ = function getQ(i) {
  4886. return attributes[i](node);
  4887. };
  4888. var nodeP = centroid;
  4889. var nodeQ = node;
  4890. return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);
  4891. };
  4892. var randomCentroids = function randomCentroids(nodes, k, attributes) {
  4893. var ndim = attributes.length;
  4894. var min = new Array(ndim);
  4895. var max = new Array(ndim);
  4896. var centroids = new Array(k);
  4897. var centroid = null;
  4898. // Find min, max values for each attribute dimension
  4899. for (var i = 0; i < ndim; i++) {
  4900. min[i] = nodes.min(attributes[i]).value;
  4901. max[i] = nodes.max(attributes[i]).value;
  4902. }
  4903. // Build k centroids, each represented as an n-dim feature vector
  4904. for (var c = 0; c < k; c++) {
  4905. centroid = [];
  4906. for (var _i = 0; _i < ndim; _i++) {
  4907. centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value
  4908. }
  4909. centroids[c] = centroid;
  4910. }
  4911. return centroids;
  4912. };
  4913. var classify = function classify(node, centroids, distance, attributes, type) {
  4914. var min = Infinity;
  4915. var index = 0;
  4916. for (var i = 0; i < centroids.length; i++) {
  4917. var dist = getDist(distance, node, centroids[i], attributes, type);
  4918. if (dist < min) {
  4919. min = dist;
  4920. index = i;
  4921. }
  4922. }
  4923. return index;
  4924. };
  4925. var buildCluster = function buildCluster(centroid, nodes, assignment) {
  4926. var cluster = [];
  4927. var node = null;
  4928. for (var n = 0; n < nodes.length; n++) {
  4929. node = nodes[n];
  4930. if (assignment[node.id()] === centroid) {
  4931. //console.log("Node " + node.id() + " is associated with medoid #: " + m);
  4932. cluster.push(node);
  4933. }
  4934. }
  4935. return cluster;
  4936. };
  4937. var haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {
  4938. return Math.abs(v2 - v1) <= sensitivityThreshold;
  4939. };
  4940. var haveMatricesConverged = function haveMatricesConverged(v1, v2, sensitivityThreshold) {
  4941. for (var i = 0; i < v1.length; i++) {
  4942. for (var j = 0; j < v1[i].length; j++) {
  4943. var diff = Math.abs(v1[i][j] - v2[i][j]);
  4944. if (diff > sensitivityThreshold) {
  4945. return false;
  4946. }
  4947. }
  4948. }
  4949. return true;
  4950. };
  4951. var seenBefore = function seenBefore(node, medoids, n) {
  4952. for (var i = 0; i < n; i++) {
  4953. if (node === medoids[i]) return true;
  4954. }
  4955. return false;
  4956. };
  4957. var randomMedoids = function randomMedoids(nodes, k) {
  4958. var medoids = new Array(k);
  4959. // For small data sets, the probability of medoid conflict is greater,
  4960. // so we need to check to see if we've already seen or chose this node before.
  4961. if (nodes.length < 50) {
  4962. // Randomly select k medoids from the n nodes
  4963. for (var i = 0; i < k; i++) {
  4964. var node = nodes[Math.floor(Math.random() * nodes.length)];
  4965. // If we've already chosen this node to be a medoid, don't choose it again (for small data sets).
  4966. // Instead choose a different random node.
  4967. while (seenBefore(node, medoids, i)) {
  4968. node = nodes[Math.floor(Math.random() * nodes.length)];
  4969. }
  4970. medoids[i] = node;
  4971. }
  4972. } else {
  4973. // Relatively large data set, so pretty safe to not check and just select random nodes
  4974. for (var _i2 = 0; _i2 < k; _i2++) {
  4975. medoids[_i2] = nodes[Math.floor(Math.random() * nodes.length)];
  4976. }
  4977. }
  4978. return medoids;
  4979. };
  4980. var findCost = function findCost(potentialNewMedoid, cluster, attributes) {
  4981. var cost = 0;
  4982. for (var n = 0; n < cluster.length; n++) {
  4983. cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');
  4984. }
  4985. return cost;
  4986. };
  4987. var kMeans = function kMeans(options) {
  4988. var cy = this.cy();
  4989. var nodes = this.nodes();
  4990. var node = null;
  4991. // Set parameters of algorithm: # of clusters, distance metric, etc.
  4992. var opts = setOptions$2(options);
  4993. // Begin k-means algorithm
  4994. var clusters = new Array(opts.k);
  4995. var assignment = {};
  4996. var centroids;
  4997. // Step 1: Initialize centroid positions
  4998. if (opts.testMode) {
  4999. if (typeof opts.testCentroids === 'number') {
  5000. // TODO: implement a seeded random number generator.
  5001. opts.testCentroids;
  5002. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5003. } else if (_typeof(opts.testCentroids) === 'object') {
  5004. centroids = opts.testCentroids;
  5005. } else {
  5006. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5007. }
  5008. } else {
  5009. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5010. }
  5011. var isStillMoving = true;
  5012. var iterations = 0;
  5013. while (isStillMoving && iterations < opts.maxIterations) {
  5014. // Step 2: Assign nodes to the nearest centroid
  5015. for (var n = 0; n < nodes.length; n++) {
  5016. node = nodes[n];
  5017. // Determine which cluster this node belongs to: node id => cluster #
  5018. assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');
  5019. }
  5020. // Step 3: For each of the k clusters, update its centroid
  5021. isStillMoving = false;
  5022. for (var c = 0; c < opts.k; c++) {
  5023. // Get all nodes that belong to this cluster
  5024. var cluster = buildCluster(c, nodes, assignment);
  5025. if (cluster.length === 0) {
  5026. // If cluster is empty, break out early & move to next cluster
  5027. continue;
  5028. }
  5029. // Update centroids by calculating avg of all nodes within the cluster.
  5030. var ndim = opts.attributes.length;
  5031. var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]
  5032. var newCentroid = new Array(ndim);
  5033. var sum = new Array(ndim);
  5034. for (var d = 0; d < ndim; d++) {
  5035. sum[d] = 0.0;
  5036. for (var i = 0; i < cluster.length; i++) {
  5037. node = cluster[i];
  5038. sum[d] += opts.attributes[d](node);
  5039. }
  5040. newCentroid[d] = sum[d] / cluster.length;
  5041. // Check to see if algorithm has converged, i.e. when centroids no longer change
  5042. if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {
  5043. isStillMoving = true;
  5044. }
  5045. }
  5046. centroids[c] = newCentroid;
  5047. clusters[c] = cy.collection(cluster);
  5048. }
  5049. iterations++;
  5050. }
  5051. return clusters;
  5052. };
  5053. var kMedoids = function kMedoids(options) {
  5054. var cy = this.cy();
  5055. var nodes = this.nodes();
  5056. var node = null;
  5057. var opts = setOptions$2(options);
  5058. // Begin k-medoids algorithm
  5059. var clusters = new Array(opts.k);
  5060. var medoids;
  5061. var assignment = {};
  5062. var curCost;
  5063. var minCosts = new Array(opts.k); // minimum cost configuration for each cluster
  5064. // Step 1: Initialize k medoids
  5065. if (opts.testMode) {
  5066. if (typeof opts.testCentroids === 'number') ; else if (_typeof(opts.testCentroids) === 'object') {
  5067. medoids = opts.testCentroids;
  5068. } else {
  5069. medoids = randomMedoids(nodes, opts.k);
  5070. }
  5071. } else {
  5072. medoids = randomMedoids(nodes, opts.k);
  5073. }
  5074. var isStillMoving = true;
  5075. var iterations = 0;
  5076. while (isStillMoving && iterations < opts.maxIterations) {
  5077. // Step 2: Assign nodes to the nearest medoid
  5078. for (var n = 0; n < nodes.length; n++) {
  5079. node = nodes[n];
  5080. // Determine which cluster this node belongs to: node id => cluster #
  5081. assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');
  5082. }
  5083. isStillMoving = false;
  5084. // Step 3: For each medoid m, and for each node associated with mediod m,
  5085. // select the node with the lowest configuration cost as new medoid.
  5086. for (var m = 0; m < medoids.length; m++) {
  5087. // Get all nodes that belong to this medoid
  5088. var cluster = buildCluster(m, nodes, assignment);
  5089. if (cluster.length === 0) {
  5090. // If cluster is empty, break out early & move to next cluster
  5091. continue;
  5092. }
  5093. minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost
  5094. // Select different medoid if its configuration has the lowest cost
  5095. for (var _n = 0; _n < cluster.length; _n++) {
  5096. curCost = findCost(cluster[_n], cluster, opts.attributes);
  5097. if (curCost < minCosts[m]) {
  5098. minCosts[m] = curCost;
  5099. medoids[m] = cluster[_n];
  5100. isStillMoving = true;
  5101. }
  5102. }
  5103. clusters[m] = cy.collection(cluster);
  5104. }
  5105. iterations++;
  5106. }
  5107. return clusters;
  5108. };
  5109. var updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {
  5110. var numerator, denominator;
  5111. for (var n = 0; n < nodes.length; n++) {
  5112. for (var c = 0; c < centroids.length; c++) {
  5113. weight[n][c] = Math.pow(U[n][c], opts.m);
  5114. }
  5115. }
  5116. for (var _c = 0; _c < centroids.length; _c++) {
  5117. for (var dim = 0; dim < opts.attributes.length; dim++) {
  5118. numerator = 0;
  5119. denominator = 0;
  5120. for (var _n2 = 0; _n2 < nodes.length; _n2++) {
  5121. numerator += weight[_n2][_c] * opts.attributes[dim](nodes[_n2]);
  5122. denominator += weight[_n2][_c];
  5123. }
  5124. centroids[_c][dim] = numerator / denominator;
  5125. }
  5126. }
  5127. };
  5128. var updateMembership = function updateMembership(U, _U, centroids, nodes, opts) {
  5129. // Save previous step
  5130. for (var i = 0; i < U.length; i++) {
  5131. _U[i] = U[i].slice();
  5132. }
  5133. var sum, numerator, denominator;
  5134. var pow = 2 / (opts.m - 1);
  5135. for (var c = 0; c < centroids.length; c++) {
  5136. for (var n = 0; n < nodes.length; n++) {
  5137. sum = 0;
  5138. for (var k = 0; k < centroids.length; k++) {
  5139. // against all other centroids
  5140. numerator = getDist(opts.distance, nodes[n], centroids[c], opts.attributes, 'cmeans');
  5141. denominator = getDist(opts.distance, nodes[n], centroids[k], opts.attributes, 'cmeans');
  5142. sum += Math.pow(numerator / denominator, pow);
  5143. }
  5144. U[n][c] = 1 / sum;
  5145. }
  5146. }
  5147. };
  5148. var assign$1 = function assign(nodes, U, opts, cy) {
  5149. var clusters = new Array(opts.k);
  5150. for (var c = 0; c < clusters.length; c++) {
  5151. clusters[c] = [];
  5152. }
  5153. var max;
  5154. var index;
  5155. for (var n = 0; n < U.length; n++) {
  5156. // for each node (U is N x C matrix)
  5157. max = -Infinity;
  5158. index = -1;
  5159. // Determine which cluster the node is most likely to belong in
  5160. for (var _c2 = 0; _c2 < U[0].length; _c2++) {
  5161. if (U[n][_c2] > max) {
  5162. max = U[n][_c2];
  5163. index = _c2;
  5164. }
  5165. }
  5166. clusters[index].push(nodes[n]);
  5167. }
  5168. // Turn every array into a collection of nodes
  5169. for (var _c3 = 0; _c3 < clusters.length; _c3++) {
  5170. clusters[_c3] = cy.collection(clusters[_c3]);
  5171. }
  5172. return clusters;
  5173. };
  5174. var fuzzyCMeans = function fuzzyCMeans(options) {
  5175. var cy = this.cy();
  5176. var nodes = this.nodes();
  5177. var opts = setOptions$2(options);
  5178. // Begin fuzzy c-means algorithm
  5179. var clusters;
  5180. var centroids;
  5181. var U;
  5182. var _U;
  5183. var weight;
  5184. // Step 1: Initialize letiables.
  5185. _U = new Array(nodes.length);
  5186. for (var i = 0; i < nodes.length; i++) {
  5187. // N x C matrix
  5188. _U[i] = new Array(opts.k);
  5189. }
  5190. U = new Array(nodes.length);
  5191. for (var _i3 = 0; _i3 < nodes.length; _i3++) {
  5192. // N x C matrix
  5193. U[_i3] = new Array(opts.k);
  5194. }
  5195. for (var _i4 = 0; _i4 < nodes.length; _i4++) {
  5196. var total = 0;
  5197. for (var j = 0; j < opts.k; j++) {
  5198. U[_i4][j] = Math.random();
  5199. total += U[_i4][j];
  5200. }
  5201. for (var _j = 0; _j < opts.k; _j++) {
  5202. U[_i4][_j] = U[_i4][_j] / total;
  5203. }
  5204. }
  5205. centroids = new Array(opts.k);
  5206. for (var _i5 = 0; _i5 < opts.k; _i5++) {
  5207. centroids[_i5] = new Array(opts.attributes.length);
  5208. }
  5209. weight = new Array(nodes.length);
  5210. for (var _i6 = 0; _i6 < nodes.length; _i6++) {
  5211. // N x C matrix
  5212. weight[_i6] = new Array(opts.k);
  5213. }
  5214. // end init FCM
  5215. var isStillMoving = true;
  5216. var iterations = 0;
  5217. while (isStillMoving && iterations < opts.maxIterations) {
  5218. isStillMoving = false;
  5219. // Step 2: Calculate the centroids for each step.
  5220. updateCentroids(centroids, nodes, U, weight, opts);
  5221. // Step 3: Update the partition matrix U.
  5222. updateMembership(U, _U, centroids, nodes, opts);
  5223. // Step 4: Check for convergence.
  5224. if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {
  5225. isStillMoving = true;
  5226. }
  5227. iterations++;
  5228. }
  5229. // Assign nodes to clusters with highest probability.
  5230. clusters = assign$1(nodes, U, opts, cy);
  5231. return {
  5232. clusters: clusters,
  5233. degreeOfMembership: U
  5234. };
  5235. };
  5236. var kClustering = {
  5237. kMeans: kMeans,
  5238. kMedoids: kMedoids,
  5239. fuzzyCMeans: fuzzyCMeans,
  5240. fcm: fuzzyCMeans
  5241. };
  5242. // Implemented by Zoe Xi @zoexi for GSOC 2016
  5243. // https://github.com/cytoscape/cytoscape.js-hierarchical
  5244. var defaults$a = defaults$g({
  5245. distance: 'euclidean',
  5246. // distance metric to compare nodes
  5247. linkage: 'min',
  5248. // linkage criterion : how to determine the distance between clusters of nodes
  5249. mode: 'threshold',
  5250. // mode:'threshold' => clusters must be threshold distance apart
  5251. threshold: Infinity,
  5252. // the distance threshold
  5253. // mode:'dendrogram' => the nodes are organised as leaves in a tree (siblings are close), merging makes clusters
  5254. addDendrogram: false,
  5255. // whether to add the dendrogram to the graph for viz
  5256. dendrogramDepth: 0,
  5257. // depth at which dendrogram branches are merged into the returned clusters
  5258. attributes: [] // array of attr functions
  5259. });
  5260. var linkageAliases = {
  5261. 'single': 'min',
  5262. 'complete': 'max'
  5263. };
  5264. var setOptions$1 = function setOptions(options) {
  5265. var opts = defaults$a(options);
  5266. var preferredAlias = linkageAliases[opts.linkage];
  5267. if (preferredAlias != null) {
  5268. opts.linkage = preferredAlias;
  5269. }
  5270. return opts;
  5271. };
  5272. var mergeClosest = function mergeClosest(clusters, index, dists, mins, opts) {
  5273. // Find two closest clusters from cached mins
  5274. var minKey = 0;
  5275. var min = Infinity;
  5276. var dist;
  5277. var attrs = opts.attributes;
  5278. var getDist = function getDist(n1, n2) {
  5279. return clusteringDistance(opts.distance, attrs.length, function (i) {
  5280. return attrs[i](n1);
  5281. }, function (i) {
  5282. return attrs[i](n2);
  5283. }, n1, n2);
  5284. };
  5285. for (var i = 0; i < clusters.length; i++) {
  5286. var key = clusters[i].key;
  5287. var _dist = dists[key][mins[key]];
  5288. if (_dist < min) {
  5289. minKey = key;
  5290. min = _dist;
  5291. }
  5292. }
  5293. if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {
  5294. return false;
  5295. }
  5296. var c1 = index[minKey];
  5297. var c2 = index[mins[minKey]];
  5298. var merged;
  5299. // Merge two closest clusters
  5300. if (opts.mode === 'dendrogram') {
  5301. merged = {
  5302. left: c1,
  5303. right: c2,
  5304. key: c1.key
  5305. };
  5306. } else {
  5307. merged = {
  5308. value: c1.value.concat(c2.value),
  5309. key: c1.key
  5310. };
  5311. }
  5312. clusters[c1.index] = merged;
  5313. clusters.splice(c2.index, 1);
  5314. index[c1.key] = merged;
  5315. // Update distances with new merged cluster
  5316. for (var _i = 0; _i < clusters.length; _i++) {
  5317. var cur = clusters[_i];
  5318. if (c1.key === cur.key) {
  5319. dist = Infinity;
  5320. } else if (opts.linkage === 'min') {
  5321. dist = dists[c1.key][cur.key];
  5322. if (dists[c1.key][cur.key] > dists[c2.key][cur.key]) {
  5323. dist = dists[c2.key][cur.key];
  5324. }
  5325. } else if (opts.linkage === 'max') {
  5326. dist = dists[c1.key][cur.key];
  5327. if (dists[c1.key][cur.key] < dists[c2.key][cur.key]) {
  5328. dist = dists[c2.key][cur.key];
  5329. }
  5330. } else if (opts.linkage === 'mean') {
  5331. dist = (dists[c1.key][cur.key] * c1.size + dists[c2.key][cur.key] * c2.size) / (c1.size + c2.size);
  5332. } else {
  5333. if (opts.mode === 'dendrogram') dist = getDist(cur.value, c1.value);else dist = getDist(cur.value[0], c1.value[0]);
  5334. }
  5335. dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric
  5336. }
  5337. // Update cached mins
  5338. for (var _i2 = 0; _i2 < clusters.length; _i2++) {
  5339. var key1 = clusters[_i2].key;
  5340. if (mins[key1] === c1.key || mins[key1] === c2.key) {
  5341. var _min = key1;
  5342. for (var j = 0; j < clusters.length; j++) {
  5343. var key2 = clusters[j].key;
  5344. if (dists[key1][key2] < dists[key1][_min]) {
  5345. _min = key2;
  5346. }
  5347. }
  5348. mins[key1] = _min;
  5349. }
  5350. clusters[_i2].index = _i2;
  5351. }
  5352. // Clean up meta data used for clustering
  5353. c1.key = c2.key = c1.index = c2.index = null;
  5354. return true;
  5355. };
  5356. var _getAllChildren = function getAllChildren(root, arr, cy) {
  5357. if (!root) return;
  5358. if (root.value) {
  5359. arr.push(root.value);
  5360. } else {
  5361. if (root.left) _getAllChildren(root.left, arr);
  5362. if (root.right) _getAllChildren(root.right, arr);
  5363. }
  5364. };
  5365. var _buildDendrogram = function buildDendrogram(root, cy) {
  5366. if (!root) return '';
  5367. if (root.left && root.right) {
  5368. var leftStr = _buildDendrogram(root.left, cy);
  5369. var rightStr = _buildDendrogram(root.right, cy);
  5370. var node = cy.add({
  5371. group: 'nodes',
  5372. data: {
  5373. id: leftStr + ',' + rightStr
  5374. }
  5375. });
  5376. cy.add({
  5377. group: 'edges',
  5378. data: {
  5379. source: leftStr,
  5380. target: node.id()
  5381. }
  5382. });
  5383. cy.add({
  5384. group: 'edges',
  5385. data: {
  5386. source: rightStr,
  5387. target: node.id()
  5388. }
  5389. });
  5390. return node.id();
  5391. } else if (root.value) {
  5392. return root.value.id();
  5393. }
  5394. };
  5395. var _buildClustersFromTree = function buildClustersFromTree(root, k, cy) {
  5396. if (!root) return [];
  5397. var left = [],
  5398. right = [],
  5399. leaves = [];
  5400. if (k === 0) {
  5401. // don't cut tree, simply return all nodes as 1 single cluster
  5402. if (root.left) _getAllChildren(root.left, left);
  5403. if (root.right) _getAllChildren(root.right, right);
  5404. leaves = left.concat(right);
  5405. return [cy.collection(leaves)];
  5406. } else if (k === 1) {
  5407. // cut at root
  5408. if (root.value) {
  5409. // leaf node
  5410. return [cy.collection(root.value)];
  5411. } else {
  5412. if (root.left) _getAllChildren(root.left, left);
  5413. if (root.right) _getAllChildren(root.right, right);
  5414. return [cy.collection(left), cy.collection(right)];
  5415. }
  5416. } else {
  5417. if (root.value) {
  5418. return [cy.collection(root.value)];
  5419. } else {
  5420. if (root.left) left = _buildClustersFromTree(root.left, k - 1, cy);
  5421. if (root.right) right = _buildClustersFromTree(root.right, k - 1, cy);
  5422. return left.concat(right);
  5423. }
  5424. }
  5425. };
  5426. var hierarchicalClustering = function hierarchicalClustering(options) {
  5427. var cy = this.cy();
  5428. var nodes = this.nodes();
  5429. // Set parameters of algorithm: linkage type, distance metric, etc.
  5430. var opts = setOptions$1(options);
  5431. var attrs = opts.attributes;
  5432. var getDist = function getDist(n1, n2) {
  5433. return clusteringDistance(opts.distance, attrs.length, function (i) {
  5434. return attrs[i](n1);
  5435. }, function (i) {
  5436. return attrs[i](n2);
  5437. }, n1, n2);
  5438. };
  5439. // Begin hierarchical algorithm
  5440. var clusters = [];
  5441. var dists = []; // distances between each pair of clusters
  5442. var mins = []; // closest cluster for each cluster
  5443. var index = []; // hash of all clusters by key
  5444. // In agglomerative (bottom-up) clustering, each node starts as its own cluster
  5445. for (var n = 0; n < nodes.length; n++) {
  5446. var cluster = {
  5447. value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],
  5448. key: n,
  5449. index: n
  5450. };
  5451. clusters[n] = cluster;
  5452. index[n] = cluster;
  5453. dists[n] = [];
  5454. mins[n] = 0;
  5455. }
  5456. // Calculate the distance between each pair of clusters
  5457. for (var i = 0; i < clusters.length; i++) {
  5458. for (var j = 0; j <= i; j++) {
  5459. var dist = undefined;
  5460. if (opts.mode === 'dendrogram') {
  5461. // modes store cluster values differently
  5462. dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);
  5463. } else {
  5464. dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);
  5465. }
  5466. dists[i][j] = dist;
  5467. dists[j][i] = dist;
  5468. if (dist < dists[i][mins[i]]) {
  5469. mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j
  5470. }
  5471. }
  5472. }
  5473. // Find the closest pair of clusters and merge them into a single cluster.
  5474. // Update distances between new cluster and each of the old clusters, and loop until threshold reached.
  5475. var merged = mergeClosest(clusters, index, dists, mins, opts);
  5476. while (merged) {
  5477. merged = mergeClosest(clusters, index, dists, mins, opts);
  5478. }
  5479. var retClusters;
  5480. // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges
  5481. // in addition to returning the clusters.
  5482. if (opts.mode === 'dendrogram') {
  5483. retClusters = _buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);
  5484. if (opts.addDendrogram) _buildDendrogram(clusters[0], cy);
  5485. } else {
  5486. // Regular mode simply returns the clusters
  5487. retClusters = new Array(clusters.length);
  5488. clusters.forEach(function (cluster, i) {
  5489. // Clean up meta data used for clustering
  5490. cluster.key = cluster.index = null;
  5491. retClusters[i] = cy.collection(cluster.value);
  5492. });
  5493. }
  5494. return retClusters;
  5495. };
  5496. var hierarchicalClustering$1 = {
  5497. hierarchicalClustering: hierarchicalClustering,
  5498. hca: hierarchicalClustering
  5499. };
  5500. // Implemented by Zoe Xi @zoexi for GSOC 2016
  5501. // https://github.com/cytoscape/cytoscape.js-affinity-propagation
  5502. var defaults$9 = defaults$g({
  5503. distance: 'euclidean',
  5504. // distance metric to compare attributes between two nodes
  5505. preference: 'median',
  5506. // suitability of a data point to serve as an exemplar
  5507. damping: 0.8,
  5508. // damping factor between [0.5, 1)
  5509. maxIterations: 1000,
  5510. // max number of iterations to run
  5511. minIterations: 100,
  5512. // min number of iterations to run in order for clustering to stop
  5513. attributes: [// functions to quantify the similarity between any two points
  5514. // e.g. node => node.data('weight')
  5515. ]
  5516. });
  5517. var setOptions = function setOptions(options) {
  5518. var dmp = options.damping;
  5519. var pref = options.preference;
  5520. if (!(0.5 <= dmp && dmp < 1)) {
  5521. error("Damping must range on [0.5, 1). Got: ".concat(dmp));
  5522. }
  5523. var validPrefs = ['median', 'mean', 'min', 'max'];
  5524. if (!(validPrefs.some(function (v) {
  5525. return v === pref;
  5526. }) || number$1(pref))) {
  5527. error("Preference must be one of [".concat(validPrefs.map(function (p) {
  5528. return "'".concat(p, "'");
  5529. }).join(', '), "] or a number. Got: ").concat(pref));
  5530. }
  5531. return defaults$9(options);
  5532. };
  5533. var getSimilarity = function getSimilarity(type, n1, n2, attributes) {
  5534. var attr = function attr(n, i) {
  5535. return attributes[i](n);
  5536. };
  5537. // nb negative because similarity should have an inverse relationship to distance
  5538. return -clusteringDistance(type, attributes.length, function (i) {
  5539. return attr(n1, i);
  5540. }, function (i) {
  5541. return attr(n2, i);
  5542. }, n1, n2);
  5543. };
  5544. var getPreference = function getPreference(S, preference) {
  5545. // larger preference = greater # of clusters
  5546. var p = null;
  5547. if (preference === 'median') {
  5548. p = median(S);
  5549. } else if (preference === 'mean') {
  5550. p = mean(S);
  5551. } else if (preference === 'min') {
  5552. p = min(S);
  5553. } else if (preference === 'max') {
  5554. p = max(S);
  5555. } else {
  5556. // Custom preference number, as set by user
  5557. p = preference;
  5558. }
  5559. return p;
  5560. };
  5561. var findExemplars = function findExemplars(n, R, A) {
  5562. var indices = [];
  5563. for (var i = 0; i < n; i++) {
  5564. if (R[i * n + i] + A[i * n + i] > 0) {
  5565. indices.push(i);
  5566. }
  5567. }
  5568. return indices;
  5569. };
  5570. var assignClusters = function assignClusters(n, S, exemplars) {
  5571. var clusters = [];
  5572. for (var i = 0; i < n; i++) {
  5573. var index = -1;
  5574. var max = -Infinity;
  5575. for (var ei = 0; ei < exemplars.length; ei++) {
  5576. var e = exemplars[ei];
  5577. if (S[i * n + e] > max) {
  5578. index = e;
  5579. max = S[i * n + e];
  5580. }
  5581. }
  5582. if (index > 0) {
  5583. clusters.push(index);
  5584. }
  5585. }
  5586. for (var _ei = 0; _ei < exemplars.length; _ei++) {
  5587. clusters[exemplars[_ei]] = exemplars[_ei];
  5588. }
  5589. return clusters;
  5590. };
  5591. var assign = function assign(n, S, exemplars) {
  5592. var clusters = assignClusters(n, S, exemplars);
  5593. for (var ei = 0; ei < exemplars.length; ei++) {
  5594. var ii = [];
  5595. for (var c = 0; c < clusters.length; c++) {
  5596. if (clusters[c] === exemplars[ei]) {
  5597. ii.push(c);
  5598. }
  5599. }
  5600. var maxI = -1;
  5601. var maxSum = -Infinity;
  5602. for (var i = 0; i < ii.length; i++) {
  5603. var sum = 0;
  5604. for (var j = 0; j < ii.length; j++) {
  5605. sum += S[ii[j] * n + ii[i]];
  5606. }
  5607. if (sum > maxSum) {
  5608. maxI = i;
  5609. maxSum = sum;
  5610. }
  5611. }
  5612. exemplars[ei] = ii[maxI];
  5613. }
  5614. clusters = assignClusters(n, S, exemplars);
  5615. return clusters;
  5616. };
  5617. var affinityPropagation = function affinityPropagation(options) {
  5618. var cy = this.cy();
  5619. var nodes = this.nodes();
  5620. var opts = setOptions(options);
  5621. // Map each node to its position in node array
  5622. var id2position = {};
  5623. for (var i = 0; i < nodes.length; i++) {
  5624. id2position[nodes[i].id()] = i;
  5625. }
  5626. // Begin affinity propagation algorithm
  5627. var n; // number of data points
  5628. var n2; // size of matrices
  5629. var S; // similarity matrix (1D array)
  5630. var p; // preference/suitability of a data point to serve as an exemplar
  5631. var R; // responsibility matrix (1D array)
  5632. var A; // availability matrix (1D array)
  5633. n = nodes.length;
  5634. n2 = n * n;
  5635. // Initialize and build S similarity matrix
  5636. S = new Array(n2);
  5637. for (var _i = 0; _i < n2; _i++) {
  5638. S[_i] = -Infinity; // for cases where two data points shouldn't be linked together
  5639. }
  5640. for (var _i2 = 0; _i2 < n; _i2++) {
  5641. for (var j = 0; j < n; j++) {
  5642. if (_i2 !== j) {
  5643. S[_i2 * n + j] = getSimilarity(opts.distance, nodes[_i2], nodes[j], opts.attributes);
  5644. }
  5645. }
  5646. }
  5647. // Place preferences on the diagonal of S
  5648. p = getPreference(S, opts.preference);
  5649. for (var _i3 = 0; _i3 < n; _i3++) {
  5650. S[_i3 * n + _i3] = p;
  5651. }
  5652. // Initialize R responsibility matrix
  5653. R = new Array(n2);
  5654. for (var _i4 = 0; _i4 < n2; _i4++) {
  5655. R[_i4] = 0.0;
  5656. }
  5657. // Initialize A availability matrix
  5658. A = new Array(n2);
  5659. for (var _i5 = 0; _i5 < n2; _i5++) {
  5660. A[_i5] = 0.0;
  5661. }
  5662. var old = new Array(n);
  5663. var Rp = new Array(n);
  5664. var se = new Array(n);
  5665. for (var _i6 = 0; _i6 < n; _i6++) {
  5666. old[_i6] = 0.0;
  5667. Rp[_i6] = 0.0;
  5668. se[_i6] = 0;
  5669. }
  5670. var e = new Array(n * opts.minIterations);
  5671. for (var _i7 = 0; _i7 < e.length; _i7++) {
  5672. e[_i7] = 0;
  5673. }
  5674. var iter;
  5675. for (iter = 0; iter < opts.maxIterations; iter++) {
  5676. // main algorithmic loop
  5677. // Update R responsibility matrix
  5678. for (var _i8 = 0; _i8 < n; _i8++) {
  5679. var max = -Infinity,
  5680. max2 = -Infinity,
  5681. maxI = -1,
  5682. AS = 0.0;
  5683. for (var _j = 0; _j < n; _j++) {
  5684. old[_j] = R[_i8 * n + _j];
  5685. AS = A[_i8 * n + _j] + S[_i8 * n + _j];
  5686. if (AS >= max) {
  5687. max2 = max;
  5688. max = AS;
  5689. maxI = _j;
  5690. } else if (AS > max2) {
  5691. max2 = AS;
  5692. }
  5693. }
  5694. for (var _j2 = 0; _j2 < n; _j2++) {
  5695. R[_i8 * n + _j2] = (1 - opts.damping) * (S[_i8 * n + _j2] - max) + opts.damping * old[_j2];
  5696. }
  5697. R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];
  5698. }
  5699. // Update A availability matrix
  5700. for (var _i9 = 0; _i9 < n; _i9++) {
  5701. var sum = 0;
  5702. for (var _j3 = 0; _j3 < n; _j3++) {
  5703. old[_j3] = A[_j3 * n + _i9];
  5704. Rp[_j3] = Math.max(0, R[_j3 * n + _i9]);
  5705. sum += Rp[_j3];
  5706. }
  5707. sum -= Rp[_i9];
  5708. Rp[_i9] = R[_i9 * n + _i9];
  5709. sum += Rp[_i9];
  5710. for (var _j4 = 0; _j4 < n; _j4++) {
  5711. A[_j4 * n + _i9] = (1 - opts.damping) * Math.min(0, sum - Rp[_j4]) + opts.damping * old[_j4];
  5712. }
  5713. A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];
  5714. }
  5715. // Check for convergence
  5716. var K = 0;
  5717. for (var _i10 = 0; _i10 < n; _i10++) {
  5718. var E = A[_i10 * n + _i10] + R[_i10 * n + _i10] > 0 ? 1 : 0;
  5719. e[iter % opts.minIterations * n + _i10] = E;
  5720. K += E;
  5721. }
  5722. if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {
  5723. var _sum = 0;
  5724. for (var _i11 = 0; _i11 < n; _i11++) {
  5725. se[_i11] = 0;
  5726. for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {
  5727. se[_i11] += e[_j5 * n + _i11];
  5728. }
  5729. if (se[_i11] === 0 || se[_i11] === opts.minIterations) {
  5730. _sum++;
  5731. }
  5732. }
  5733. if (_sum === n) {
  5734. // then we have convergence
  5735. break;
  5736. }
  5737. }
  5738. }
  5739. // Identify exemplars (cluster centers)
  5740. var exemplarsIndices = findExemplars(n, R, A);
  5741. // Assign nodes to clusters
  5742. var clusterIndices = assign(n, S, exemplarsIndices);
  5743. var clusters = {};
  5744. for (var c = 0; c < exemplarsIndices.length; c++) {
  5745. clusters[exemplarsIndices[c]] = [];
  5746. }
  5747. for (var _i12 = 0; _i12 < nodes.length; _i12++) {
  5748. var pos = id2position[nodes[_i12].id()];
  5749. var clusterIndex = clusterIndices[pos];
  5750. if (clusterIndex != null) {
  5751. // the node may have not been assigned a cluster if no valid attributes were specified
  5752. clusters[clusterIndex].push(nodes[_i12]);
  5753. }
  5754. }
  5755. var retClusters = new Array(exemplarsIndices.length);
  5756. for (var _c = 0; _c < exemplarsIndices.length; _c++) {
  5757. retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);
  5758. }
  5759. return retClusters;
  5760. };
  5761. var affinityPropagation$1 = {
  5762. affinityPropagation: affinityPropagation,
  5763. ap: affinityPropagation
  5764. };
  5765. var hierholzerDefaults = defaults$g({
  5766. root: undefined,
  5767. directed: false
  5768. });
  5769. var elesfn$k = {
  5770. hierholzer: function hierholzer(options) {
  5771. if (!plainObject(options)) {
  5772. var args = arguments;
  5773. options = {
  5774. root: args[0],
  5775. directed: args[1]
  5776. };
  5777. }
  5778. var _hierholzerDefaults = hierholzerDefaults(options),
  5779. root = _hierholzerDefaults.root,
  5780. directed = _hierholzerDefaults.directed;
  5781. var eles = this;
  5782. var dflag = false;
  5783. var oddIn;
  5784. var oddOut;
  5785. var startVertex;
  5786. if (root) startVertex = string(root) ? this.filter(root)[0].id() : root[0].id();
  5787. var nodes = {};
  5788. var edges = {};
  5789. if (directed) {
  5790. eles.forEach(function (ele) {
  5791. var id = ele.id();
  5792. if (ele.isNode()) {
  5793. var ind = ele.indegree(true);
  5794. var outd = ele.outdegree(true);
  5795. var d1 = ind - outd;
  5796. var d2 = outd - ind;
  5797. if (d1 == 1) {
  5798. if (oddIn) dflag = true;else oddIn = id;
  5799. } else if (d2 == 1) {
  5800. if (oddOut) dflag = true;else oddOut = id;
  5801. } else if (d2 > 1 || d1 > 1) {
  5802. dflag = true;
  5803. }
  5804. nodes[id] = [];
  5805. ele.outgoers().forEach(function (e) {
  5806. if (e.isEdge()) nodes[id].push(e.id());
  5807. });
  5808. } else {
  5809. edges[id] = [undefined, ele.target().id()];
  5810. }
  5811. });
  5812. } else {
  5813. eles.forEach(function (ele) {
  5814. var id = ele.id();
  5815. if (ele.isNode()) {
  5816. var d = ele.degree(true);
  5817. if (d % 2) {
  5818. if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;
  5819. }
  5820. nodes[id] = [];
  5821. ele.connectedEdges().forEach(function (e) {
  5822. return nodes[id].push(e.id());
  5823. });
  5824. } else {
  5825. edges[id] = [ele.source().id(), ele.target().id()];
  5826. }
  5827. });
  5828. }
  5829. var result = {
  5830. found: false,
  5831. trail: undefined
  5832. };
  5833. if (dflag) return result;else if (oddOut && oddIn) {
  5834. if (directed) {
  5835. if (startVertex && oddOut != startVertex) {
  5836. return result;
  5837. }
  5838. startVertex = oddOut;
  5839. } else {
  5840. if (startVertex && oddOut != startVertex && oddIn != startVertex) {
  5841. return result;
  5842. } else if (!startVertex) {
  5843. startVertex = oddOut;
  5844. }
  5845. }
  5846. } else {
  5847. if (!startVertex) startVertex = eles[0].id();
  5848. }
  5849. var walk = function walk(v) {
  5850. var currentNode = v;
  5851. var subtour = [v];
  5852. var adj, adjTail, adjHead;
  5853. while (nodes[currentNode].length) {
  5854. adj = nodes[currentNode].shift();
  5855. adjTail = edges[adj][0];
  5856. adjHead = edges[adj][1];
  5857. if (currentNode != adjHead) {
  5858. nodes[adjHead] = nodes[adjHead].filter(function (e) {
  5859. return e != adj;
  5860. });
  5861. currentNode = adjHead;
  5862. } else if (!directed && currentNode != adjTail) {
  5863. nodes[adjTail] = nodes[adjTail].filter(function (e) {
  5864. return e != adj;
  5865. });
  5866. currentNode = adjTail;
  5867. }
  5868. subtour.unshift(adj);
  5869. subtour.unshift(currentNode);
  5870. }
  5871. return subtour;
  5872. };
  5873. var trail = [];
  5874. var subtour = [];
  5875. subtour = walk(startVertex);
  5876. while (subtour.length != 1) {
  5877. if (nodes[subtour[0]].length == 0) {
  5878. trail.unshift(eles.getElementById(subtour.shift()));
  5879. trail.unshift(eles.getElementById(subtour.shift()));
  5880. } else {
  5881. subtour = walk(subtour.shift()).concat(subtour);
  5882. }
  5883. }
  5884. trail.unshift(eles.getElementById(subtour.shift())); // final node
  5885. for (var d in nodes) {
  5886. if (nodes[d].length) {
  5887. return result;
  5888. }
  5889. }
  5890. result.found = true;
  5891. result.trail = this.spawn(trail, true);
  5892. return result;
  5893. }
  5894. };
  5895. var hopcroftTarjanBiconnected = function hopcroftTarjanBiconnected() {
  5896. var eles = this;
  5897. var nodes = {};
  5898. var id = 0;
  5899. var edgeCount = 0;
  5900. var components = [];
  5901. var stack = [];
  5902. var visitedEdges = {};
  5903. var buildComponent = function buildComponent(x, y) {
  5904. var i = stack.length - 1;
  5905. var cutset = [];
  5906. var component = eles.spawn();
  5907. while (stack[i].x != x || stack[i].y != y) {
  5908. cutset.push(stack.pop().edge);
  5909. i--;
  5910. }
  5911. cutset.push(stack.pop().edge);
  5912. cutset.forEach(function (edge) {
  5913. var connectedNodes = edge.connectedNodes().intersection(eles);
  5914. component.merge(edge);
  5915. connectedNodes.forEach(function (node) {
  5916. var nodeId = node.id();
  5917. var connectedEdges = node.connectedEdges().intersection(eles);
  5918. component.merge(node);
  5919. if (!nodes[nodeId].cutVertex) {
  5920. component.merge(connectedEdges);
  5921. } else {
  5922. component.merge(connectedEdges.filter(function (edge) {
  5923. return edge.isLoop();
  5924. }));
  5925. }
  5926. });
  5927. });
  5928. components.push(component);
  5929. };
  5930. var _biconnectedSearch = function biconnectedSearch(root, currentNode, parent) {
  5931. if (root === parent) edgeCount += 1;
  5932. nodes[currentNode] = {
  5933. id: id,
  5934. low: id++,
  5935. cutVertex: false
  5936. };
  5937. var edges = eles.getElementById(currentNode).connectedEdges().intersection(eles);
  5938. if (edges.size() === 0) {
  5939. components.push(eles.spawn(eles.getElementById(currentNode)));
  5940. } else {
  5941. var sourceId, targetId, otherNodeId, edgeId;
  5942. edges.forEach(function (edge) {
  5943. sourceId = edge.source().id();
  5944. targetId = edge.target().id();
  5945. otherNodeId = sourceId === currentNode ? targetId : sourceId;
  5946. if (otherNodeId !== parent) {
  5947. edgeId = edge.id();
  5948. if (!visitedEdges[edgeId]) {
  5949. visitedEdges[edgeId] = true;
  5950. stack.push({
  5951. x: currentNode,
  5952. y: otherNodeId,
  5953. edge: edge
  5954. });
  5955. }
  5956. if (!(otherNodeId in nodes)) {
  5957. _biconnectedSearch(root, otherNodeId, currentNode);
  5958. nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].low);
  5959. if (nodes[currentNode].id <= nodes[otherNodeId].low) {
  5960. nodes[currentNode].cutVertex = true;
  5961. buildComponent(currentNode, otherNodeId);
  5962. }
  5963. } else {
  5964. nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].id);
  5965. }
  5966. }
  5967. });
  5968. }
  5969. };
  5970. eles.forEach(function (ele) {
  5971. if (ele.isNode()) {
  5972. var nodeId = ele.id();
  5973. if (!(nodeId in nodes)) {
  5974. edgeCount = 0;
  5975. _biconnectedSearch(nodeId, nodeId);
  5976. nodes[nodeId].cutVertex = edgeCount > 1;
  5977. }
  5978. }
  5979. });
  5980. var cutVertices = Object.keys(nodes).filter(function (id) {
  5981. return nodes[id].cutVertex;
  5982. }).map(function (id) {
  5983. return eles.getElementById(id);
  5984. });
  5985. return {
  5986. cut: eles.spawn(cutVertices),
  5987. components: components
  5988. };
  5989. };
  5990. var hopcroftTarjanBiconnected$1 = {
  5991. hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,
  5992. htbc: hopcroftTarjanBiconnected,
  5993. htb: hopcroftTarjanBiconnected,
  5994. hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected
  5995. };
  5996. var tarjanStronglyConnected = function tarjanStronglyConnected() {
  5997. var eles = this;
  5998. var nodes = {};
  5999. var index = 0;
  6000. var components = [];
  6001. var stack = [];
  6002. var cut = eles.spawn(eles);
  6003. var _stronglyConnectedSearch = function stronglyConnectedSearch(sourceNodeId) {
  6004. stack.push(sourceNodeId);
  6005. nodes[sourceNodeId] = {
  6006. index: index,
  6007. low: index++,
  6008. explored: false
  6009. };
  6010. var connectedEdges = eles.getElementById(sourceNodeId).connectedEdges().intersection(eles);
  6011. connectedEdges.forEach(function (edge) {
  6012. var targetNodeId = edge.target().id();
  6013. if (targetNodeId !== sourceNodeId) {
  6014. if (!(targetNodeId in nodes)) {
  6015. _stronglyConnectedSearch(targetNodeId);
  6016. }
  6017. if (!nodes[targetNodeId].explored) {
  6018. nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);
  6019. }
  6020. }
  6021. });
  6022. if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {
  6023. var componentNodes = eles.spawn();
  6024. for (;;) {
  6025. var nodeId = stack.pop();
  6026. componentNodes.merge(eles.getElementById(nodeId));
  6027. nodes[nodeId].low = nodes[sourceNodeId].index;
  6028. nodes[nodeId].explored = true;
  6029. if (nodeId === sourceNodeId) {
  6030. break;
  6031. }
  6032. }
  6033. var componentEdges = componentNodes.edgesWith(componentNodes);
  6034. var component = componentNodes.merge(componentEdges);
  6035. components.push(component);
  6036. cut = cut.difference(component);
  6037. }
  6038. };
  6039. eles.forEach(function (ele) {
  6040. if (ele.isNode()) {
  6041. var nodeId = ele.id();
  6042. if (!(nodeId in nodes)) {
  6043. _stronglyConnectedSearch(nodeId);
  6044. }
  6045. }
  6046. });
  6047. return {
  6048. cut: cut,
  6049. components: components
  6050. };
  6051. };
  6052. var tarjanStronglyConnected$1 = {
  6053. tarjanStronglyConnected: tarjanStronglyConnected,
  6054. tsc: tarjanStronglyConnected,
  6055. tscc: tarjanStronglyConnected,
  6056. tarjanStronglyConnectedComponents: tarjanStronglyConnected
  6057. };
  6058. var elesfn$j = {};
  6059. [elesfn$v, elesfn$u, elesfn$t, elesfn$s, elesfn$r, elesfn$q, elesfn$p, elesfn$o, elesfn$n, elesfn$m, elesfn$l, markovClustering$1, kClustering, hierarchicalClustering$1, affinityPropagation$1, elesfn$k, hopcroftTarjanBiconnected$1, tarjanStronglyConnected$1].forEach(function (props) {
  6060. extend(elesfn$j, props);
  6061. });
  6062. /*!
  6063. Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
  6064. Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
  6065. Licensed under The MIT License (http://opensource.org/licenses/MIT)
  6066. */
  6067. /* promise states [Promises/A+ 2.1] */
  6068. var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
  6069. var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
  6070. var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
  6071. /* promise object constructor */
  6072. var _api = function api(executor) {
  6073. /* optionally support non-constructor/plain-function call */
  6074. if (!(this instanceof _api)) return new _api(executor);
  6075. /* initialize object */
  6076. this.id = 'Thenable/1.0.7';
  6077. this.state = STATE_PENDING; /* initial state */
  6078. this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */
  6079. this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */
  6080. this.onFulfilled = []; /* initial handlers */
  6081. this.onRejected = []; /* initial handlers */
  6082. /* provide optional information-hiding proxy */
  6083. this.proxy = {
  6084. then: this.then.bind(this)
  6085. };
  6086. /* support optional executor function */
  6087. if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
  6088. };
  6089. /* promise API methods */
  6090. _api.prototype = {
  6091. /* promise resolving methods */
  6092. fulfill: function fulfill(value) {
  6093. return deliver(this, STATE_FULFILLED, 'fulfillValue', value);
  6094. },
  6095. reject: function reject(value) {
  6096. return deliver(this, STATE_REJECTED, 'rejectReason', value);
  6097. },
  6098. /* "The then Method" [Promises/A+ 1.1, 1.2, 2.2] */
  6099. then: function then(onFulfilled, onRejected) {
  6100. var curr = this;
  6101. var next = new _api(); /* [Promises/A+ 2.2.7] */
  6102. curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill')); /* [Promises/A+ 2.2.2/2.2.6] */
  6103. curr.onRejected.push(resolver(onRejected, next, 'reject')); /* [Promises/A+ 2.2.3/2.2.6] */
  6104. execute(curr);
  6105. return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */
  6106. }
  6107. };
  6108. /* deliver an action */
  6109. var deliver = function deliver(curr, state, name, value) {
  6110. if (curr.state === STATE_PENDING) {
  6111. curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */
  6112. curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */
  6113. execute(curr);
  6114. }
  6115. return curr;
  6116. };
  6117. /* execute all handlers */
  6118. var execute = function execute(curr) {
  6119. if (curr.state === STATE_FULFILLED) execute_handlers(curr, 'onFulfilled', curr.fulfillValue);else if (curr.state === STATE_REJECTED) execute_handlers(curr, 'onRejected', curr.rejectReason);
  6120. };
  6121. /* execute particular set of handlers */
  6122. var execute_handlers = function execute_handlers(curr, name, value) {
  6123. /* global setImmediate: true */
  6124. /* global setTimeout: true */
  6125. /* short-circuit processing */
  6126. if (curr[name].length === 0) return;
  6127. /* iterate over all handlers, exactly once */
  6128. var handlers = curr[name];
  6129. curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */
  6130. var func = function func() {
  6131. for (var i = 0; i < handlers.length; i++) handlers[i](value); /* [Promises/A+ 2.2.5] */
  6132. };
  6133. /* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */
  6134. if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);
  6135. };
  6136. /* generate a resolver function */
  6137. var resolver = function resolver(cb, next, method) {
  6138. return function (value) {
  6139. if (typeof cb !== 'function') /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */
  6140. next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */else {
  6141. var result;
  6142. try {
  6143. result = cb(value);
  6144. } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */ catch (e) {
  6145. next.reject(e); /* [Promises/A+ 2.2.7.2] */
  6146. return;
  6147. }
  6148. _resolve(next, result); /* [Promises/A+ 2.2.7.1] */
  6149. }
  6150. };
  6151. };
  6152. /* "Promise Resolution Procedure" */ /* [Promises/A+ 2.3] */
  6153. var _resolve = function resolve(promise, x) {
  6154. /* sanity check arguments */ /* [Promises/A+ 2.3.1] */
  6155. if (promise === x || promise.proxy === x) {
  6156. promise.reject(new TypeError('cannot resolve promise with itself'));
  6157. return;
  6158. }
  6159. /* surgically check for a "then" method
  6160. (mainly to just call the "getter" of "then" only once) */
  6161. var then;
  6162. if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {
  6163. try {
  6164. then = x.then;
  6165. } /* [Promises/A+ 2.3.3.1, 3.5] */ catch (e) {
  6166. promise.reject(e); /* [Promises/A+ 2.3.3.2] */
  6167. return;
  6168. }
  6169. }
  6170. /* handle own Thenables [Promises/A+ 2.3.2]
  6171. and similar "thenables" [Promises/A+ 2.3.3] */
  6172. if (typeof then === 'function') {
  6173. var resolved = false;
  6174. try {
  6175. /* call retrieved "then" method */ /* [Promises/A+ 2.3.3.3] */
  6176. then.call(x, /* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */
  6177. function (y) {
  6178. if (resolved) return;
  6179. resolved = true; /* [Promises/A+ 2.3.3.3.3] */
  6180. if (y === x) /* [Promises/A+ 3.6] */
  6181. promise.reject(new TypeError('circular thenable chain'));else _resolve(promise, y);
  6182. }, /* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */
  6183. function (r) {
  6184. if (resolved) return;
  6185. resolved = true; /* [Promises/A+ 2.3.3.3.3] */
  6186. promise.reject(r);
  6187. });
  6188. } catch (e) {
  6189. if (!resolved) /* [Promises/A+ 2.3.3.3.3] */
  6190. promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */
  6191. }
  6192. return;
  6193. }
  6194. /* handle other values */
  6195. promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */
  6196. };
  6197. // so we always have Promise.all()
  6198. _api.all = function (ps) {
  6199. return new _api(function (resolveAll, rejectAll) {
  6200. var vals = new Array(ps.length);
  6201. var doneCount = 0;
  6202. var fulfill = function fulfill(i, val) {
  6203. vals[i] = val;
  6204. doneCount++;
  6205. if (doneCount === ps.length) {
  6206. resolveAll(vals);
  6207. }
  6208. };
  6209. for (var i = 0; i < ps.length; i++) {
  6210. (function (i) {
  6211. var p = ps[i];
  6212. var isPromise = p != null && p.then != null;
  6213. if (isPromise) {
  6214. p.then(function (val) {
  6215. fulfill(i, val);
  6216. }, function (err) {
  6217. rejectAll(err);
  6218. });
  6219. } else {
  6220. var val = p;
  6221. fulfill(i, val);
  6222. }
  6223. })(i);
  6224. }
  6225. });
  6226. };
  6227. _api.resolve = function (val) {
  6228. return new _api(function (resolve, reject) {
  6229. resolve(val);
  6230. });
  6231. };
  6232. _api.reject = function (val) {
  6233. return new _api(function (resolve, reject) {
  6234. reject(val);
  6235. });
  6236. };
  6237. var Promise$1 = typeof Promise !== 'undefined' ? Promise : _api; // eslint-disable-line no-undef
  6238. var Animation = function Animation(target, opts, opts2) {
  6239. var isCore = core(target);
  6240. var isEle = !isCore;
  6241. var _p = this._private = extend({
  6242. duration: 1000
  6243. }, opts, opts2);
  6244. _p.target = target;
  6245. _p.style = _p.style || _p.css;
  6246. _p.started = false;
  6247. _p.playing = false;
  6248. _p.hooked = false;
  6249. _p.applying = false;
  6250. _p.progress = 0;
  6251. _p.completes = [];
  6252. _p.frames = [];
  6253. if (_p.complete && fn$6(_p.complete)) {
  6254. _p.completes.push(_p.complete);
  6255. }
  6256. if (isEle) {
  6257. var pos = target.position();
  6258. _p.startPosition = _p.startPosition || {
  6259. x: pos.x,
  6260. y: pos.y
  6261. };
  6262. _p.startStyle = _p.startStyle || target.cy().style().getAnimationStartStyle(target, _p.style);
  6263. }
  6264. if (isCore) {
  6265. var pan = target.pan();
  6266. _p.startPan = {
  6267. x: pan.x,
  6268. y: pan.y
  6269. };
  6270. _p.startZoom = target.zoom();
  6271. }
  6272. // for future timeline/animations impl
  6273. this.length = 1;
  6274. this[0] = this;
  6275. };
  6276. var anifn = Animation.prototype;
  6277. extend(anifn, {
  6278. instanceString: function instanceString() {
  6279. return 'animation';
  6280. },
  6281. hook: function hook() {
  6282. var _p = this._private;
  6283. if (!_p.hooked) {
  6284. // add to target's animation queue
  6285. var q;
  6286. var tAni = _p.target._private.animation;
  6287. if (_p.queue) {
  6288. q = tAni.queue;
  6289. } else {
  6290. q = tAni.current;
  6291. }
  6292. q.push(this);
  6293. // add to the animation loop pool
  6294. if (elementOrCollection(_p.target)) {
  6295. _p.target.cy().addToAnimationPool(_p.target);
  6296. }
  6297. _p.hooked = true;
  6298. }
  6299. return this;
  6300. },
  6301. play: function play() {
  6302. var _p = this._private;
  6303. // autorewind
  6304. if (_p.progress === 1) {
  6305. _p.progress = 0;
  6306. }
  6307. _p.playing = true;
  6308. _p.started = false; // needs to be started by animation loop
  6309. _p.stopped = false;
  6310. this.hook();
  6311. // the animation loop will start the animation...
  6312. return this;
  6313. },
  6314. playing: function playing() {
  6315. return this._private.playing;
  6316. },
  6317. apply: function apply() {
  6318. var _p = this._private;
  6319. _p.applying = true;
  6320. _p.started = false; // needs to be started by animation loop
  6321. _p.stopped = false;
  6322. this.hook();
  6323. // the animation loop will apply the animation at this progress
  6324. return this;
  6325. },
  6326. applying: function applying() {
  6327. return this._private.applying;
  6328. },
  6329. pause: function pause() {
  6330. var _p = this._private;
  6331. _p.playing = false;
  6332. _p.started = false;
  6333. return this;
  6334. },
  6335. stop: function stop() {
  6336. var _p = this._private;
  6337. _p.playing = false;
  6338. _p.started = false;
  6339. _p.stopped = true; // to be removed from animation queues
  6340. return this;
  6341. },
  6342. rewind: function rewind() {
  6343. return this.progress(0);
  6344. },
  6345. fastforward: function fastforward() {
  6346. return this.progress(1);
  6347. },
  6348. time: function time(t) {
  6349. var _p = this._private;
  6350. if (t === undefined) {
  6351. return _p.progress * _p.duration;
  6352. } else {
  6353. return this.progress(t / _p.duration);
  6354. }
  6355. },
  6356. progress: function progress(p) {
  6357. var _p = this._private;
  6358. var wasPlaying = _p.playing;
  6359. if (p === undefined) {
  6360. return _p.progress;
  6361. } else {
  6362. if (wasPlaying) {
  6363. this.pause();
  6364. }
  6365. _p.progress = p;
  6366. _p.started = false;
  6367. if (wasPlaying) {
  6368. this.play();
  6369. }
  6370. }
  6371. return this;
  6372. },
  6373. completed: function completed() {
  6374. return this._private.progress === 1;
  6375. },
  6376. reverse: function reverse() {
  6377. var _p = this._private;
  6378. var wasPlaying = _p.playing;
  6379. if (wasPlaying) {
  6380. this.pause();
  6381. }
  6382. _p.progress = 1 - _p.progress;
  6383. _p.started = false;
  6384. var swap = function swap(a, b) {
  6385. var _pa = _p[a];
  6386. if (_pa == null) {
  6387. return;
  6388. }
  6389. _p[a] = _p[b];
  6390. _p[b] = _pa;
  6391. };
  6392. swap('zoom', 'startZoom');
  6393. swap('pan', 'startPan');
  6394. swap('position', 'startPosition');
  6395. // swap styles
  6396. if (_p.style) {
  6397. for (var i = 0; i < _p.style.length; i++) {
  6398. var prop = _p.style[i];
  6399. var name = prop.name;
  6400. var startStyleProp = _p.startStyle[name];
  6401. _p.startStyle[name] = prop;
  6402. _p.style[i] = startStyleProp;
  6403. }
  6404. }
  6405. if (wasPlaying) {
  6406. this.play();
  6407. }
  6408. return this;
  6409. },
  6410. promise: function promise(type) {
  6411. var _p = this._private;
  6412. var arr;
  6413. switch (type) {
  6414. case 'frame':
  6415. arr = _p.frames;
  6416. break;
  6417. default:
  6418. case 'complete':
  6419. case 'completed':
  6420. arr = _p.completes;
  6421. }
  6422. return new Promise$1(function (resolve, reject) {
  6423. arr.push(function () {
  6424. resolve();
  6425. });
  6426. });
  6427. }
  6428. });
  6429. anifn.complete = anifn.completed;
  6430. anifn.run = anifn.play;
  6431. anifn.running = anifn.playing;
  6432. var define$3 = {
  6433. animated: function animated() {
  6434. return function animatedImpl() {
  6435. var self = this;
  6436. var selfIsArrayLike = self.length !== undefined;
  6437. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6438. var cy = this._private.cy || this;
  6439. if (!cy.styleEnabled()) {
  6440. return false;
  6441. }
  6442. var ele = all[0];
  6443. if (ele) {
  6444. return ele._private.animation.current.length > 0;
  6445. }
  6446. };
  6447. },
  6448. // animated
  6449. clearQueue: function clearQueue() {
  6450. return function clearQueueImpl() {
  6451. var self = this;
  6452. var selfIsArrayLike = self.length !== undefined;
  6453. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6454. var cy = this._private.cy || this;
  6455. if (!cy.styleEnabled()) {
  6456. return this;
  6457. }
  6458. for (var i = 0; i < all.length; i++) {
  6459. var ele = all[i];
  6460. ele._private.animation.queue = [];
  6461. }
  6462. return this;
  6463. };
  6464. },
  6465. // clearQueue
  6466. delay: function delay() {
  6467. return function delayImpl(time, complete) {
  6468. var cy = this._private.cy || this;
  6469. if (!cy.styleEnabled()) {
  6470. return this;
  6471. }
  6472. return this.animate({
  6473. delay: time,
  6474. duration: time,
  6475. complete: complete
  6476. });
  6477. };
  6478. },
  6479. // delay
  6480. delayAnimation: function delayAnimation() {
  6481. return function delayAnimationImpl(time, complete) {
  6482. var cy = this._private.cy || this;
  6483. if (!cy.styleEnabled()) {
  6484. return this;
  6485. }
  6486. return this.animation({
  6487. delay: time,
  6488. duration: time,
  6489. complete: complete
  6490. });
  6491. };
  6492. },
  6493. // delay
  6494. animation: function animation() {
  6495. return function animationImpl(properties, params) {
  6496. var self = this;
  6497. var selfIsArrayLike = self.length !== undefined;
  6498. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6499. var cy = this._private.cy || this;
  6500. var isCore = !selfIsArrayLike;
  6501. var isEles = !isCore;
  6502. if (!cy.styleEnabled()) {
  6503. return this;
  6504. }
  6505. var style = cy.style();
  6506. properties = extend({}, properties, params);
  6507. var propertiesEmpty = Object.keys(properties).length === 0;
  6508. if (propertiesEmpty) {
  6509. return new Animation(all[0], properties); // nothing to animate
  6510. }
  6511. if (properties.duration === undefined) {
  6512. properties.duration = 400;
  6513. }
  6514. switch (properties.duration) {
  6515. case 'slow':
  6516. properties.duration = 600;
  6517. break;
  6518. case 'fast':
  6519. properties.duration = 200;
  6520. break;
  6521. }
  6522. if (isEles) {
  6523. properties.style = style.getPropsList(properties.style || properties.css);
  6524. properties.css = undefined;
  6525. }
  6526. if (isEles && properties.renderedPosition != null) {
  6527. var rpos = properties.renderedPosition;
  6528. var pan = cy.pan();
  6529. var zoom = cy.zoom();
  6530. properties.position = renderedToModelPosition(rpos, zoom, pan);
  6531. }
  6532. // override pan w/ panBy if set
  6533. if (isCore && properties.panBy != null) {
  6534. var panBy = properties.panBy;
  6535. var cyPan = cy.pan();
  6536. properties.pan = {
  6537. x: cyPan.x + panBy.x,
  6538. y: cyPan.y + panBy.y
  6539. };
  6540. }
  6541. // override pan w/ center if set
  6542. var center = properties.center || properties.centre;
  6543. if (isCore && center != null) {
  6544. var centerPan = cy.getCenterPan(center.eles, properties.zoom);
  6545. if (centerPan != null) {
  6546. properties.pan = centerPan;
  6547. }
  6548. }
  6549. // override pan & zoom w/ fit if set
  6550. if (isCore && properties.fit != null) {
  6551. var fit = properties.fit;
  6552. var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);
  6553. if (fitVp != null) {
  6554. properties.pan = fitVp.pan;
  6555. properties.zoom = fitVp.zoom;
  6556. }
  6557. }
  6558. // override zoom (& potentially pan) w/ zoom obj if set
  6559. if (isCore && plainObject(properties.zoom)) {
  6560. var vp = cy.getZoomedViewport(properties.zoom);
  6561. if (vp != null) {
  6562. if (vp.zoomed) {
  6563. properties.zoom = vp.zoom;
  6564. }
  6565. if (vp.panned) {
  6566. properties.pan = vp.pan;
  6567. }
  6568. } else {
  6569. properties.zoom = null; // an inavalid zoom (e.g. no delta) gets automatically destroyed
  6570. }
  6571. }
  6572. return new Animation(all[0], properties);
  6573. };
  6574. },
  6575. // animate
  6576. animate: function animate() {
  6577. return function animateImpl(properties, params) {
  6578. var self = this;
  6579. var selfIsArrayLike = self.length !== undefined;
  6580. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6581. var cy = this._private.cy || this;
  6582. if (!cy.styleEnabled()) {
  6583. return this;
  6584. }
  6585. if (params) {
  6586. properties = extend({}, properties, params);
  6587. }
  6588. // manually hook and run the animation
  6589. for (var i = 0; i < all.length; i++) {
  6590. var ele = all[i];
  6591. var queue = ele.animated() && (properties.queue === undefined || properties.queue);
  6592. var ani = ele.animation(properties, queue ? {
  6593. queue: true
  6594. } : undefined);
  6595. ani.play();
  6596. }
  6597. return this; // chaining
  6598. };
  6599. },
  6600. // animate
  6601. stop: function stop() {
  6602. return function stopImpl(clearQueue, jumpToEnd) {
  6603. var self = this;
  6604. var selfIsArrayLike = self.length !== undefined;
  6605. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6606. var cy = this._private.cy || this;
  6607. if (!cy.styleEnabled()) {
  6608. return this;
  6609. }
  6610. for (var i = 0; i < all.length; i++) {
  6611. var ele = all[i];
  6612. var _p = ele._private;
  6613. var anis = _p.animation.current;
  6614. for (var j = 0; j < anis.length; j++) {
  6615. var ani = anis[j];
  6616. var ani_p = ani._private;
  6617. if (jumpToEnd) {
  6618. // next iteration of the animation loop, the animation
  6619. // will go straight to the end and be removed
  6620. ani_p.duration = 0;
  6621. }
  6622. }
  6623. // clear the queue of future animations
  6624. if (clearQueue) {
  6625. _p.animation.queue = [];
  6626. }
  6627. if (!jumpToEnd) {
  6628. _p.animation.current = [];
  6629. }
  6630. }
  6631. // we have to notify (the animation loop doesn't do it for us on `stop`)
  6632. cy.notify('draw');
  6633. return this;
  6634. };
  6635. } // stop
  6636. }; // define
  6637. /**
  6638. * Checks if `value` is classified as an `Array` object.
  6639. *
  6640. * @static
  6641. * @memberOf _
  6642. * @since 0.1.0
  6643. * @category Lang
  6644. * @param {*} value The value to check.
  6645. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  6646. * @example
  6647. *
  6648. * _.isArray([1, 2, 3]);
  6649. * // => true
  6650. *
  6651. * _.isArray(document.body.children);
  6652. * // => false
  6653. *
  6654. * _.isArray('abc');
  6655. * // => false
  6656. *
  6657. * _.isArray(_.noop);
  6658. * // => false
  6659. */
  6660. var isArray_1;
  6661. var hasRequiredIsArray;
  6662. function requireIsArray () {
  6663. if (hasRequiredIsArray) return isArray_1;
  6664. hasRequiredIsArray = 1;
  6665. var isArray = Array.isArray;
  6666. isArray_1 = isArray;
  6667. return isArray_1;
  6668. }
  6669. var _isKey;
  6670. var hasRequired_isKey;
  6671. function require_isKey () {
  6672. if (hasRequired_isKey) return _isKey;
  6673. hasRequired_isKey = 1;
  6674. var isArray = requireIsArray(),
  6675. isSymbol = requireIsSymbol();
  6676. /** Used to match property names within property paths. */
  6677. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  6678. reIsPlainProp = /^\w*$/;
  6679. /**
  6680. * Checks if `value` is a property name and not a property path.
  6681. *
  6682. * @private
  6683. * @param {*} value The value to check.
  6684. * @param {Object} [object] The object to query keys on.
  6685. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  6686. */
  6687. function isKey(value, object) {
  6688. if (isArray(value)) {
  6689. return false;
  6690. }
  6691. var type = typeof value;
  6692. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  6693. value == null || isSymbol(value)) {
  6694. return true;
  6695. }
  6696. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  6697. (object != null && value in Object(object));
  6698. }
  6699. _isKey = isKey;
  6700. return _isKey;
  6701. }
  6702. var isFunction_1;
  6703. var hasRequiredIsFunction;
  6704. function requireIsFunction () {
  6705. if (hasRequiredIsFunction) return isFunction_1;
  6706. hasRequiredIsFunction = 1;
  6707. var baseGetTag = require_baseGetTag(),
  6708. isObject = requireIsObject();
  6709. /** `Object#toString` result references. */
  6710. var asyncTag = '[object AsyncFunction]',
  6711. funcTag = '[object Function]',
  6712. genTag = '[object GeneratorFunction]',
  6713. proxyTag = '[object Proxy]';
  6714. /**
  6715. * Checks if `value` is classified as a `Function` object.
  6716. *
  6717. * @static
  6718. * @memberOf _
  6719. * @since 0.1.0
  6720. * @category Lang
  6721. * @param {*} value The value to check.
  6722. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  6723. * @example
  6724. *
  6725. * _.isFunction(_);
  6726. * // => true
  6727. *
  6728. * _.isFunction(/abc/);
  6729. * // => false
  6730. */
  6731. function isFunction(value) {
  6732. if (!isObject(value)) {
  6733. return false;
  6734. }
  6735. // The use of `Object#toString` avoids issues with the `typeof` operator
  6736. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  6737. var tag = baseGetTag(value);
  6738. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  6739. }
  6740. isFunction_1 = isFunction;
  6741. return isFunction_1;
  6742. }
  6743. var _coreJsData;
  6744. var hasRequired_coreJsData;
  6745. function require_coreJsData () {
  6746. if (hasRequired_coreJsData) return _coreJsData;
  6747. hasRequired_coreJsData = 1;
  6748. var root = require_root();
  6749. /** Used to detect overreaching core-js shims. */
  6750. var coreJsData = root['__core-js_shared__'];
  6751. _coreJsData = coreJsData;
  6752. return _coreJsData;
  6753. }
  6754. var _isMasked;
  6755. var hasRequired_isMasked;
  6756. function require_isMasked () {
  6757. if (hasRequired_isMasked) return _isMasked;
  6758. hasRequired_isMasked = 1;
  6759. var coreJsData = require_coreJsData();
  6760. /** Used to detect methods masquerading as native. */
  6761. var maskSrcKey = (function() {
  6762. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  6763. return uid ? ('Symbol(src)_1.' + uid) : '';
  6764. }());
  6765. /**
  6766. * Checks if `func` has its source masked.
  6767. *
  6768. * @private
  6769. * @param {Function} func The function to check.
  6770. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  6771. */
  6772. function isMasked(func) {
  6773. return !!maskSrcKey && (maskSrcKey in func);
  6774. }
  6775. _isMasked = isMasked;
  6776. return _isMasked;
  6777. }
  6778. /** Used for built-in method references. */
  6779. var _toSource;
  6780. var hasRequired_toSource;
  6781. function require_toSource () {
  6782. if (hasRequired_toSource) return _toSource;
  6783. hasRequired_toSource = 1;
  6784. var funcProto = Function.prototype;
  6785. /** Used to resolve the decompiled source of functions. */
  6786. var funcToString = funcProto.toString;
  6787. /**
  6788. * Converts `func` to its source code.
  6789. *
  6790. * @private
  6791. * @param {Function} func The function to convert.
  6792. * @returns {string} Returns the source code.
  6793. */
  6794. function toSource(func) {
  6795. if (func != null) {
  6796. try {
  6797. return funcToString.call(func);
  6798. } catch (e) {}
  6799. try {
  6800. return (func + '');
  6801. } catch (e) {}
  6802. }
  6803. return '';
  6804. }
  6805. _toSource = toSource;
  6806. return _toSource;
  6807. }
  6808. var _baseIsNative;
  6809. var hasRequired_baseIsNative;
  6810. function require_baseIsNative () {
  6811. if (hasRequired_baseIsNative) return _baseIsNative;
  6812. hasRequired_baseIsNative = 1;
  6813. var isFunction = requireIsFunction(),
  6814. isMasked = require_isMasked(),
  6815. isObject = requireIsObject(),
  6816. toSource = require_toSource();
  6817. /**
  6818. * Used to match `RegExp`
  6819. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  6820. */
  6821. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  6822. /** Used to detect host constructors (Safari). */
  6823. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  6824. /** Used for built-in method references. */
  6825. var funcProto = Function.prototype,
  6826. objectProto = Object.prototype;
  6827. /** Used to resolve the decompiled source of functions. */
  6828. var funcToString = funcProto.toString;
  6829. /** Used to check objects for own properties. */
  6830. var hasOwnProperty = objectProto.hasOwnProperty;
  6831. /** Used to detect if a method is native. */
  6832. var reIsNative = RegExp('^' +
  6833. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  6834. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  6835. );
  6836. /**
  6837. * The base implementation of `_.isNative` without bad shim checks.
  6838. *
  6839. * @private
  6840. * @param {*} value The value to check.
  6841. * @returns {boolean} Returns `true` if `value` is a native function,
  6842. * else `false`.
  6843. */
  6844. function baseIsNative(value) {
  6845. if (!isObject(value) || isMasked(value)) {
  6846. return false;
  6847. }
  6848. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  6849. return pattern.test(toSource(value));
  6850. }
  6851. _baseIsNative = baseIsNative;
  6852. return _baseIsNative;
  6853. }
  6854. /**
  6855. * Gets the value at `key` of `object`.
  6856. *
  6857. * @private
  6858. * @param {Object} [object] The object to query.
  6859. * @param {string} key The key of the property to get.
  6860. * @returns {*} Returns the property value.
  6861. */
  6862. var _getValue;
  6863. var hasRequired_getValue;
  6864. function require_getValue () {
  6865. if (hasRequired_getValue) return _getValue;
  6866. hasRequired_getValue = 1;
  6867. function getValue(object, key) {
  6868. return object == null ? undefined : object[key];
  6869. }
  6870. _getValue = getValue;
  6871. return _getValue;
  6872. }
  6873. var _getNative;
  6874. var hasRequired_getNative;
  6875. function require_getNative () {
  6876. if (hasRequired_getNative) return _getNative;
  6877. hasRequired_getNative = 1;
  6878. var baseIsNative = require_baseIsNative(),
  6879. getValue = require_getValue();
  6880. /**
  6881. * Gets the native function at `key` of `object`.
  6882. *
  6883. * @private
  6884. * @param {Object} object The object to query.
  6885. * @param {string} key The key of the method to get.
  6886. * @returns {*} Returns the function if it's native, else `undefined`.
  6887. */
  6888. function getNative(object, key) {
  6889. var value = getValue(object, key);
  6890. return baseIsNative(value) ? value : undefined;
  6891. }
  6892. _getNative = getNative;
  6893. return _getNative;
  6894. }
  6895. var _nativeCreate;
  6896. var hasRequired_nativeCreate;
  6897. function require_nativeCreate () {
  6898. if (hasRequired_nativeCreate) return _nativeCreate;
  6899. hasRequired_nativeCreate = 1;
  6900. var getNative = require_getNative();
  6901. /* Built-in method references that are verified to be native. */
  6902. var nativeCreate = getNative(Object, 'create');
  6903. _nativeCreate = nativeCreate;
  6904. return _nativeCreate;
  6905. }
  6906. var _hashClear;
  6907. var hasRequired_hashClear;
  6908. function require_hashClear () {
  6909. if (hasRequired_hashClear) return _hashClear;
  6910. hasRequired_hashClear = 1;
  6911. var nativeCreate = require_nativeCreate();
  6912. /**
  6913. * Removes all key-value entries from the hash.
  6914. *
  6915. * @private
  6916. * @name clear
  6917. * @memberOf Hash
  6918. */
  6919. function hashClear() {
  6920. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  6921. this.size = 0;
  6922. }
  6923. _hashClear = hashClear;
  6924. return _hashClear;
  6925. }
  6926. /**
  6927. * Removes `key` and its value from the hash.
  6928. *
  6929. * @private
  6930. * @name delete
  6931. * @memberOf Hash
  6932. * @param {Object} hash The hash to modify.
  6933. * @param {string} key The key of the value to remove.
  6934. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  6935. */
  6936. var _hashDelete;
  6937. var hasRequired_hashDelete;
  6938. function require_hashDelete () {
  6939. if (hasRequired_hashDelete) return _hashDelete;
  6940. hasRequired_hashDelete = 1;
  6941. function hashDelete(key) {
  6942. var result = this.has(key) && delete this.__data__[key];
  6943. this.size -= result ? 1 : 0;
  6944. return result;
  6945. }
  6946. _hashDelete = hashDelete;
  6947. return _hashDelete;
  6948. }
  6949. var _hashGet;
  6950. var hasRequired_hashGet;
  6951. function require_hashGet () {
  6952. if (hasRequired_hashGet) return _hashGet;
  6953. hasRequired_hashGet = 1;
  6954. var nativeCreate = require_nativeCreate();
  6955. /** Used to stand-in for `undefined` hash values. */
  6956. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  6957. /** Used for built-in method references. */
  6958. var objectProto = Object.prototype;
  6959. /** Used to check objects for own properties. */
  6960. var hasOwnProperty = objectProto.hasOwnProperty;
  6961. /**
  6962. * Gets the hash value for `key`.
  6963. *
  6964. * @private
  6965. * @name get
  6966. * @memberOf Hash
  6967. * @param {string} key The key of the value to get.
  6968. * @returns {*} Returns the entry value.
  6969. */
  6970. function hashGet(key) {
  6971. var data = this.__data__;
  6972. if (nativeCreate) {
  6973. var result = data[key];
  6974. return result === HASH_UNDEFINED ? undefined : result;
  6975. }
  6976. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  6977. }
  6978. _hashGet = hashGet;
  6979. return _hashGet;
  6980. }
  6981. var _hashHas;
  6982. var hasRequired_hashHas;
  6983. function require_hashHas () {
  6984. if (hasRequired_hashHas) return _hashHas;
  6985. hasRequired_hashHas = 1;
  6986. var nativeCreate = require_nativeCreate();
  6987. /** Used for built-in method references. */
  6988. var objectProto = Object.prototype;
  6989. /** Used to check objects for own properties. */
  6990. var hasOwnProperty = objectProto.hasOwnProperty;
  6991. /**
  6992. * Checks if a hash value for `key` exists.
  6993. *
  6994. * @private
  6995. * @name has
  6996. * @memberOf Hash
  6997. * @param {string} key The key of the entry to check.
  6998. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  6999. */
  7000. function hashHas(key) {
  7001. var data = this.__data__;
  7002. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
  7003. }
  7004. _hashHas = hashHas;
  7005. return _hashHas;
  7006. }
  7007. var _hashSet;
  7008. var hasRequired_hashSet;
  7009. function require_hashSet () {
  7010. if (hasRequired_hashSet) return _hashSet;
  7011. hasRequired_hashSet = 1;
  7012. var nativeCreate = require_nativeCreate();
  7013. /** Used to stand-in for `undefined` hash values. */
  7014. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  7015. /**
  7016. * Sets the hash `key` to `value`.
  7017. *
  7018. * @private
  7019. * @name set
  7020. * @memberOf Hash
  7021. * @param {string} key The key of the value to set.
  7022. * @param {*} value The value to set.
  7023. * @returns {Object} Returns the hash instance.
  7024. */
  7025. function hashSet(key, value) {
  7026. var data = this.__data__;
  7027. this.size += this.has(key) ? 0 : 1;
  7028. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  7029. return this;
  7030. }
  7031. _hashSet = hashSet;
  7032. return _hashSet;
  7033. }
  7034. var _Hash;
  7035. var hasRequired_Hash;
  7036. function require_Hash () {
  7037. if (hasRequired_Hash) return _Hash;
  7038. hasRequired_Hash = 1;
  7039. var hashClear = require_hashClear(),
  7040. hashDelete = require_hashDelete(),
  7041. hashGet = require_hashGet(),
  7042. hashHas = require_hashHas(),
  7043. hashSet = require_hashSet();
  7044. /**
  7045. * Creates a hash object.
  7046. *
  7047. * @private
  7048. * @constructor
  7049. * @param {Array} [entries] The key-value pairs to cache.
  7050. */
  7051. function Hash(entries) {
  7052. var index = -1,
  7053. length = entries == null ? 0 : entries.length;
  7054. this.clear();
  7055. while (++index < length) {
  7056. var entry = entries[index];
  7057. this.set(entry[0], entry[1]);
  7058. }
  7059. }
  7060. // Add methods to `Hash`.
  7061. Hash.prototype.clear = hashClear;
  7062. Hash.prototype['delete'] = hashDelete;
  7063. Hash.prototype.get = hashGet;
  7064. Hash.prototype.has = hashHas;
  7065. Hash.prototype.set = hashSet;
  7066. _Hash = Hash;
  7067. return _Hash;
  7068. }
  7069. /**
  7070. * Removes all key-value entries from the list cache.
  7071. *
  7072. * @private
  7073. * @name clear
  7074. * @memberOf ListCache
  7075. */
  7076. var _listCacheClear;
  7077. var hasRequired_listCacheClear;
  7078. function require_listCacheClear () {
  7079. if (hasRequired_listCacheClear) return _listCacheClear;
  7080. hasRequired_listCacheClear = 1;
  7081. function listCacheClear() {
  7082. this.__data__ = [];
  7083. this.size = 0;
  7084. }
  7085. _listCacheClear = listCacheClear;
  7086. return _listCacheClear;
  7087. }
  7088. /**
  7089. * Performs a
  7090. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7091. * comparison between two values to determine if they are equivalent.
  7092. *
  7093. * @static
  7094. * @memberOf _
  7095. * @since 4.0.0
  7096. * @category Lang
  7097. * @param {*} value The value to compare.
  7098. * @param {*} other The other value to compare.
  7099. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  7100. * @example
  7101. *
  7102. * var object = { 'a': 1 };
  7103. * var other = { 'a': 1 };
  7104. *
  7105. * _.eq(object, object);
  7106. * // => true
  7107. *
  7108. * _.eq(object, other);
  7109. * // => false
  7110. *
  7111. * _.eq('a', 'a');
  7112. * // => true
  7113. *
  7114. * _.eq('a', Object('a'));
  7115. * // => false
  7116. *
  7117. * _.eq(NaN, NaN);
  7118. * // => true
  7119. */
  7120. var eq_1;
  7121. var hasRequiredEq;
  7122. function requireEq () {
  7123. if (hasRequiredEq) return eq_1;
  7124. hasRequiredEq = 1;
  7125. function eq(value, other) {
  7126. return value === other || (value !== value && other !== other);
  7127. }
  7128. eq_1 = eq;
  7129. return eq_1;
  7130. }
  7131. var _assocIndexOf;
  7132. var hasRequired_assocIndexOf;
  7133. function require_assocIndexOf () {
  7134. if (hasRequired_assocIndexOf) return _assocIndexOf;
  7135. hasRequired_assocIndexOf = 1;
  7136. var eq = requireEq();
  7137. /**
  7138. * Gets the index at which the `key` is found in `array` of key-value pairs.
  7139. *
  7140. * @private
  7141. * @param {Array} array The array to inspect.
  7142. * @param {*} key The key to search for.
  7143. * @returns {number} Returns the index of the matched value, else `-1`.
  7144. */
  7145. function assocIndexOf(array, key) {
  7146. var length = array.length;
  7147. while (length--) {
  7148. if (eq(array[length][0], key)) {
  7149. return length;
  7150. }
  7151. }
  7152. return -1;
  7153. }
  7154. _assocIndexOf = assocIndexOf;
  7155. return _assocIndexOf;
  7156. }
  7157. var _listCacheDelete;
  7158. var hasRequired_listCacheDelete;
  7159. function require_listCacheDelete () {
  7160. if (hasRequired_listCacheDelete) return _listCacheDelete;
  7161. hasRequired_listCacheDelete = 1;
  7162. var assocIndexOf = require_assocIndexOf();
  7163. /** Used for built-in method references. */
  7164. var arrayProto = Array.prototype;
  7165. /** Built-in value references. */
  7166. var splice = arrayProto.splice;
  7167. /**
  7168. * Removes `key` and its value from the list cache.
  7169. *
  7170. * @private
  7171. * @name delete
  7172. * @memberOf ListCache
  7173. * @param {string} key The key of the value to remove.
  7174. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7175. */
  7176. function listCacheDelete(key) {
  7177. var data = this.__data__,
  7178. index = assocIndexOf(data, key);
  7179. if (index < 0) {
  7180. return false;
  7181. }
  7182. var lastIndex = data.length - 1;
  7183. if (index == lastIndex) {
  7184. data.pop();
  7185. } else {
  7186. splice.call(data, index, 1);
  7187. }
  7188. --this.size;
  7189. return true;
  7190. }
  7191. _listCacheDelete = listCacheDelete;
  7192. return _listCacheDelete;
  7193. }
  7194. var _listCacheGet;
  7195. var hasRequired_listCacheGet;
  7196. function require_listCacheGet () {
  7197. if (hasRequired_listCacheGet) return _listCacheGet;
  7198. hasRequired_listCacheGet = 1;
  7199. var assocIndexOf = require_assocIndexOf();
  7200. /**
  7201. * Gets the list cache value for `key`.
  7202. *
  7203. * @private
  7204. * @name get
  7205. * @memberOf ListCache
  7206. * @param {string} key The key of the value to get.
  7207. * @returns {*} Returns the entry value.
  7208. */
  7209. function listCacheGet(key) {
  7210. var data = this.__data__,
  7211. index = assocIndexOf(data, key);
  7212. return index < 0 ? undefined : data[index][1];
  7213. }
  7214. _listCacheGet = listCacheGet;
  7215. return _listCacheGet;
  7216. }
  7217. var _listCacheHas;
  7218. var hasRequired_listCacheHas;
  7219. function require_listCacheHas () {
  7220. if (hasRequired_listCacheHas) return _listCacheHas;
  7221. hasRequired_listCacheHas = 1;
  7222. var assocIndexOf = require_assocIndexOf();
  7223. /**
  7224. * Checks if a list cache value for `key` exists.
  7225. *
  7226. * @private
  7227. * @name has
  7228. * @memberOf ListCache
  7229. * @param {string} key The key of the entry to check.
  7230. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7231. */
  7232. function listCacheHas(key) {
  7233. return assocIndexOf(this.__data__, key) > -1;
  7234. }
  7235. _listCacheHas = listCacheHas;
  7236. return _listCacheHas;
  7237. }
  7238. var _listCacheSet;
  7239. var hasRequired_listCacheSet;
  7240. function require_listCacheSet () {
  7241. if (hasRequired_listCacheSet) return _listCacheSet;
  7242. hasRequired_listCacheSet = 1;
  7243. var assocIndexOf = require_assocIndexOf();
  7244. /**
  7245. * Sets the list cache `key` to `value`.
  7246. *
  7247. * @private
  7248. * @name set
  7249. * @memberOf ListCache
  7250. * @param {string} key The key of the value to set.
  7251. * @param {*} value The value to set.
  7252. * @returns {Object} Returns the list cache instance.
  7253. */
  7254. function listCacheSet(key, value) {
  7255. var data = this.__data__,
  7256. index = assocIndexOf(data, key);
  7257. if (index < 0) {
  7258. ++this.size;
  7259. data.push([key, value]);
  7260. } else {
  7261. data[index][1] = value;
  7262. }
  7263. return this;
  7264. }
  7265. _listCacheSet = listCacheSet;
  7266. return _listCacheSet;
  7267. }
  7268. var _ListCache;
  7269. var hasRequired_ListCache;
  7270. function require_ListCache () {
  7271. if (hasRequired_ListCache) return _ListCache;
  7272. hasRequired_ListCache = 1;
  7273. var listCacheClear = require_listCacheClear(),
  7274. listCacheDelete = require_listCacheDelete(),
  7275. listCacheGet = require_listCacheGet(),
  7276. listCacheHas = require_listCacheHas(),
  7277. listCacheSet = require_listCacheSet();
  7278. /**
  7279. * Creates an list cache object.
  7280. *
  7281. * @private
  7282. * @constructor
  7283. * @param {Array} [entries] The key-value pairs to cache.
  7284. */
  7285. function ListCache(entries) {
  7286. var index = -1,
  7287. length = entries == null ? 0 : entries.length;
  7288. this.clear();
  7289. while (++index < length) {
  7290. var entry = entries[index];
  7291. this.set(entry[0], entry[1]);
  7292. }
  7293. }
  7294. // Add methods to `ListCache`.
  7295. ListCache.prototype.clear = listCacheClear;
  7296. ListCache.prototype['delete'] = listCacheDelete;
  7297. ListCache.prototype.get = listCacheGet;
  7298. ListCache.prototype.has = listCacheHas;
  7299. ListCache.prototype.set = listCacheSet;
  7300. _ListCache = ListCache;
  7301. return _ListCache;
  7302. }
  7303. var _Map;
  7304. var hasRequired_Map;
  7305. function require_Map () {
  7306. if (hasRequired_Map) return _Map;
  7307. hasRequired_Map = 1;
  7308. var getNative = require_getNative(),
  7309. root = require_root();
  7310. /* Built-in method references that are verified to be native. */
  7311. var Map = getNative(root, 'Map');
  7312. _Map = Map;
  7313. return _Map;
  7314. }
  7315. var _mapCacheClear;
  7316. var hasRequired_mapCacheClear;
  7317. function require_mapCacheClear () {
  7318. if (hasRequired_mapCacheClear) return _mapCacheClear;
  7319. hasRequired_mapCacheClear = 1;
  7320. var Hash = require_Hash(),
  7321. ListCache = require_ListCache(),
  7322. Map = require_Map();
  7323. /**
  7324. * Removes all key-value entries from the map.
  7325. *
  7326. * @private
  7327. * @name clear
  7328. * @memberOf MapCache
  7329. */
  7330. function mapCacheClear() {
  7331. this.size = 0;
  7332. this.__data__ = {
  7333. 'hash': new Hash,
  7334. 'map': new (Map || ListCache),
  7335. 'string': new Hash
  7336. };
  7337. }
  7338. _mapCacheClear = mapCacheClear;
  7339. return _mapCacheClear;
  7340. }
  7341. /**
  7342. * Checks if `value` is suitable for use as unique object key.
  7343. *
  7344. * @private
  7345. * @param {*} value The value to check.
  7346. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  7347. */
  7348. var _isKeyable;
  7349. var hasRequired_isKeyable;
  7350. function require_isKeyable () {
  7351. if (hasRequired_isKeyable) return _isKeyable;
  7352. hasRequired_isKeyable = 1;
  7353. function isKeyable(value) {
  7354. var type = typeof value;
  7355. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  7356. ? (value !== '__proto__')
  7357. : (value === null);
  7358. }
  7359. _isKeyable = isKeyable;
  7360. return _isKeyable;
  7361. }
  7362. var _getMapData;
  7363. var hasRequired_getMapData;
  7364. function require_getMapData () {
  7365. if (hasRequired_getMapData) return _getMapData;
  7366. hasRequired_getMapData = 1;
  7367. var isKeyable = require_isKeyable();
  7368. /**
  7369. * Gets the data for `map`.
  7370. *
  7371. * @private
  7372. * @param {Object} map The map to query.
  7373. * @param {string} key The reference key.
  7374. * @returns {*} Returns the map data.
  7375. */
  7376. function getMapData(map, key) {
  7377. var data = map.__data__;
  7378. return isKeyable(key)
  7379. ? data[typeof key == 'string' ? 'string' : 'hash']
  7380. : data.map;
  7381. }
  7382. _getMapData = getMapData;
  7383. return _getMapData;
  7384. }
  7385. var _mapCacheDelete;
  7386. var hasRequired_mapCacheDelete;
  7387. function require_mapCacheDelete () {
  7388. if (hasRequired_mapCacheDelete) return _mapCacheDelete;
  7389. hasRequired_mapCacheDelete = 1;
  7390. var getMapData = require_getMapData();
  7391. /**
  7392. * Removes `key` and its value from the map.
  7393. *
  7394. * @private
  7395. * @name delete
  7396. * @memberOf MapCache
  7397. * @param {string} key The key of the value to remove.
  7398. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7399. */
  7400. function mapCacheDelete(key) {
  7401. var result = getMapData(this, key)['delete'](key);
  7402. this.size -= result ? 1 : 0;
  7403. return result;
  7404. }
  7405. _mapCacheDelete = mapCacheDelete;
  7406. return _mapCacheDelete;
  7407. }
  7408. var _mapCacheGet;
  7409. var hasRequired_mapCacheGet;
  7410. function require_mapCacheGet () {
  7411. if (hasRequired_mapCacheGet) return _mapCacheGet;
  7412. hasRequired_mapCacheGet = 1;
  7413. var getMapData = require_getMapData();
  7414. /**
  7415. * Gets the map value for `key`.
  7416. *
  7417. * @private
  7418. * @name get
  7419. * @memberOf MapCache
  7420. * @param {string} key The key of the value to get.
  7421. * @returns {*} Returns the entry value.
  7422. */
  7423. function mapCacheGet(key) {
  7424. return getMapData(this, key).get(key);
  7425. }
  7426. _mapCacheGet = mapCacheGet;
  7427. return _mapCacheGet;
  7428. }
  7429. var _mapCacheHas;
  7430. var hasRequired_mapCacheHas;
  7431. function require_mapCacheHas () {
  7432. if (hasRequired_mapCacheHas) return _mapCacheHas;
  7433. hasRequired_mapCacheHas = 1;
  7434. var getMapData = require_getMapData();
  7435. /**
  7436. * Checks if a map value for `key` exists.
  7437. *
  7438. * @private
  7439. * @name has
  7440. * @memberOf MapCache
  7441. * @param {string} key The key of the entry to check.
  7442. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7443. */
  7444. function mapCacheHas(key) {
  7445. return getMapData(this, key).has(key);
  7446. }
  7447. _mapCacheHas = mapCacheHas;
  7448. return _mapCacheHas;
  7449. }
  7450. var _mapCacheSet;
  7451. var hasRequired_mapCacheSet;
  7452. function require_mapCacheSet () {
  7453. if (hasRequired_mapCacheSet) return _mapCacheSet;
  7454. hasRequired_mapCacheSet = 1;
  7455. var getMapData = require_getMapData();
  7456. /**
  7457. * Sets the map `key` to `value`.
  7458. *
  7459. * @private
  7460. * @name set
  7461. * @memberOf MapCache
  7462. * @param {string} key The key of the value to set.
  7463. * @param {*} value The value to set.
  7464. * @returns {Object} Returns the map cache instance.
  7465. */
  7466. function mapCacheSet(key, value) {
  7467. var data = getMapData(this, key),
  7468. size = data.size;
  7469. data.set(key, value);
  7470. this.size += data.size == size ? 0 : 1;
  7471. return this;
  7472. }
  7473. _mapCacheSet = mapCacheSet;
  7474. return _mapCacheSet;
  7475. }
  7476. var _MapCache;
  7477. var hasRequired_MapCache;
  7478. function require_MapCache () {
  7479. if (hasRequired_MapCache) return _MapCache;
  7480. hasRequired_MapCache = 1;
  7481. var mapCacheClear = require_mapCacheClear(),
  7482. mapCacheDelete = require_mapCacheDelete(),
  7483. mapCacheGet = require_mapCacheGet(),
  7484. mapCacheHas = require_mapCacheHas(),
  7485. mapCacheSet = require_mapCacheSet();
  7486. /**
  7487. * Creates a map cache object to store key-value pairs.
  7488. *
  7489. * @private
  7490. * @constructor
  7491. * @param {Array} [entries] The key-value pairs to cache.
  7492. */
  7493. function MapCache(entries) {
  7494. var index = -1,
  7495. length = entries == null ? 0 : entries.length;
  7496. this.clear();
  7497. while (++index < length) {
  7498. var entry = entries[index];
  7499. this.set(entry[0], entry[1]);
  7500. }
  7501. }
  7502. // Add methods to `MapCache`.
  7503. MapCache.prototype.clear = mapCacheClear;
  7504. MapCache.prototype['delete'] = mapCacheDelete;
  7505. MapCache.prototype.get = mapCacheGet;
  7506. MapCache.prototype.has = mapCacheHas;
  7507. MapCache.prototype.set = mapCacheSet;
  7508. _MapCache = MapCache;
  7509. return _MapCache;
  7510. }
  7511. var memoize_1;
  7512. var hasRequiredMemoize;
  7513. function requireMemoize () {
  7514. if (hasRequiredMemoize) return memoize_1;
  7515. hasRequiredMemoize = 1;
  7516. var MapCache = require_MapCache();
  7517. /** Error message constants. */
  7518. var FUNC_ERROR_TEXT = 'Expected a function';
  7519. /**
  7520. * Creates a function that memoizes the result of `func`. If `resolver` is
  7521. * provided, it determines the cache key for storing the result based on the
  7522. * arguments provided to the memoized function. By default, the first argument
  7523. * provided to the memoized function is used as the map cache key. The `func`
  7524. * is invoked with the `this` binding of the memoized function.
  7525. *
  7526. * **Note:** The cache is exposed as the `cache` property on the memoized
  7527. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  7528. * constructor with one whose instances implement the
  7529. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  7530. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  7531. *
  7532. * @static
  7533. * @memberOf _
  7534. * @since 0.1.0
  7535. * @category Function
  7536. * @param {Function} func The function to have its output memoized.
  7537. * @param {Function} [resolver] The function to resolve the cache key.
  7538. * @returns {Function} Returns the new memoized function.
  7539. * @example
  7540. *
  7541. * var object = { 'a': 1, 'b': 2 };
  7542. * var other = { 'c': 3, 'd': 4 };
  7543. *
  7544. * var values = _.memoize(_.values);
  7545. * values(object);
  7546. * // => [1, 2]
  7547. *
  7548. * values(other);
  7549. * // => [3, 4]
  7550. *
  7551. * object.a = 2;
  7552. * values(object);
  7553. * // => [1, 2]
  7554. *
  7555. * // Modify the result cache.
  7556. * values.cache.set(object, ['a', 'b']);
  7557. * values(object);
  7558. * // => ['a', 'b']
  7559. *
  7560. * // Replace `_.memoize.Cache`.
  7561. * _.memoize.Cache = WeakMap;
  7562. */
  7563. function memoize(func, resolver) {
  7564. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  7565. throw new TypeError(FUNC_ERROR_TEXT);
  7566. }
  7567. var memoized = function() {
  7568. var args = arguments,
  7569. key = resolver ? resolver.apply(this, args) : args[0],
  7570. cache = memoized.cache;
  7571. if (cache.has(key)) {
  7572. return cache.get(key);
  7573. }
  7574. var result = func.apply(this, args);
  7575. memoized.cache = cache.set(key, result) || cache;
  7576. return result;
  7577. };
  7578. memoized.cache = new (memoize.Cache || MapCache);
  7579. return memoized;
  7580. }
  7581. // Expose `MapCache`.
  7582. memoize.Cache = MapCache;
  7583. memoize_1 = memoize;
  7584. return memoize_1;
  7585. }
  7586. var _memoizeCapped;
  7587. var hasRequired_memoizeCapped;
  7588. function require_memoizeCapped () {
  7589. if (hasRequired_memoizeCapped) return _memoizeCapped;
  7590. hasRequired_memoizeCapped = 1;
  7591. var memoize = requireMemoize();
  7592. /** Used as the maximum memoize cache size. */
  7593. var MAX_MEMOIZE_SIZE = 500;
  7594. /**
  7595. * A specialized version of `_.memoize` which clears the memoized function's
  7596. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  7597. *
  7598. * @private
  7599. * @param {Function} func The function to have its output memoized.
  7600. * @returns {Function} Returns the new memoized function.
  7601. */
  7602. function memoizeCapped(func) {
  7603. var result = memoize(func, function(key) {
  7604. if (cache.size === MAX_MEMOIZE_SIZE) {
  7605. cache.clear();
  7606. }
  7607. return key;
  7608. });
  7609. var cache = result.cache;
  7610. return result;
  7611. }
  7612. _memoizeCapped = memoizeCapped;
  7613. return _memoizeCapped;
  7614. }
  7615. var _stringToPath;
  7616. var hasRequired_stringToPath;
  7617. function require_stringToPath () {
  7618. if (hasRequired_stringToPath) return _stringToPath;
  7619. hasRequired_stringToPath = 1;
  7620. var memoizeCapped = require_memoizeCapped();
  7621. /** Used to match property names within property paths. */
  7622. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  7623. /** Used to match backslashes in property paths. */
  7624. var reEscapeChar = /\\(\\)?/g;
  7625. /**
  7626. * Converts `string` to a property path array.
  7627. *
  7628. * @private
  7629. * @param {string} string The string to convert.
  7630. * @returns {Array} Returns the property path array.
  7631. */
  7632. var stringToPath = memoizeCapped(function(string) {
  7633. var result = [];
  7634. if (string.charCodeAt(0) === 46 /* . */) {
  7635. result.push('');
  7636. }
  7637. string.replace(rePropName, function(match, number, quote, subString) {
  7638. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  7639. });
  7640. return result;
  7641. });
  7642. _stringToPath = stringToPath;
  7643. return _stringToPath;
  7644. }
  7645. /**
  7646. * A specialized version of `_.map` for arrays without support for iteratee
  7647. * shorthands.
  7648. *
  7649. * @private
  7650. * @param {Array} [array] The array to iterate over.
  7651. * @param {Function} iteratee The function invoked per iteration.
  7652. * @returns {Array} Returns the new mapped array.
  7653. */
  7654. var _arrayMap;
  7655. var hasRequired_arrayMap;
  7656. function require_arrayMap () {
  7657. if (hasRequired_arrayMap) return _arrayMap;
  7658. hasRequired_arrayMap = 1;
  7659. function arrayMap(array, iteratee) {
  7660. var index = -1,
  7661. length = array == null ? 0 : array.length,
  7662. result = Array(length);
  7663. while (++index < length) {
  7664. result[index] = iteratee(array[index], index, array);
  7665. }
  7666. return result;
  7667. }
  7668. _arrayMap = arrayMap;
  7669. return _arrayMap;
  7670. }
  7671. var _baseToString;
  7672. var hasRequired_baseToString;
  7673. function require_baseToString () {
  7674. if (hasRequired_baseToString) return _baseToString;
  7675. hasRequired_baseToString = 1;
  7676. var Symbol = require_Symbol(),
  7677. arrayMap = require_arrayMap(),
  7678. isArray = requireIsArray(),
  7679. isSymbol = requireIsSymbol();
  7680. /** Used to convert symbols to primitives and strings. */
  7681. var symbolProto = Symbol ? Symbol.prototype : undefined,
  7682. symbolToString = symbolProto ? symbolProto.toString : undefined;
  7683. /**
  7684. * The base implementation of `_.toString` which doesn't convert nullish
  7685. * values to empty strings.
  7686. *
  7687. * @private
  7688. * @param {*} value The value to process.
  7689. * @returns {string} Returns the string.
  7690. */
  7691. function baseToString(value) {
  7692. // Exit early for strings to avoid a performance hit in some environments.
  7693. if (typeof value == 'string') {
  7694. return value;
  7695. }
  7696. if (isArray(value)) {
  7697. // Recursively convert values (susceptible to call stack limits).
  7698. return arrayMap(value, baseToString) + '';
  7699. }
  7700. if (isSymbol(value)) {
  7701. return symbolToString ? symbolToString.call(value) : '';
  7702. }
  7703. var result = (value + '');
  7704. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  7705. }
  7706. _baseToString = baseToString;
  7707. return _baseToString;
  7708. }
  7709. var toString_1;
  7710. var hasRequiredToString;
  7711. function requireToString () {
  7712. if (hasRequiredToString) return toString_1;
  7713. hasRequiredToString = 1;
  7714. var baseToString = require_baseToString();
  7715. /**
  7716. * Converts `value` to a string. An empty string is returned for `null`
  7717. * and `undefined` values. The sign of `-0` is preserved.
  7718. *
  7719. * @static
  7720. * @memberOf _
  7721. * @since 4.0.0
  7722. * @category Lang
  7723. * @param {*} value The value to convert.
  7724. * @returns {string} Returns the converted string.
  7725. * @example
  7726. *
  7727. * _.toString(null);
  7728. * // => ''
  7729. *
  7730. * _.toString(-0);
  7731. * // => '-0'
  7732. *
  7733. * _.toString([1, 2, 3]);
  7734. * // => '1,2,3'
  7735. */
  7736. function toString(value) {
  7737. return value == null ? '' : baseToString(value);
  7738. }
  7739. toString_1 = toString;
  7740. return toString_1;
  7741. }
  7742. var _castPath;
  7743. var hasRequired_castPath;
  7744. function require_castPath () {
  7745. if (hasRequired_castPath) return _castPath;
  7746. hasRequired_castPath = 1;
  7747. var isArray = requireIsArray(),
  7748. isKey = require_isKey(),
  7749. stringToPath = require_stringToPath(),
  7750. toString = requireToString();
  7751. /**
  7752. * Casts `value` to a path array if it's not one.
  7753. *
  7754. * @private
  7755. * @param {*} value The value to inspect.
  7756. * @param {Object} [object] The object to query keys on.
  7757. * @returns {Array} Returns the cast property path array.
  7758. */
  7759. function castPath(value, object) {
  7760. if (isArray(value)) {
  7761. return value;
  7762. }
  7763. return isKey(value, object) ? [value] : stringToPath(toString(value));
  7764. }
  7765. _castPath = castPath;
  7766. return _castPath;
  7767. }
  7768. var _toKey;
  7769. var hasRequired_toKey;
  7770. function require_toKey () {
  7771. if (hasRequired_toKey) return _toKey;
  7772. hasRequired_toKey = 1;
  7773. var isSymbol = requireIsSymbol();
  7774. /**
  7775. * Converts `value` to a string key if it's not a string or symbol.
  7776. *
  7777. * @private
  7778. * @param {*} value The value to inspect.
  7779. * @returns {string|symbol} Returns the key.
  7780. */
  7781. function toKey(value) {
  7782. if (typeof value == 'string' || isSymbol(value)) {
  7783. return value;
  7784. }
  7785. var result = (value + '');
  7786. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  7787. }
  7788. _toKey = toKey;
  7789. return _toKey;
  7790. }
  7791. var _baseGet;
  7792. var hasRequired_baseGet;
  7793. function require_baseGet () {
  7794. if (hasRequired_baseGet) return _baseGet;
  7795. hasRequired_baseGet = 1;
  7796. var castPath = require_castPath(),
  7797. toKey = require_toKey();
  7798. /**
  7799. * The base implementation of `_.get` without support for default values.
  7800. *
  7801. * @private
  7802. * @param {Object} object The object to query.
  7803. * @param {Array|string} path The path of the property to get.
  7804. * @returns {*} Returns the resolved value.
  7805. */
  7806. function baseGet(object, path) {
  7807. path = castPath(path, object);
  7808. var index = 0,
  7809. length = path.length;
  7810. while (object != null && index < length) {
  7811. object = object[toKey(path[index++])];
  7812. }
  7813. return (index && index == length) ? object : undefined;
  7814. }
  7815. _baseGet = baseGet;
  7816. return _baseGet;
  7817. }
  7818. var get_1;
  7819. var hasRequiredGet;
  7820. function requireGet () {
  7821. if (hasRequiredGet) return get_1;
  7822. hasRequiredGet = 1;
  7823. var baseGet = require_baseGet();
  7824. /**
  7825. * Gets the value at `path` of `object`. If the resolved value is
  7826. * `undefined`, the `defaultValue` is returned in its place.
  7827. *
  7828. * @static
  7829. * @memberOf _
  7830. * @since 3.7.0
  7831. * @category Object
  7832. * @param {Object} object The object to query.
  7833. * @param {Array|string} path The path of the property to get.
  7834. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  7835. * @returns {*} Returns the resolved value.
  7836. * @example
  7837. *
  7838. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  7839. *
  7840. * _.get(object, 'a[0].b.c');
  7841. * // => 3
  7842. *
  7843. * _.get(object, ['a', '0', 'b', 'c']);
  7844. * // => 3
  7845. *
  7846. * _.get(object, 'a.b.c', 'default');
  7847. * // => 'default'
  7848. */
  7849. function get(object, path, defaultValue) {
  7850. var result = object == null ? undefined : baseGet(object, path);
  7851. return result === undefined ? defaultValue : result;
  7852. }
  7853. get_1 = get;
  7854. return get_1;
  7855. }
  7856. var getExports = requireGet();
  7857. var get = /*@__PURE__*/getDefaultExportFromCjs(getExports);
  7858. var _defineProperty;
  7859. var hasRequired_defineProperty;
  7860. function require_defineProperty () {
  7861. if (hasRequired_defineProperty) return _defineProperty;
  7862. hasRequired_defineProperty = 1;
  7863. var getNative = require_getNative();
  7864. var defineProperty = (function() {
  7865. try {
  7866. var func = getNative(Object, 'defineProperty');
  7867. func({}, '', {});
  7868. return func;
  7869. } catch (e) {}
  7870. }());
  7871. _defineProperty = defineProperty;
  7872. return _defineProperty;
  7873. }
  7874. var _baseAssignValue;
  7875. var hasRequired_baseAssignValue;
  7876. function require_baseAssignValue () {
  7877. if (hasRequired_baseAssignValue) return _baseAssignValue;
  7878. hasRequired_baseAssignValue = 1;
  7879. var defineProperty = require_defineProperty();
  7880. /**
  7881. * The base implementation of `assignValue` and `assignMergeValue` without
  7882. * value checks.
  7883. *
  7884. * @private
  7885. * @param {Object} object The object to modify.
  7886. * @param {string} key The key of the property to assign.
  7887. * @param {*} value The value to assign.
  7888. */
  7889. function baseAssignValue(object, key, value) {
  7890. if (key == '__proto__' && defineProperty) {
  7891. defineProperty(object, key, {
  7892. 'configurable': true,
  7893. 'enumerable': true,
  7894. 'value': value,
  7895. 'writable': true
  7896. });
  7897. } else {
  7898. object[key] = value;
  7899. }
  7900. }
  7901. _baseAssignValue = baseAssignValue;
  7902. return _baseAssignValue;
  7903. }
  7904. var _assignValue;
  7905. var hasRequired_assignValue;
  7906. function require_assignValue () {
  7907. if (hasRequired_assignValue) return _assignValue;
  7908. hasRequired_assignValue = 1;
  7909. var baseAssignValue = require_baseAssignValue(),
  7910. eq = requireEq();
  7911. /** Used for built-in method references. */
  7912. var objectProto = Object.prototype;
  7913. /** Used to check objects for own properties. */
  7914. var hasOwnProperty = objectProto.hasOwnProperty;
  7915. /**
  7916. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  7917. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7918. * for equality comparisons.
  7919. *
  7920. * @private
  7921. * @param {Object} object The object to modify.
  7922. * @param {string} key The key of the property to assign.
  7923. * @param {*} value The value to assign.
  7924. */
  7925. function assignValue(object, key, value) {
  7926. var objValue = object[key];
  7927. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  7928. (value === undefined && !(key in object))) {
  7929. baseAssignValue(object, key, value);
  7930. }
  7931. }
  7932. _assignValue = assignValue;
  7933. return _assignValue;
  7934. }
  7935. /** Used as references for various `Number` constants. */
  7936. var _isIndex;
  7937. var hasRequired_isIndex;
  7938. function require_isIndex () {
  7939. if (hasRequired_isIndex) return _isIndex;
  7940. hasRequired_isIndex = 1;
  7941. var MAX_SAFE_INTEGER = 9007199254740991;
  7942. /** Used to detect unsigned integer values. */
  7943. var reIsUint = /^(?:0|[1-9]\d*)$/;
  7944. /**
  7945. * Checks if `value` is a valid array-like index.
  7946. *
  7947. * @private
  7948. * @param {*} value The value to check.
  7949. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  7950. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  7951. */
  7952. function isIndex(value, length) {
  7953. var type = typeof value;
  7954. length = length == null ? MAX_SAFE_INTEGER : length;
  7955. return !!length &&
  7956. (type == 'number' ||
  7957. (type != 'symbol' && reIsUint.test(value))) &&
  7958. (value > -1 && value % 1 == 0 && value < length);
  7959. }
  7960. _isIndex = isIndex;
  7961. return _isIndex;
  7962. }
  7963. var _baseSet;
  7964. var hasRequired_baseSet;
  7965. function require_baseSet () {
  7966. if (hasRequired_baseSet) return _baseSet;
  7967. hasRequired_baseSet = 1;
  7968. var assignValue = require_assignValue(),
  7969. castPath = require_castPath(),
  7970. isIndex = require_isIndex(),
  7971. isObject = requireIsObject(),
  7972. toKey = require_toKey();
  7973. /**
  7974. * The base implementation of `_.set`.
  7975. *
  7976. * @private
  7977. * @param {Object} object The object to modify.
  7978. * @param {Array|string} path The path of the property to set.
  7979. * @param {*} value The value to set.
  7980. * @param {Function} [customizer] The function to customize path creation.
  7981. * @returns {Object} Returns `object`.
  7982. */
  7983. function baseSet(object, path, value, customizer) {
  7984. if (!isObject(object)) {
  7985. return object;
  7986. }
  7987. path = castPath(path, object);
  7988. var index = -1,
  7989. length = path.length,
  7990. lastIndex = length - 1,
  7991. nested = object;
  7992. while (nested != null && ++index < length) {
  7993. var key = toKey(path[index]),
  7994. newValue = value;
  7995. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  7996. return object;
  7997. }
  7998. if (index != lastIndex) {
  7999. var objValue = nested[key];
  8000. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  8001. if (newValue === undefined) {
  8002. newValue = isObject(objValue)
  8003. ? objValue
  8004. : (isIndex(path[index + 1]) ? [] : {});
  8005. }
  8006. }
  8007. assignValue(nested, key, newValue);
  8008. nested = nested[key];
  8009. }
  8010. return object;
  8011. }
  8012. _baseSet = baseSet;
  8013. return _baseSet;
  8014. }
  8015. var set_1;
  8016. var hasRequiredSet;
  8017. function requireSet () {
  8018. if (hasRequiredSet) return set_1;
  8019. hasRequiredSet = 1;
  8020. var baseSet = require_baseSet();
  8021. /**
  8022. * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
  8023. * it's created. Arrays are created for missing index properties while objects
  8024. * are created for all other missing properties. Use `_.setWith` to customize
  8025. * `path` creation.
  8026. *
  8027. * **Note:** This method mutates `object`.
  8028. *
  8029. * @static
  8030. * @memberOf _
  8031. * @since 3.7.0
  8032. * @category Object
  8033. * @param {Object} object The object to modify.
  8034. * @param {Array|string} path The path of the property to set.
  8035. * @param {*} value The value to set.
  8036. * @returns {Object} Returns `object`.
  8037. * @example
  8038. *
  8039. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  8040. *
  8041. * _.set(object, 'a[0].b.c', 4);
  8042. * console.log(object.a[0].b.c);
  8043. * // => 4
  8044. *
  8045. * _.set(object, ['x', '0', 'y', 'z'], 5);
  8046. * console.log(object.x[0].y.z);
  8047. * // => 5
  8048. */
  8049. function set(object, path, value) {
  8050. return object == null ? object : baseSet(object, path, value);
  8051. }
  8052. set_1 = set;
  8053. return set_1;
  8054. }
  8055. var setExports = requireSet();
  8056. var set = /*@__PURE__*/getDefaultExportFromCjs(setExports);
  8057. /**
  8058. * Copies the values of `source` to `array`.
  8059. *
  8060. * @private
  8061. * @param {Array} source The array to copy values from.
  8062. * @param {Array} [array=[]] The array to copy values to.
  8063. * @returns {Array} Returns `array`.
  8064. */
  8065. var _copyArray;
  8066. var hasRequired_copyArray;
  8067. function require_copyArray () {
  8068. if (hasRequired_copyArray) return _copyArray;
  8069. hasRequired_copyArray = 1;
  8070. function copyArray(source, array) {
  8071. var index = -1,
  8072. length = source.length;
  8073. array || (array = Array(length));
  8074. while (++index < length) {
  8075. array[index] = source[index];
  8076. }
  8077. return array;
  8078. }
  8079. _copyArray = copyArray;
  8080. return _copyArray;
  8081. }
  8082. var toPath_1;
  8083. var hasRequiredToPath;
  8084. function requireToPath () {
  8085. if (hasRequiredToPath) return toPath_1;
  8086. hasRequiredToPath = 1;
  8087. var arrayMap = require_arrayMap(),
  8088. copyArray = require_copyArray(),
  8089. isArray = requireIsArray(),
  8090. isSymbol = requireIsSymbol(),
  8091. stringToPath = require_stringToPath(),
  8092. toKey = require_toKey(),
  8093. toString = requireToString();
  8094. /**
  8095. * Converts `value` to a property path array.
  8096. *
  8097. * @static
  8098. * @memberOf _
  8099. * @since 4.0.0
  8100. * @category Util
  8101. * @param {*} value The value to convert.
  8102. * @returns {Array} Returns the new property path array.
  8103. * @example
  8104. *
  8105. * _.toPath('a.b.c');
  8106. * // => ['a', 'b', 'c']
  8107. *
  8108. * _.toPath('a[0].b.c');
  8109. * // => ['a', '0', 'b', 'c']
  8110. */
  8111. function toPath(value) {
  8112. if (isArray(value)) {
  8113. return arrayMap(value, toKey);
  8114. }
  8115. return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
  8116. }
  8117. toPath_1 = toPath;
  8118. return toPath_1;
  8119. }
  8120. var toPathExports = requireToPath();
  8121. var toPath = /*@__PURE__*/getDefaultExportFromCjs(toPathExports);
  8122. var define$2 = {
  8123. // access data field
  8124. data: function data(params) {
  8125. var defaults = {
  8126. field: 'data',
  8127. bindingEvent: 'data',
  8128. allowBinding: false,
  8129. allowSetting: false,
  8130. allowGetting: false,
  8131. settingEvent: 'data',
  8132. settingTriggersEvent: false,
  8133. triggerFnName: 'trigger',
  8134. immutableKeys: {},
  8135. // key => true if immutable
  8136. updateStyle: false,
  8137. beforeGet: function beforeGet(self) {},
  8138. beforeSet: function beforeSet(self, obj) {},
  8139. onSet: function onSet(self) {},
  8140. canSet: function canSet(self) {
  8141. return true;
  8142. }
  8143. };
  8144. params = extend({}, defaults, params);
  8145. return function dataImpl(name, value) {
  8146. var p = params;
  8147. var self = this;
  8148. var selfIsArrayLike = self.length !== undefined;
  8149. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  8150. var single = selfIsArrayLike ? self[0] : self;
  8151. // .data('foo', ...)
  8152. if (string(name)) {
  8153. // set or get property
  8154. var isPathLike = name.indexOf('.') !== -1; // there might be a normal field with a dot
  8155. var path = isPathLike && toPath(name);
  8156. // .data('foo')
  8157. if (p.allowGetting && value === undefined) {
  8158. // get
  8159. var ret;
  8160. if (single) {
  8161. p.beforeGet(single);
  8162. // check if it's path and a field with the same name doesn't exist
  8163. if (path && single._private[p.field][name] === undefined) {
  8164. ret = get(single._private[p.field], path);
  8165. } else {
  8166. ret = single._private[p.field][name];
  8167. }
  8168. }
  8169. return ret;
  8170. // .data('foo', 'bar')
  8171. } else if (p.allowSetting && value !== undefined) {
  8172. // set
  8173. var valid = !p.immutableKeys[name];
  8174. if (valid) {
  8175. var change = _defineProperty$1({}, name, value);
  8176. p.beforeSet(self, change);
  8177. for (var i = 0, l = all.length; i < l; i++) {
  8178. var ele = all[i];
  8179. if (p.canSet(ele)) {
  8180. if (path && single._private[p.field][name] === undefined) {
  8181. set(ele._private[p.field], path, value);
  8182. } else {
  8183. ele._private[p.field][name] = value;
  8184. }
  8185. }
  8186. }
  8187. // update mappers if asked
  8188. if (p.updateStyle) {
  8189. self.updateStyle();
  8190. }
  8191. // call onSet callback
  8192. p.onSet(self);
  8193. if (p.settingTriggersEvent) {
  8194. self[p.triggerFnName](p.settingEvent);
  8195. }
  8196. }
  8197. }
  8198. // .data({ 'foo': 'bar' })
  8199. } else if (p.allowSetting && plainObject(name)) {
  8200. // extend
  8201. var obj = name;
  8202. var k, v;
  8203. var keys = Object.keys(obj);
  8204. p.beforeSet(self, obj);
  8205. for (var _i = 0; _i < keys.length; _i++) {
  8206. k = keys[_i];
  8207. v = obj[k];
  8208. var _valid = !p.immutableKeys[k];
  8209. if (_valid) {
  8210. for (var j = 0; j < all.length; j++) {
  8211. var _ele = all[j];
  8212. if (p.canSet(_ele)) {
  8213. _ele._private[p.field][k] = v;
  8214. }
  8215. }
  8216. }
  8217. }
  8218. // update mappers if asked
  8219. if (p.updateStyle) {
  8220. self.updateStyle();
  8221. }
  8222. // call onSet callback
  8223. p.onSet(self);
  8224. if (p.settingTriggersEvent) {
  8225. self[p.triggerFnName](p.settingEvent);
  8226. }
  8227. // .data(function(){ ... })
  8228. } else if (p.allowBinding && fn$6(name)) {
  8229. // bind to event
  8230. var fn = name;
  8231. self.on(p.bindingEvent, fn);
  8232. // .data()
  8233. } else if (p.allowGetting && name === undefined) {
  8234. // get whole object
  8235. var _ret;
  8236. if (single) {
  8237. p.beforeGet(single);
  8238. _ret = single._private[p.field];
  8239. }
  8240. return _ret;
  8241. }
  8242. return self; // maintain chainability
  8243. }; // function
  8244. },
  8245. // data
  8246. // remove data field
  8247. removeData: function removeData(params) {
  8248. var defaults = {
  8249. field: 'data',
  8250. event: 'data',
  8251. triggerFnName: 'trigger',
  8252. triggerEvent: false,
  8253. immutableKeys: {} // key => true if immutable
  8254. };
  8255. params = extend({}, defaults, params);
  8256. return function removeDataImpl(names) {
  8257. var p = params;
  8258. var self = this;
  8259. var selfIsArrayLike = self.length !== undefined;
  8260. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  8261. // .removeData('foo bar')
  8262. if (string(names)) {
  8263. // then get the list of keys, and delete them
  8264. var keys = names.split(/\s+/);
  8265. var l = keys.length;
  8266. for (var i = 0; i < l; i++) {
  8267. // delete each non-empty key
  8268. var key = keys[i];
  8269. if (emptyString(key)) {
  8270. continue;
  8271. }
  8272. var valid = !p.immutableKeys[key]; // not valid if immutable
  8273. if (valid) {
  8274. for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {
  8275. all[i_a]._private[p.field][key] = undefined;
  8276. }
  8277. }
  8278. }
  8279. if (p.triggerEvent) {
  8280. self[p.triggerFnName](p.event);
  8281. }
  8282. // .removeData()
  8283. } else if (names === undefined) {
  8284. // then delete all keys
  8285. for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {
  8286. var _privateFields = all[_i_a]._private[p.field];
  8287. var _keys = Object.keys(_privateFields);
  8288. for (var _i2 = 0; _i2 < _keys.length; _i2++) {
  8289. var _key = _keys[_i2];
  8290. var validKeyToDelete = !p.immutableKeys[_key];
  8291. if (validKeyToDelete) {
  8292. _privateFields[_key] = undefined;
  8293. }
  8294. }
  8295. }
  8296. if (p.triggerEvent) {
  8297. self[p.triggerFnName](p.event);
  8298. }
  8299. }
  8300. return self; // maintain chaining
  8301. }; // function
  8302. } // removeData
  8303. }; // define
  8304. var define$1 = {
  8305. eventAliasesOn: function eventAliasesOn(proto) {
  8306. var p = proto;
  8307. p.addListener = p.listen = p.bind = p.on;
  8308. p.unlisten = p.unbind = p.off = p.removeListener;
  8309. p.trigger = p.emit;
  8310. // this is just a wrapper alias of .on()
  8311. p.pon = p.promiseOn = function (events, selector) {
  8312. var self = this;
  8313. var args = Array.prototype.slice.call(arguments, 0);
  8314. return new Promise$1(function (resolve, reject) {
  8315. var callback = function callback(e) {
  8316. self.off.apply(self, offArgs);
  8317. resolve(e);
  8318. };
  8319. var onArgs = args.concat([callback]);
  8320. var offArgs = onArgs.concat([]);
  8321. self.on.apply(self, onArgs);
  8322. });
  8323. };
  8324. }
  8325. }; // define
  8326. // use this module to cherry pick functions into your prototype
  8327. // (useful for functions shared between the core and collections, for example)
  8328. var define = {};
  8329. [define$3, define$2, define$1].forEach(function (m) {
  8330. extend(define, m);
  8331. });
  8332. var elesfn$i = {
  8333. animate: define.animate(),
  8334. animation: define.animation(),
  8335. animated: define.animated(),
  8336. clearQueue: define.clearQueue(),
  8337. delay: define.delay(),
  8338. delayAnimation: define.delayAnimation(),
  8339. stop: define.stop()
  8340. };
  8341. var elesfn$h = {
  8342. classes: function classes(_classes) {
  8343. var self = this;
  8344. if (_classes === undefined) {
  8345. var ret = [];
  8346. self[0]._private.classes.forEach(function (cls) {
  8347. return ret.push(cls);
  8348. });
  8349. return ret;
  8350. } else if (!array(_classes)) {
  8351. // extract classes from string
  8352. _classes = (_classes || '').match(/\S+/g) || [];
  8353. }
  8354. var changed = [];
  8355. var classesSet = new Set$1(_classes);
  8356. // check and update each ele
  8357. for (var j = 0; j < self.length; j++) {
  8358. var ele = self[j];
  8359. var _p = ele._private;
  8360. var eleClasses = _p.classes;
  8361. var changedEle = false;
  8362. // check if ele has all of the passed classes
  8363. for (var i = 0; i < _classes.length; i++) {
  8364. var cls = _classes[i];
  8365. var eleHasClass = eleClasses.has(cls);
  8366. if (!eleHasClass) {
  8367. changedEle = true;
  8368. break;
  8369. }
  8370. }
  8371. // check if ele has classes outside of those passed
  8372. if (!changedEle) {
  8373. changedEle = eleClasses.size !== _classes.length;
  8374. }
  8375. if (changedEle) {
  8376. _p.classes = classesSet;
  8377. changed.push(ele);
  8378. }
  8379. }
  8380. // trigger update style on those eles that had class changes
  8381. if (changed.length > 0) {
  8382. this.spawn(changed).updateStyle().emit('class');
  8383. }
  8384. return self;
  8385. },
  8386. addClass: function addClass(classes) {
  8387. return this.toggleClass(classes, true);
  8388. },
  8389. hasClass: function hasClass(className) {
  8390. var ele = this[0];
  8391. return ele != null && ele._private.classes.has(className);
  8392. },
  8393. toggleClass: function toggleClass(classes, toggle) {
  8394. if (!array(classes)) {
  8395. // extract classes from string
  8396. classes = classes.match(/\S+/g) || [];
  8397. }
  8398. var self = this;
  8399. var toggleUndefd = toggle === undefined;
  8400. var changed = []; // eles who had classes changed
  8401. for (var i = 0, il = self.length; i < il; i++) {
  8402. var ele = self[i];
  8403. var eleClasses = ele._private.classes;
  8404. var changedEle = false;
  8405. for (var j = 0; j < classes.length; j++) {
  8406. var cls = classes[j];
  8407. var hasClass = eleClasses.has(cls);
  8408. var changedNow = false;
  8409. if (toggle || toggleUndefd && !hasClass) {
  8410. eleClasses.add(cls);
  8411. changedNow = true;
  8412. } else if (!toggle || toggleUndefd && hasClass) {
  8413. eleClasses["delete"](cls);
  8414. changedNow = true;
  8415. }
  8416. if (!changedEle && changedNow) {
  8417. changed.push(ele);
  8418. changedEle = true;
  8419. }
  8420. } // for j classes
  8421. } // for i eles
  8422. // trigger update style on those eles that had class changes
  8423. if (changed.length > 0) {
  8424. this.spawn(changed).updateStyle().emit('class');
  8425. }
  8426. return self;
  8427. },
  8428. removeClass: function removeClass(classes) {
  8429. return this.toggleClass(classes, false);
  8430. },
  8431. flashClass: function flashClass(classes, duration) {
  8432. var self = this;
  8433. if (duration == null) {
  8434. duration = 250;
  8435. } else if (duration === 0) {
  8436. return self; // nothing to do really
  8437. }
  8438. self.addClass(classes);
  8439. setTimeout(function () {
  8440. self.removeClass(classes);
  8441. }, duration);
  8442. return self;
  8443. }
  8444. };
  8445. elesfn$h.className = elesfn$h.classNames = elesfn$h.classes;
  8446. // tokens in the query language
  8447. var tokens = {
  8448. metaChar: '[\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]',
  8449. // chars we need to escape in let names, etc
  8450. comparatorOp: '=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=',
  8451. // binary comparison op (used in data selectors)
  8452. boolOp: '\\?|\\!|\\^',
  8453. // boolean (unary) operators (used in data selectors)
  8454. string: '"(?:\\\\"|[^"])*"' + '|' + "'(?:\\\\'|[^'])*'",
  8455. // string literals (used in data selectors) -- doublequotes | singlequotes
  8456. number: number,
  8457. // number literal (used in data selectors) --- e.g. 0.1234, 1234, 12e123
  8458. meta: 'degree|indegree|outdegree',
  8459. // allowed metadata fields (i.e. allowed functions to use from Collection)
  8460. separator: '\\s*,\\s*',
  8461. // queries are separated by commas, e.g. edge[foo = 'bar'], node.someClass
  8462. descendant: '\\s+',
  8463. child: '\\s+>\\s+',
  8464. subject: '\\$',
  8465. group: 'node|edge|\\*',
  8466. directedEdge: '\\s+->\\s+',
  8467. undirectedEdge: '\\s+<->\\s+'
  8468. };
  8469. tokens.variable = '(?:[\\w-.]|(?:\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods
  8470. tokens.className = '(?:[\\w-]|(?:\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name
  8471. tokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number
  8472. tokens.id = tokens.variable; // an element id (follows variable conventions)
  8473. (function () {
  8474. var ops, op, i;
  8475. // add @ variants to comparatorOp
  8476. ops = tokens.comparatorOp.split('|');
  8477. for (i = 0; i < ops.length; i++) {
  8478. op = ops[i];
  8479. tokens.comparatorOp += '|@' + op;
  8480. }
  8481. // add ! variants to comparatorOp
  8482. ops = tokens.comparatorOp.split('|');
  8483. for (i = 0; i < ops.length; i++) {
  8484. op = ops[i];
  8485. if (op.indexOf('!') >= 0) {
  8486. continue;
  8487. } // skip ops that explicitly contain !
  8488. if (op === '=') {
  8489. continue;
  8490. } // skip = b/c != is explicitly defined
  8491. tokens.comparatorOp += '|\\!' + op;
  8492. }
  8493. })();
  8494. /**
  8495. * Make a new query object
  8496. *
  8497. * @prop type {Type} The type enum (int) of the query
  8498. * @prop checks List of checks to make against an ele to test for a match
  8499. */
  8500. var newQuery = function newQuery() {
  8501. return {
  8502. checks: []
  8503. };
  8504. };
  8505. /**
  8506. * A check type enum-like object. Uses integer values for fast match() lookup.
  8507. * The ordering does not matter as long as the ints are unique.
  8508. */
  8509. var Type = {
  8510. /** E.g. node */
  8511. GROUP: 0,
  8512. /** A collection of elements */
  8513. COLLECTION: 1,
  8514. /** A filter(ele) function */
  8515. FILTER: 2,
  8516. /** E.g. [foo > 1] */
  8517. DATA_COMPARE: 3,
  8518. /** E.g. [foo] */
  8519. DATA_EXIST: 4,
  8520. /** E.g. [?foo] */
  8521. DATA_BOOL: 5,
  8522. /** E.g. [[degree > 2]] */
  8523. META_COMPARE: 6,
  8524. /** E.g. :selected */
  8525. STATE: 7,
  8526. /** E.g. #foo */
  8527. ID: 8,
  8528. /** E.g. .foo */
  8529. CLASS: 9,
  8530. /** E.g. #foo <-> #bar */
  8531. UNDIRECTED_EDGE: 10,
  8532. /** E.g. #foo -> #bar */
  8533. DIRECTED_EDGE: 11,
  8534. /** E.g. $#foo -> #bar */
  8535. NODE_SOURCE: 12,
  8536. /** E.g. #foo -> $#bar */
  8537. NODE_TARGET: 13,
  8538. /** E.g. $#foo <-> #bar */
  8539. NODE_NEIGHBOR: 14,
  8540. /** E.g. #foo > #bar */
  8541. CHILD: 15,
  8542. /** E.g. #foo #bar */
  8543. DESCENDANT: 16,
  8544. /** E.g. $#foo > #bar */
  8545. PARENT: 17,
  8546. /** E.g. $#foo #bar */
  8547. ANCESTOR: 18,
  8548. /** E.g. #foo > $bar > #baz */
  8549. COMPOUND_SPLIT: 19,
  8550. /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */
  8551. TRUE: 20
  8552. };
  8553. var stateSelectors = [{
  8554. selector: ':selected',
  8555. matches: function matches(ele) {
  8556. return ele.selected();
  8557. }
  8558. }, {
  8559. selector: ':unselected',
  8560. matches: function matches(ele) {
  8561. return !ele.selected();
  8562. }
  8563. }, {
  8564. selector: ':selectable',
  8565. matches: function matches(ele) {
  8566. return ele.selectable();
  8567. }
  8568. }, {
  8569. selector: ':unselectable',
  8570. matches: function matches(ele) {
  8571. return !ele.selectable();
  8572. }
  8573. }, {
  8574. selector: ':locked',
  8575. matches: function matches(ele) {
  8576. return ele.locked();
  8577. }
  8578. }, {
  8579. selector: ':unlocked',
  8580. matches: function matches(ele) {
  8581. return !ele.locked();
  8582. }
  8583. }, {
  8584. selector: ':visible',
  8585. matches: function matches(ele) {
  8586. return ele.visible();
  8587. }
  8588. }, {
  8589. selector: ':hidden',
  8590. matches: function matches(ele) {
  8591. return !ele.visible();
  8592. }
  8593. }, {
  8594. selector: ':transparent',
  8595. matches: function matches(ele) {
  8596. return ele.transparent();
  8597. }
  8598. }, {
  8599. selector: ':grabbed',
  8600. matches: function matches(ele) {
  8601. return ele.grabbed();
  8602. }
  8603. }, {
  8604. selector: ':free',
  8605. matches: function matches(ele) {
  8606. return !ele.grabbed();
  8607. }
  8608. }, {
  8609. selector: ':removed',
  8610. matches: function matches(ele) {
  8611. return ele.removed();
  8612. }
  8613. }, {
  8614. selector: ':inside',
  8615. matches: function matches(ele) {
  8616. return !ele.removed();
  8617. }
  8618. }, {
  8619. selector: ':grabbable',
  8620. matches: function matches(ele) {
  8621. return ele.grabbable();
  8622. }
  8623. }, {
  8624. selector: ':ungrabbable',
  8625. matches: function matches(ele) {
  8626. return !ele.grabbable();
  8627. }
  8628. }, {
  8629. selector: ':animated',
  8630. matches: function matches(ele) {
  8631. return ele.animated();
  8632. }
  8633. }, {
  8634. selector: ':unanimated',
  8635. matches: function matches(ele) {
  8636. return !ele.animated();
  8637. }
  8638. }, {
  8639. selector: ':parent',
  8640. matches: function matches(ele) {
  8641. return ele.isParent();
  8642. }
  8643. }, {
  8644. selector: ':childless',
  8645. matches: function matches(ele) {
  8646. return ele.isChildless();
  8647. }
  8648. }, {
  8649. selector: ':child',
  8650. matches: function matches(ele) {
  8651. return ele.isChild();
  8652. }
  8653. }, {
  8654. selector: ':orphan',
  8655. matches: function matches(ele) {
  8656. return ele.isOrphan();
  8657. }
  8658. }, {
  8659. selector: ':nonorphan',
  8660. matches: function matches(ele) {
  8661. return ele.isChild();
  8662. }
  8663. }, {
  8664. selector: ':compound',
  8665. matches: function matches(ele) {
  8666. if (ele.isNode()) {
  8667. return ele.isParent();
  8668. } else {
  8669. return ele.source().isParent() || ele.target().isParent();
  8670. }
  8671. }
  8672. }, {
  8673. selector: ':loop',
  8674. matches: function matches(ele) {
  8675. return ele.isLoop();
  8676. }
  8677. }, {
  8678. selector: ':simple',
  8679. matches: function matches(ele) {
  8680. return ele.isSimple();
  8681. }
  8682. }, {
  8683. selector: ':active',
  8684. matches: function matches(ele) {
  8685. return ele.active();
  8686. }
  8687. }, {
  8688. selector: ':inactive',
  8689. matches: function matches(ele) {
  8690. return !ele.active();
  8691. }
  8692. }, {
  8693. selector: ':backgrounding',
  8694. matches: function matches(ele) {
  8695. return ele.backgrounding();
  8696. }
  8697. }, {
  8698. selector: ':nonbackgrounding',
  8699. matches: function matches(ele) {
  8700. return !ele.backgrounding();
  8701. }
  8702. }].sort(function (a, b) {
  8703. // n.b. selectors that are starting substrings of others must have the longer ones first
  8704. return descending(a.selector, b.selector);
  8705. });
  8706. var lookup = function () {
  8707. var selToFn = {};
  8708. var s;
  8709. for (var i = 0; i < stateSelectors.length; i++) {
  8710. s = stateSelectors[i];
  8711. selToFn[s.selector] = s.matches;
  8712. }
  8713. return selToFn;
  8714. }();
  8715. var stateSelectorMatches = function stateSelectorMatches(sel, ele) {
  8716. return lookup[sel](ele);
  8717. };
  8718. var stateSelectorRegex = '(' + stateSelectors.map(function (s) {
  8719. return s.selector;
  8720. }).join('|') + ')';
  8721. // when a token like a variable has escaped meta characters, we need to clean the backslashes out
  8722. // so that values get compared properly in Selector.filter()
  8723. var cleanMetaChars = function cleanMetaChars(str) {
  8724. return str.replace(new RegExp('\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {
  8725. return $1;
  8726. });
  8727. };
  8728. var replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {
  8729. selector[selector.length - 1] = replacementQuery;
  8730. };
  8731. // NOTE: add new expression syntax here to have it recognised by the parser;
  8732. // - a query contains all adjacent (i.e. no separator in between) expressions;
  8733. // - the current query is stored in selector[i]
  8734. // - you need to check the query objects in match() for it actually filter properly, but that's pretty straight forward
  8735. var exprs = [{
  8736. name: 'group',
  8737. // just used for identifying when debugging
  8738. query: true,
  8739. regex: '(' + tokens.group + ')',
  8740. populate: function populate(selector, query, _ref) {
  8741. var _ref2 = _slicedToArray(_ref, 1),
  8742. group = _ref2[0];
  8743. query.checks.push({
  8744. type: Type.GROUP,
  8745. value: group === '*' ? group : group + 's'
  8746. });
  8747. }
  8748. }, {
  8749. name: 'state',
  8750. query: true,
  8751. regex: stateSelectorRegex,
  8752. populate: function populate(selector, query, _ref3) {
  8753. var _ref4 = _slicedToArray(_ref3, 1),
  8754. state = _ref4[0];
  8755. query.checks.push({
  8756. type: Type.STATE,
  8757. value: state
  8758. });
  8759. }
  8760. }, {
  8761. name: 'id',
  8762. query: true,
  8763. regex: '\\#(' + tokens.id + ')',
  8764. populate: function populate(selector, query, _ref5) {
  8765. var _ref6 = _slicedToArray(_ref5, 1),
  8766. id = _ref6[0];
  8767. query.checks.push({
  8768. type: Type.ID,
  8769. value: cleanMetaChars(id)
  8770. });
  8771. }
  8772. }, {
  8773. name: 'className',
  8774. query: true,
  8775. regex: '\\.(' + tokens.className + ')',
  8776. populate: function populate(selector, query, _ref7) {
  8777. var _ref8 = _slicedToArray(_ref7, 1),
  8778. className = _ref8[0];
  8779. query.checks.push({
  8780. type: Type.CLASS,
  8781. value: cleanMetaChars(className)
  8782. });
  8783. }
  8784. }, {
  8785. name: 'dataExists',
  8786. query: true,
  8787. regex: '\\[\\s*(' + tokens.variable + ')\\s*\\]',
  8788. populate: function populate(selector, query, _ref9) {
  8789. var _ref10 = _slicedToArray(_ref9, 1),
  8790. variable = _ref10[0];
  8791. query.checks.push({
  8792. type: Type.DATA_EXIST,
  8793. field: cleanMetaChars(variable)
  8794. });
  8795. }
  8796. }, {
  8797. name: 'dataCompare',
  8798. query: true,
  8799. regex: '\\[\\s*(' + tokens.variable + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.value + ')\\s*\\]',
  8800. populate: function populate(selector, query, _ref11) {
  8801. var _ref12 = _slicedToArray(_ref11, 3),
  8802. variable = _ref12[0],
  8803. comparatorOp = _ref12[1],
  8804. value = _ref12[2];
  8805. var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;
  8806. if (valueIsString) {
  8807. value = value.substring(1, value.length - 1);
  8808. } else {
  8809. value = parseFloat(value);
  8810. }
  8811. query.checks.push({
  8812. type: Type.DATA_COMPARE,
  8813. field: cleanMetaChars(variable),
  8814. operator: comparatorOp,
  8815. value: value
  8816. });
  8817. }
  8818. }, {
  8819. name: 'dataBool',
  8820. query: true,
  8821. regex: '\\[\\s*(' + tokens.boolOp + ')\\s*(' + tokens.variable + ')\\s*\\]',
  8822. populate: function populate(selector, query, _ref13) {
  8823. var _ref14 = _slicedToArray(_ref13, 2),
  8824. boolOp = _ref14[0],
  8825. variable = _ref14[1];
  8826. query.checks.push({
  8827. type: Type.DATA_BOOL,
  8828. field: cleanMetaChars(variable),
  8829. operator: boolOp
  8830. });
  8831. }
  8832. }, {
  8833. name: 'metaCompare',
  8834. query: true,
  8835. regex: '\\[\\[\\s*(' + tokens.meta + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.number + ')\\s*\\]\\]',
  8836. populate: function populate(selector, query, _ref15) {
  8837. var _ref16 = _slicedToArray(_ref15, 3),
  8838. meta = _ref16[0],
  8839. comparatorOp = _ref16[1],
  8840. number = _ref16[2];
  8841. query.checks.push({
  8842. type: Type.META_COMPARE,
  8843. field: cleanMetaChars(meta),
  8844. operator: comparatorOp,
  8845. value: parseFloat(number)
  8846. });
  8847. }
  8848. }, {
  8849. name: 'nextQuery',
  8850. separator: true,
  8851. regex: tokens.separator,
  8852. populate: function populate(selector, query) {
  8853. var currentSubject = selector.currentSubject;
  8854. var edgeCount = selector.edgeCount;
  8855. var compoundCount = selector.compoundCount;
  8856. var lastQ = selector[selector.length - 1];
  8857. if (currentSubject != null) {
  8858. lastQ.subject = currentSubject;
  8859. selector.currentSubject = null;
  8860. }
  8861. lastQ.edgeCount = edgeCount;
  8862. lastQ.compoundCount = compoundCount;
  8863. selector.edgeCount = 0;
  8864. selector.compoundCount = 0;
  8865. // go on to next query
  8866. var nextQuery = selector[selector.length++] = newQuery();
  8867. return nextQuery; // this is the new query to be filled by the following exprs
  8868. }
  8869. }, {
  8870. name: 'directedEdge',
  8871. separator: true,
  8872. regex: tokens.directedEdge,
  8873. populate: function populate(selector, query) {
  8874. if (selector.currentSubject == null) {
  8875. // undirected edge
  8876. var edgeQuery = newQuery();
  8877. var source = query;
  8878. var target = newQuery();
  8879. edgeQuery.checks.push({
  8880. type: Type.DIRECTED_EDGE,
  8881. source: source,
  8882. target: target
  8883. });
  8884. // the query in the selector should be the edge rather than the source
  8885. replaceLastQuery(selector, query, edgeQuery);
  8886. selector.edgeCount++;
  8887. // we're now populating the target query with expressions that follow
  8888. return target;
  8889. } else {
  8890. // source/target
  8891. var srcTgtQ = newQuery();
  8892. var _source = query;
  8893. var _target = newQuery();
  8894. srcTgtQ.checks.push({
  8895. type: Type.NODE_SOURCE,
  8896. source: _source,
  8897. target: _target
  8898. });
  8899. // the query in the selector should be the neighbourhood rather than the node
  8900. replaceLastQuery(selector, query, srcTgtQ);
  8901. selector.edgeCount++;
  8902. return _target; // now populating the target with the following expressions
  8903. }
  8904. }
  8905. }, {
  8906. name: 'undirectedEdge',
  8907. separator: true,
  8908. regex: tokens.undirectedEdge,
  8909. populate: function populate(selector, query) {
  8910. if (selector.currentSubject == null) {
  8911. // undirected edge
  8912. var edgeQuery = newQuery();
  8913. var source = query;
  8914. var target = newQuery();
  8915. edgeQuery.checks.push({
  8916. type: Type.UNDIRECTED_EDGE,
  8917. nodes: [source, target]
  8918. });
  8919. // the query in the selector should be the edge rather than the source
  8920. replaceLastQuery(selector, query, edgeQuery);
  8921. selector.edgeCount++;
  8922. // we're now populating the target query with expressions that follow
  8923. return target;
  8924. } else {
  8925. // neighbourhood
  8926. var nhoodQ = newQuery();
  8927. var node = query;
  8928. var neighbor = newQuery();
  8929. nhoodQ.checks.push({
  8930. type: Type.NODE_NEIGHBOR,
  8931. node: node,
  8932. neighbor: neighbor
  8933. });
  8934. // the query in the selector should be the neighbourhood rather than the node
  8935. replaceLastQuery(selector, query, nhoodQ);
  8936. return neighbor; // now populating the neighbor with following expressions
  8937. }
  8938. }
  8939. }, {
  8940. name: 'child',
  8941. separator: true,
  8942. regex: tokens.child,
  8943. populate: function populate(selector, query) {
  8944. if (selector.currentSubject == null) {
  8945. // default: child query
  8946. var parentChildQuery = newQuery();
  8947. var child = newQuery();
  8948. var parent = selector[selector.length - 1];
  8949. parentChildQuery.checks.push({
  8950. type: Type.CHILD,
  8951. parent: parent,
  8952. child: child
  8953. });
  8954. // the query in the selector should be the '>' itself
  8955. replaceLastQuery(selector, query, parentChildQuery);
  8956. selector.compoundCount++;
  8957. // we're now populating the child query with expressions that follow
  8958. return child;
  8959. } else if (selector.currentSubject === query) {
  8960. // compound split query
  8961. var compound = newQuery();
  8962. var left = selector[selector.length - 1];
  8963. var right = newQuery();
  8964. var subject = newQuery();
  8965. var _child = newQuery();
  8966. var _parent = newQuery();
  8967. // set up the root compound q
  8968. compound.checks.push({
  8969. type: Type.COMPOUND_SPLIT,
  8970. left: left,
  8971. right: right,
  8972. subject: subject
  8973. });
  8974. // populate the subject and replace the q at the old spot (within left) with TRUE
  8975. subject.checks = query.checks; // take the checks from the left
  8976. query.checks = [{
  8977. type: Type.TRUE
  8978. }]; // checks under left refs the subject implicitly
  8979. // set up the right q
  8980. _parent.checks.push({
  8981. type: Type.TRUE
  8982. }); // parent implicitly refs the subject
  8983. right.checks.push({
  8984. type: Type.PARENT,
  8985. // type is swapped on right side queries
  8986. parent: _parent,
  8987. child: _child // empty for now
  8988. });
  8989. replaceLastQuery(selector, left, compound);
  8990. // update the ref since we moved things around for `query`
  8991. selector.currentSubject = subject;
  8992. selector.compoundCount++;
  8993. return _child; // now populating the right side's child
  8994. } else {
  8995. // parent query
  8996. // info for parent query
  8997. var _parent2 = newQuery();
  8998. var _child2 = newQuery();
  8999. var pcQChecks = [{
  9000. type: Type.PARENT,
  9001. parent: _parent2,
  9002. child: _child2
  9003. }];
  9004. // the parent-child query takes the place of the query previously being populated
  9005. _parent2.checks = query.checks; // the previous query contains the checks for the parent
  9006. query.checks = pcQChecks; // pc query takes over
  9007. selector.compoundCount++;
  9008. return _child2; // we're now populating the child
  9009. }
  9010. }
  9011. }, {
  9012. name: 'descendant',
  9013. separator: true,
  9014. regex: tokens.descendant,
  9015. populate: function populate(selector, query) {
  9016. if (selector.currentSubject == null) {
  9017. // default: descendant query
  9018. var ancChQuery = newQuery();
  9019. var descendant = newQuery();
  9020. var ancestor = selector[selector.length - 1];
  9021. ancChQuery.checks.push({
  9022. type: Type.DESCENDANT,
  9023. ancestor: ancestor,
  9024. descendant: descendant
  9025. });
  9026. // the query in the selector should be the '>' itself
  9027. replaceLastQuery(selector, query, ancChQuery);
  9028. selector.compoundCount++;
  9029. // we're now populating the descendant query with expressions that follow
  9030. return descendant;
  9031. } else if (selector.currentSubject === query) {
  9032. // compound split query
  9033. var compound = newQuery();
  9034. var left = selector[selector.length - 1];
  9035. var right = newQuery();
  9036. var subject = newQuery();
  9037. var _descendant = newQuery();
  9038. var _ancestor = newQuery();
  9039. // set up the root compound q
  9040. compound.checks.push({
  9041. type: Type.COMPOUND_SPLIT,
  9042. left: left,
  9043. right: right,
  9044. subject: subject
  9045. });
  9046. // populate the subject and replace the q at the old spot (within left) with TRUE
  9047. subject.checks = query.checks; // take the checks from the left
  9048. query.checks = [{
  9049. type: Type.TRUE
  9050. }]; // checks under left refs the subject implicitly
  9051. // set up the right q
  9052. _ancestor.checks.push({
  9053. type: Type.TRUE
  9054. }); // ancestor implicitly refs the subject
  9055. right.checks.push({
  9056. type: Type.ANCESTOR,
  9057. // type is swapped on right side queries
  9058. ancestor: _ancestor,
  9059. descendant: _descendant // empty for now
  9060. });
  9061. replaceLastQuery(selector, left, compound);
  9062. // update the ref since we moved things around for `query`
  9063. selector.currentSubject = subject;
  9064. selector.compoundCount++;
  9065. return _descendant; // now populating the right side's descendant
  9066. } else {
  9067. // ancestor query
  9068. // info for parent query
  9069. var _ancestor2 = newQuery();
  9070. var _descendant2 = newQuery();
  9071. var adQChecks = [{
  9072. type: Type.ANCESTOR,
  9073. ancestor: _ancestor2,
  9074. descendant: _descendant2
  9075. }];
  9076. // the parent-child query takes the place of the query previously being populated
  9077. _ancestor2.checks = query.checks; // the previous query contains the checks for the parent
  9078. query.checks = adQChecks; // pc query takes over
  9079. selector.compoundCount++;
  9080. return _descendant2; // we're now populating the child
  9081. }
  9082. }
  9083. }, {
  9084. name: 'subject',
  9085. modifier: true,
  9086. regex: tokens.subject,
  9087. populate: function populate(selector, query) {
  9088. if (selector.currentSubject != null && selector.currentSubject !== query) {
  9089. warn('Redefinition of subject in selector `' + selector.toString() + '`');
  9090. return false;
  9091. }
  9092. selector.currentSubject = query;
  9093. var topQ = selector[selector.length - 1];
  9094. var topChk = topQ.checks[0];
  9095. var topType = topChk == null ? null : topChk.type;
  9096. if (topType === Type.DIRECTED_EDGE) {
  9097. // directed edge with subject on the target
  9098. // change to target node check
  9099. topChk.type = Type.NODE_TARGET;
  9100. } else if (topType === Type.UNDIRECTED_EDGE) {
  9101. // undirected edge with subject on the second node
  9102. // change to neighbor check
  9103. topChk.type = Type.NODE_NEIGHBOR;
  9104. topChk.node = topChk.nodes[1]; // second node is subject
  9105. topChk.neighbor = topChk.nodes[0];
  9106. // clean up unused fields for new type
  9107. topChk.nodes = null;
  9108. }
  9109. }
  9110. }];
  9111. exprs.forEach(function (e) {
  9112. return e.regexObj = new RegExp('^' + e.regex);
  9113. });
  9114. /**
  9115. * Of all the expressions, find the first match in the remaining text.
  9116. * @param {string} remaining The remaining text to parse
  9117. * @returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`
  9118. */
  9119. var consumeExpr = function consumeExpr(remaining) {
  9120. var expr;
  9121. var match;
  9122. var name;
  9123. for (var j = 0; j < exprs.length; j++) {
  9124. var e = exprs[j];
  9125. var n = e.name;
  9126. var m = remaining.match(e.regexObj);
  9127. if (m != null) {
  9128. match = m;
  9129. expr = e;
  9130. name = n;
  9131. var consumed = m[0];
  9132. remaining = remaining.substring(consumed.length);
  9133. break; // we've consumed one expr, so we can return now
  9134. }
  9135. }
  9136. return {
  9137. expr: expr,
  9138. match: match,
  9139. name: name,
  9140. remaining: remaining
  9141. };
  9142. };
  9143. /**
  9144. * Consume all the leading whitespace
  9145. * @param {string} remaining The text to consume
  9146. * @returns The text with the leading whitespace removed
  9147. */
  9148. var consumeWhitespace = function consumeWhitespace(remaining) {
  9149. var match = remaining.match(/^\s+/);
  9150. if (match) {
  9151. var consumed = match[0];
  9152. remaining = remaining.substring(consumed.length);
  9153. }
  9154. return remaining;
  9155. };
  9156. /**
  9157. * Parse the string and store the parsed representation in the Selector.
  9158. * @param {string} selector The selector string
  9159. * @returns `true` if the selector was successfully parsed, `false` otherwise
  9160. */
  9161. var parse = function parse(selector) {
  9162. var self = this;
  9163. var remaining = self.inputText = selector;
  9164. var currentQuery = self[0] = newQuery();
  9165. self.length = 1;
  9166. remaining = consumeWhitespace(remaining); // get rid of leading whitespace
  9167. for (;;) {
  9168. var exprInfo = consumeExpr(remaining);
  9169. if (exprInfo.expr == null) {
  9170. warn('The selector `' + selector + '`is invalid');
  9171. return false;
  9172. } else {
  9173. var args = exprInfo.match.slice(1);
  9174. // let the token populate the selector object in currentQuery
  9175. var ret = exprInfo.expr.populate(self, currentQuery, args);
  9176. if (ret === false) {
  9177. return false; // exit if population failed
  9178. } else if (ret != null) {
  9179. currentQuery = ret; // change the current query to be filled if the expr specifies
  9180. }
  9181. }
  9182. remaining = exprInfo.remaining;
  9183. // we're done when there's nothing left to parse
  9184. if (remaining.match(/^\s*$/)) {
  9185. break;
  9186. }
  9187. }
  9188. var lastQ = self[self.length - 1];
  9189. if (self.currentSubject != null) {
  9190. lastQ.subject = self.currentSubject;
  9191. }
  9192. lastQ.edgeCount = self.edgeCount;
  9193. lastQ.compoundCount = self.compoundCount;
  9194. for (var i = 0; i < self.length; i++) {
  9195. var q = self[i];
  9196. // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations
  9197. if (q.compoundCount > 0 && q.edgeCount > 0) {
  9198. warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');
  9199. return false;
  9200. }
  9201. if (q.edgeCount > 1) {
  9202. warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');
  9203. return false;
  9204. } else if (q.edgeCount === 1) {
  9205. warn('The selector `' + selector + '` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.');
  9206. }
  9207. }
  9208. return true; // success
  9209. };
  9210. /**
  9211. * Get the selector represented as a string. This value uses default formatting,
  9212. * so things like spacing may differ from the input text passed to the constructor.
  9213. * @returns {string} The selector string
  9214. */
  9215. var toString = function toString() {
  9216. if (this.toStringCache != null) {
  9217. return this.toStringCache;
  9218. }
  9219. var clean = function clean(obj) {
  9220. if (obj == null) {
  9221. return '';
  9222. } else {
  9223. return obj;
  9224. }
  9225. };
  9226. var cleanVal = function cleanVal(val) {
  9227. if (string(val)) {
  9228. return '"' + val + '"';
  9229. } else {
  9230. return clean(val);
  9231. }
  9232. };
  9233. var space = function space(val) {
  9234. return ' ' + val + ' ';
  9235. };
  9236. var checkToString = function checkToString(check, subject) {
  9237. var type = check.type,
  9238. value = check.value;
  9239. switch (type) {
  9240. case Type.GROUP:
  9241. {
  9242. var group = clean(value);
  9243. return group.substring(0, group.length - 1);
  9244. }
  9245. case Type.DATA_COMPARE:
  9246. {
  9247. var field = check.field,
  9248. operator = check.operator;
  9249. return '[' + field + space(clean(operator)) + cleanVal(value) + ']';
  9250. }
  9251. case Type.DATA_BOOL:
  9252. {
  9253. var _operator = check.operator,
  9254. _field = check.field;
  9255. return '[' + clean(_operator) + _field + ']';
  9256. }
  9257. case Type.DATA_EXIST:
  9258. {
  9259. var _field2 = check.field;
  9260. return '[' + _field2 + ']';
  9261. }
  9262. case Type.META_COMPARE:
  9263. {
  9264. var _operator2 = check.operator,
  9265. _field3 = check.field;
  9266. return '[[' + _field3 + space(clean(_operator2)) + cleanVal(value) + ']]';
  9267. }
  9268. case Type.STATE:
  9269. {
  9270. return value;
  9271. }
  9272. case Type.ID:
  9273. {
  9274. return '#' + value;
  9275. }
  9276. case Type.CLASS:
  9277. {
  9278. return '.' + value;
  9279. }
  9280. case Type.PARENT:
  9281. case Type.CHILD:
  9282. {
  9283. return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);
  9284. }
  9285. case Type.ANCESTOR:
  9286. case Type.DESCENDANT:
  9287. {
  9288. return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);
  9289. }
  9290. case Type.COMPOUND_SPLIT:
  9291. {
  9292. var lhs = queryToString(check.left, subject);
  9293. var sub = queryToString(check.subject, subject);
  9294. var rhs = queryToString(check.right, subject);
  9295. return lhs + (lhs.length > 0 ? ' ' : '') + sub + rhs;
  9296. }
  9297. case Type.TRUE:
  9298. {
  9299. return '';
  9300. }
  9301. }
  9302. };
  9303. var queryToString = function queryToString(query, subject) {
  9304. return query.checks.reduce(function (str, chk, i) {
  9305. return str + (subject === query && i === 0 ? '$' : '') + checkToString(chk, subject);
  9306. }, '');
  9307. };
  9308. var str = '';
  9309. for (var i = 0; i < this.length; i++) {
  9310. var query = this[i];
  9311. str += queryToString(query, query.subject);
  9312. if (this.length > 1 && i < this.length - 1) {
  9313. str += ', ';
  9314. }
  9315. }
  9316. this.toStringCache = str;
  9317. return str;
  9318. };
  9319. var parse$1 = {
  9320. parse: parse,
  9321. toString: toString
  9322. };
  9323. var valCmp = function valCmp(fieldVal, operator, value) {
  9324. var matches;
  9325. var isFieldStr = string(fieldVal);
  9326. var isFieldNum = number$1(fieldVal);
  9327. var isValStr = string(value);
  9328. var fieldStr, valStr;
  9329. var caseInsensitive = false;
  9330. var notExpr = false;
  9331. var isIneqCmp = false;
  9332. if (operator.indexOf('!') >= 0) {
  9333. operator = operator.replace('!', '');
  9334. notExpr = true;
  9335. }
  9336. if (operator.indexOf('@') >= 0) {
  9337. operator = operator.replace('@', '');
  9338. caseInsensitive = true;
  9339. }
  9340. if (isFieldStr || isValStr || caseInsensitive) {
  9341. fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;
  9342. valStr = '' + value;
  9343. }
  9344. // if we're doing a case insensitive comparison, then we're using a STRING comparison
  9345. // even if we're comparing numbers
  9346. if (caseInsensitive) {
  9347. fieldVal = fieldStr = fieldStr.toLowerCase();
  9348. value = valStr = valStr.toLowerCase();
  9349. }
  9350. switch (operator) {
  9351. case '*=':
  9352. matches = fieldStr.indexOf(valStr) >= 0;
  9353. break;
  9354. case '$=':
  9355. matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;
  9356. break;
  9357. case '^=':
  9358. matches = fieldStr.indexOf(valStr) === 0;
  9359. break;
  9360. case '=':
  9361. matches = fieldVal === value;
  9362. break;
  9363. case '>':
  9364. isIneqCmp = true;
  9365. matches = fieldVal > value;
  9366. break;
  9367. case '>=':
  9368. isIneqCmp = true;
  9369. matches = fieldVal >= value;
  9370. break;
  9371. case '<':
  9372. isIneqCmp = true;
  9373. matches = fieldVal < value;
  9374. break;
  9375. case '<=':
  9376. isIneqCmp = true;
  9377. matches = fieldVal <= value;
  9378. break;
  9379. default:
  9380. matches = false;
  9381. break;
  9382. }
  9383. // apply the not op, but null vals for inequalities should always stay non-matching
  9384. if (notExpr && (fieldVal != null || !isIneqCmp)) {
  9385. matches = !matches;
  9386. }
  9387. return matches;
  9388. };
  9389. var boolCmp = function boolCmp(fieldVal, operator) {
  9390. switch (operator) {
  9391. case '?':
  9392. return fieldVal ? true : false;
  9393. case '!':
  9394. return fieldVal ? false : true;
  9395. case '^':
  9396. return fieldVal === undefined;
  9397. }
  9398. };
  9399. var existCmp = function existCmp(fieldVal) {
  9400. return fieldVal !== undefined;
  9401. };
  9402. var data$1 = function data(ele, field) {
  9403. return ele.data(field);
  9404. };
  9405. var meta = function meta(ele, field) {
  9406. return ele[field]();
  9407. };
  9408. /** A lookup of `match(check, ele)` functions by `Type` int */
  9409. var match = [];
  9410. /**
  9411. * Returns whether the query matches for the element
  9412. * @param query The `{ type, value, ... }` query object
  9413. * @param ele The element to compare against
  9414. */
  9415. var matches$1 = function matches(query, ele) {
  9416. return query.checks.every(function (chk) {
  9417. return match[chk.type](chk, ele);
  9418. });
  9419. };
  9420. match[Type.GROUP] = function (check, ele) {
  9421. var group = check.value;
  9422. return group === '*' || group === ele.group();
  9423. };
  9424. match[Type.STATE] = function (check, ele) {
  9425. var stateSelector = check.value;
  9426. return stateSelectorMatches(stateSelector, ele);
  9427. };
  9428. match[Type.ID] = function (check, ele) {
  9429. var id = check.value;
  9430. return ele.id() === id;
  9431. };
  9432. match[Type.CLASS] = function (check, ele) {
  9433. var cls = check.value;
  9434. return ele.hasClass(cls);
  9435. };
  9436. match[Type.META_COMPARE] = function (check, ele) {
  9437. var field = check.field,
  9438. operator = check.operator,
  9439. value = check.value;
  9440. return valCmp(meta(ele, field), operator, value);
  9441. };
  9442. match[Type.DATA_COMPARE] = function (check, ele) {
  9443. var field = check.field,
  9444. operator = check.operator,
  9445. value = check.value;
  9446. return valCmp(data$1(ele, field), operator, value);
  9447. };
  9448. match[Type.DATA_BOOL] = function (check, ele) {
  9449. var field = check.field,
  9450. operator = check.operator;
  9451. return boolCmp(data$1(ele, field), operator);
  9452. };
  9453. match[Type.DATA_EXIST] = function (check, ele) {
  9454. var field = check.field;
  9455. check.operator;
  9456. return existCmp(data$1(ele, field));
  9457. };
  9458. match[Type.UNDIRECTED_EDGE] = function (check, ele) {
  9459. var qA = check.nodes[0];
  9460. var qB = check.nodes[1];
  9461. var src = ele.source();
  9462. var tgt = ele.target();
  9463. return matches$1(qA, src) && matches$1(qB, tgt) || matches$1(qB, src) && matches$1(qA, tgt);
  9464. };
  9465. match[Type.NODE_NEIGHBOR] = function (check, ele) {
  9466. return matches$1(check.node, ele) && ele.neighborhood().some(function (n) {
  9467. return n.isNode() && matches$1(check.neighbor, n);
  9468. });
  9469. };
  9470. match[Type.DIRECTED_EDGE] = function (check, ele) {
  9471. return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());
  9472. };
  9473. match[Type.NODE_SOURCE] = function (check, ele) {
  9474. return matches$1(check.source, ele) && ele.outgoers().some(function (n) {
  9475. return n.isNode() && matches$1(check.target, n);
  9476. });
  9477. };
  9478. match[Type.NODE_TARGET] = function (check, ele) {
  9479. return matches$1(check.target, ele) && ele.incomers().some(function (n) {
  9480. return n.isNode() && matches$1(check.source, n);
  9481. });
  9482. };
  9483. match[Type.CHILD] = function (check, ele) {
  9484. return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());
  9485. };
  9486. match[Type.PARENT] = function (check, ele) {
  9487. return matches$1(check.parent, ele) && ele.children().some(function (c) {
  9488. return matches$1(check.child, c);
  9489. });
  9490. };
  9491. match[Type.DESCENDANT] = function (check, ele) {
  9492. return matches$1(check.descendant, ele) && ele.ancestors().some(function (a) {
  9493. return matches$1(check.ancestor, a);
  9494. });
  9495. };
  9496. match[Type.ANCESTOR] = function (check, ele) {
  9497. return matches$1(check.ancestor, ele) && ele.descendants().some(function (d) {
  9498. return matches$1(check.descendant, d);
  9499. });
  9500. };
  9501. match[Type.COMPOUND_SPLIT] = function (check, ele) {
  9502. return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);
  9503. };
  9504. match[Type.TRUE] = function () {
  9505. return true;
  9506. };
  9507. match[Type.COLLECTION] = function (check, ele) {
  9508. var collection = check.value;
  9509. return collection.has(ele);
  9510. };
  9511. match[Type.FILTER] = function (check, ele) {
  9512. var filter = check.value;
  9513. return filter(ele);
  9514. };
  9515. // filter an existing collection
  9516. var filter = function filter(collection) {
  9517. var self = this;
  9518. // for 1 id #foo queries, just get the element
  9519. if (self.length === 1 && self[0].checks.length === 1 && self[0].checks[0].type === Type.ID) {
  9520. return collection.getElementById(self[0].checks[0].value).collection();
  9521. }
  9522. var selectorFunction = function selectorFunction(element) {
  9523. for (var j = 0; j < self.length; j++) {
  9524. var query = self[j];
  9525. if (matches$1(query, element)) {
  9526. return true;
  9527. }
  9528. }
  9529. return false;
  9530. };
  9531. if (self.text() == null) {
  9532. selectorFunction = function selectorFunction() {
  9533. return true;
  9534. };
  9535. }
  9536. return collection.filter(selectorFunction);
  9537. }; // filter
  9538. // does selector match a single element?
  9539. var matches = function matches(ele) {
  9540. var self = this;
  9541. for (var j = 0; j < self.length; j++) {
  9542. var query = self[j];
  9543. if (matches$1(query, ele)) {
  9544. return true;
  9545. }
  9546. }
  9547. return false;
  9548. }; // matches
  9549. var matching = {
  9550. matches: matches,
  9551. filter: filter
  9552. };
  9553. var Selector = function Selector(selector) {
  9554. this.inputText = selector;
  9555. this.currentSubject = null;
  9556. this.compoundCount = 0;
  9557. this.edgeCount = 0;
  9558. this.length = 0;
  9559. if (selector == null || string(selector) && selector.match(/^\s*$/)) ; else if (elementOrCollection(selector)) {
  9560. this.addQuery({
  9561. checks: [{
  9562. type: Type.COLLECTION,
  9563. value: selector.collection()
  9564. }]
  9565. });
  9566. } else if (fn$6(selector)) {
  9567. this.addQuery({
  9568. checks: [{
  9569. type: Type.FILTER,
  9570. value: selector
  9571. }]
  9572. });
  9573. } else if (string(selector)) {
  9574. if (!this.parse(selector)) {
  9575. this.invalid = true;
  9576. }
  9577. } else {
  9578. error('A selector must be created from a string; found ');
  9579. }
  9580. };
  9581. var selfn = Selector.prototype;
  9582. [parse$1, matching].forEach(function (p) {
  9583. return extend(selfn, p);
  9584. });
  9585. selfn.text = function () {
  9586. return this.inputText;
  9587. };
  9588. selfn.size = function () {
  9589. return this.length;
  9590. };
  9591. selfn.eq = function (i) {
  9592. return this[i];
  9593. };
  9594. selfn.sameText = function (otherSel) {
  9595. return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();
  9596. };
  9597. selfn.addQuery = function (q) {
  9598. this[this.length++] = q;
  9599. };
  9600. selfn.selector = selfn.toString;
  9601. var elesfn$g = {
  9602. allAre: function allAre(selector) {
  9603. var selObj = new Selector(selector);
  9604. return this.every(function (ele) {
  9605. return selObj.matches(ele);
  9606. });
  9607. },
  9608. is: function is(selector) {
  9609. var selObj = new Selector(selector);
  9610. return this.some(function (ele) {
  9611. return selObj.matches(ele);
  9612. });
  9613. },
  9614. some: function some(fn, thisArg) {
  9615. for (var i = 0; i < this.length; i++) {
  9616. var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
  9617. if (ret) {
  9618. return true;
  9619. }
  9620. }
  9621. return false;
  9622. },
  9623. every: function every(fn, thisArg) {
  9624. for (var i = 0; i < this.length; i++) {
  9625. var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
  9626. if (!ret) {
  9627. return false;
  9628. }
  9629. }
  9630. return true;
  9631. },
  9632. same: function same(collection) {
  9633. // cheap collection ref check
  9634. if (this === collection) {
  9635. return true;
  9636. }
  9637. collection = this.cy().collection(collection);
  9638. var thisLength = this.length;
  9639. var collectionLength = collection.length;
  9640. // cheap length check
  9641. if (thisLength !== collectionLength) {
  9642. return false;
  9643. }
  9644. // cheap element ref check
  9645. if (thisLength === 1) {
  9646. return this[0] === collection[0];
  9647. }
  9648. return this.every(function (ele) {
  9649. return collection.hasElementWithId(ele.id());
  9650. });
  9651. },
  9652. anySame: function anySame(collection) {
  9653. collection = this.cy().collection(collection);
  9654. return this.some(function (ele) {
  9655. return collection.hasElementWithId(ele.id());
  9656. });
  9657. },
  9658. allAreNeighbors: function allAreNeighbors(collection) {
  9659. collection = this.cy().collection(collection);
  9660. var nhood = this.neighborhood();
  9661. return collection.every(function (ele) {
  9662. return nhood.hasElementWithId(ele.id());
  9663. });
  9664. },
  9665. contains: function contains(collection) {
  9666. collection = this.cy().collection(collection);
  9667. var self = this;
  9668. return collection.every(function (ele) {
  9669. return self.hasElementWithId(ele.id());
  9670. });
  9671. }
  9672. };
  9673. elesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;
  9674. elesfn$g.has = elesfn$g.contains;
  9675. elesfn$g.equal = elesfn$g.equals = elesfn$g.same;
  9676. var cache = function cache(fn, name) {
  9677. return function traversalCache(arg1, arg2, arg3, arg4) {
  9678. var selectorOrEles = arg1;
  9679. var eles = this;
  9680. var key;
  9681. if (selectorOrEles == null) {
  9682. key = '';
  9683. } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {
  9684. key = selectorOrEles.id();
  9685. }
  9686. if (eles.length === 1 && key) {
  9687. var _p = eles[0]._private;
  9688. var tch = _p.traversalCache = _p.traversalCache || {};
  9689. var ch = tch[name] = tch[name] || [];
  9690. var hash = hashString(key);
  9691. var cacheHit = ch[hash];
  9692. if (cacheHit) {
  9693. return cacheHit;
  9694. } else {
  9695. return ch[hash] = fn.call(eles, arg1, arg2, arg3, arg4);
  9696. }
  9697. } else {
  9698. return fn.call(eles, arg1, arg2, arg3, arg4);
  9699. }
  9700. };
  9701. };
  9702. var elesfn$f = {
  9703. parent: function parent(selector) {
  9704. var parents = [];
  9705. // optimisation for single ele call
  9706. if (this.length === 1) {
  9707. var parent = this[0]._private.parent;
  9708. if (parent) {
  9709. return parent;
  9710. }
  9711. }
  9712. for (var i = 0; i < this.length; i++) {
  9713. var ele = this[i];
  9714. var _parent = ele._private.parent;
  9715. if (_parent) {
  9716. parents.push(_parent);
  9717. }
  9718. }
  9719. return this.spawn(parents, true).filter(selector);
  9720. },
  9721. parents: function parents(selector) {
  9722. var parents = [];
  9723. var eles = this.parent();
  9724. while (eles.nonempty()) {
  9725. for (var i = 0; i < eles.length; i++) {
  9726. var ele = eles[i];
  9727. parents.push(ele);
  9728. }
  9729. eles = eles.parent();
  9730. }
  9731. return this.spawn(parents, true).filter(selector);
  9732. },
  9733. commonAncestors: function commonAncestors(selector) {
  9734. var ancestors;
  9735. for (var i = 0; i < this.length; i++) {
  9736. var ele = this[i];
  9737. var parents = ele.parents();
  9738. ancestors = ancestors || parents;
  9739. ancestors = ancestors.intersect(parents); // current list must be common with current ele parents set
  9740. }
  9741. return ancestors.filter(selector);
  9742. },
  9743. orphans: function orphans(selector) {
  9744. return this.stdFilter(function (ele) {
  9745. return ele.isOrphan();
  9746. }).filter(selector);
  9747. },
  9748. nonorphans: function nonorphans(selector) {
  9749. return this.stdFilter(function (ele) {
  9750. return ele.isChild();
  9751. }).filter(selector);
  9752. },
  9753. children: cache(function (selector) {
  9754. var children = [];
  9755. for (var i = 0; i < this.length; i++) {
  9756. var ele = this[i];
  9757. var eleChildren = ele._private.children;
  9758. for (var j = 0; j < eleChildren.length; j++) {
  9759. children.push(eleChildren[j]);
  9760. }
  9761. }
  9762. return this.spawn(children, true).filter(selector);
  9763. }, 'children'),
  9764. siblings: function siblings(selector) {
  9765. return this.parent().children().not(this).filter(selector);
  9766. },
  9767. isParent: function isParent() {
  9768. var ele = this[0];
  9769. if (ele) {
  9770. return ele.isNode() && ele._private.children.length !== 0;
  9771. }
  9772. },
  9773. isChildless: function isChildless() {
  9774. var ele = this[0];
  9775. if (ele) {
  9776. return ele.isNode() && ele._private.children.length === 0;
  9777. }
  9778. },
  9779. isChild: function isChild() {
  9780. var ele = this[0];
  9781. if (ele) {
  9782. return ele.isNode() && ele._private.parent != null;
  9783. }
  9784. },
  9785. isOrphan: function isOrphan() {
  9786. var ele = this[0];
  9787. if (ele) {
  9788. return ele.isNode() && ele._private.parent == null;
  9789. }
  9790. },
  9791. descendants: function descendants(selector) {
  9792. var elements = [];
  9793. function add(eles) {
  9794. for (var i = 0; i < eles.length; i++) {
  9795. var ele = eles[i];
  9796. elements.push(ele);
  9797. if (ele.children().nonempty()) {
  9798. add(ele.children());
  9799. }
  9800. }
  9801. }
  9802. add(this.children());
  9803. return this.spawn(elements, true).filter(selector);
  9804. }
  9805. };
  9806. function forEachCompound(eles, fn, includeSelf, recursiveStep) {
  9807. var q = [];
  9808. var did = new Set$1();
  9809. var cy = eles.cy();
  9810. var hasCompounds = cy.hasCompoundNodes();
  9811. for (var i = 0; i < eles.length; i++) {
  9812. var ele = eles[i];
  9813. if (includeSelf) {
  9814. q.push(ele);
  9815. } else if (hasCompounds) {
  9816. recursiveStep(q, did, ele);
  9817. }
  9818. }
  9819. while (q.length > 0) {
  9820. var _ele = q.shift();
  9821. fn(_ele);
  9822. did.add(_ele.id());
  9823. if (hasCompounds) {
  9824. recursiveStep(q, did, _ele);
  9825. }
  9826. }
  9827. return eles;
  9828. }
  9829. function addChildren(q, did, ele) {
  9830. if (ele.isParent()) {
  9831. var children = ele._private.children;
  9832. for (var i = 0; i < children.length; i++) {
  9833. var child = children[i];
  9834. if (!did.has(child.id())) {
  9835. q.push(child);
  9836. }
  9837. }
  9838. }
  9839. }
  9840. // very efficient version of eles.add( eles.descendants() ).forEach()
  9841. // for internal use
  9842. elesfn$f.forEachDown = function (fn) {
  9843. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9844. return forEachCompound(this, fn, includeSelf, addChildren);
  9845. };
  9846. function addParent(q, did, ele) {
  9847. if (ele.isChild()) {
  9848. var parent = ele._private.parent;
  9849. if (!did.has(parent.id())) {
  9850. q.push(parent);
  9851. }
  9852. }
  9853. }
  9854. elesfn$f.forEachUp = function (fn) {
  9855. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9856. return forEachCompound(this, fn, includeSelf, addParent);
  9857. };
  9858. function addParentAndChildren(q, did, ele) {
  9859. addParent(q, did, ele);
  9860. addChildren(q, did, ele);
  9861. }
  9862. elesfn$f.forEachUpAndDown = function (fn) {
  9863. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9864. return forEachCompound(this, fn, includeSelf, addParentAndChildren);
  9865. };
  9866. // aliases
  9867. elesfn$f.ancestors = elesfn$f.parents;
  9868. var fn$5, elesfn$e;
  9869. fn$5 = elesfn$e = {
  9870. data: define.data({
  9871. field: 'data',
  9872. bindingEvent: 'data',
  9873. allowBinding: true,
  9874. allowSetting: true,
  9875. settingEvent: 'data',
  9876. settingTriggersEvent: true,
  9877. triggerFnName: 'trigger',
  9878. allowGetting: true,
  9879. immutableKeys: {
  9880. 'id': true,
  9881. 'source': true,
  9882. 'target': true,
  9883. 'parent': true
  9884. },
  9885. updateStyle: true
  9886. }),
  9887. removeData: define.removeData({
  9888. field: 'data',
  9889. event: 'data',
  9890. triggerFnName: 'trigger',
  9891. triggerEvent: true,
  9892. immutableKeys: {
  9893. 'id': true,
  9894. 'source': true,
  9895. 'target': true,
  9896. 'parent': true
  9897. },
  9898. updateStyle: true
  9899. }),
  9900. scratch: define.data({
  9901. field: 'scratch',
  9902. bindingEvent: 'scratch',
  9903. allowBinding: true,
  9904. allowSetting: true,
  9905. settingEvent: 'scratch',
  9906. settingTriggersEvent: true,
  9907. triggerFnName: 'trigger',
  9908. allowGetting: true,
  9909. updateStyle: true
  9910. }),
  9911. removeScratch: define.removeData({
  9912. field: 'scratch',
  9913. event: 'scratch',
  9914. triggerFnName: 'trigger',
  9915. triggerEvent: true,
  9916. updateStyle: true
  9917. }),
  9918. rscratch: define.data({
  9919. field: 'rscratch',
  9920. allowBinding: false,
  9921. allowSetting: true,
  9922. settingTriggersEvent: false,
  9923. allowGetting: true
  9924. }),
  9925. removeRscratch: define.removeData({
  9926. field: 'rscratch',
  9927. triggerEvent: false
  9928. }),
  9929. id: function id() {
  9930. var ele = this[0];
  9931. if (ele) {
  9932. return ele._private.data.id;
  9933. }
  9934. }
  9935. };
  9936. // aliases
  9937. fn$5.attr = fn$5.data;
  9938. fn$5.removeAttr = fn$5.removeData;
  9939. var data = elesfn$e;
  9940. var elesfn$d = {};
  9941. function defineDegreeFunction(callback) {
  9942. return function (includeLoops) {
  9943. var self = this;
  9944. if (includeLoops === undefined) {
  9945. includeLoops = true;
  9946. }
  9947. if (self.length === 0) {
  9948. return;
  9949. }
  9950. if (self.isNode() && !self.removed()) {
  9951. var degree = 0;
  9952. var node = self[0];
  9953. var connectedEdges = node._private.edges;
  9954. for (var i = 0; i < connectedEdges.length; i++) {
  9955. var edge = connectedEdges[i];
  9956. if (!includeLoops && edge.isLoop()) {
  9957. continue;
  9958. }
  9959. degree += callback(node, edge);
  9960. }
  9961. return degree;
  9962. } else {
  9963. return;
  9964. }
  9965. };
  9966. }
  9967. extend(elesfn$d, {
  9968. degree: defineDegreeFunction(function (node, edge) {
  9969. if (edge.source().same(edge.target())) {
  9970. return 2;
  9971. } else {
  9972. return 1;
  9973. }
  9974. }),
  9975. indegree: defineDegreeFunction(function (node, edge) {
  9976. if (edge.target().same(node)) {
  9977. return 1;
  9978. } else {
  9979. return 0;
  9980. }
  9981. }),
  9982. outdegree: defineDegreeFunction(function (node, edge) {
  9983. if (edge.source().same(node)) {
  9984. return 1;
  9985. } else {
  9986. return 0;
  9987. }
  9988. })
  9989. });
  9990. function defineDegreeBoundsFunction(degreeFn, callback) {
  9991. return function (includeLoops) {
  9992. var ret;
  9993. var nodes = this.nodes();
  9994. for (var i = 0; i < nodes.length; i++) {
  9995. var ele = nodes[i];
  9996. var degree = ele[degreeFn](includeLoops);
  9997. if (degree !== undefined && (ret === undefined || callback(degree, ret))) {
  9998. ret = degree;
  9999. }
  10000. }
  10001. return ret;
  10002. };
  10003. }
  10004. extend(elesfn$d, {
  10005. minDegree: defineDegreeBoundsFunction('degree', function (degree, min) {
  10006. return degree < min;
  10007. }),
  10008. maxDegree: defineDegreeBoundsFunction('degree', function (degree, max) {
  10009. return degree > max;
  10010. }),
  10011. minIndegree: defineDegreeBoundsFunction('indegree', function (degree, min) {
  10012. return degree < min;
  10013. }),
  10014. maxIndegree: defineDegreeBoundsFunction('indegree', function (degree, max) {
  10015. return degree > max;
  10016. }),
  10017. minOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, min) {
  10018. return degree < min;
  10019. }),
  10020. maxOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, max) {
  10021. return degree > max;
  10022. })
  10023. });
  10024. extend(elesfn$d, {
  10025. totalDegree: function totalDegree(includeLoops) {
  10026. var total = 0;
  10027. var nodes = this.nodes();
  10028. for (var i = 0; i < nodes.length; i++) {
  10029. total += nodes[i].degree(includeLoops);
  10030. }
  10031. return total;
  10032. }
  10033. });
  10034. var fn$4, elesfn$c;
  10035. var beforePositionSet = function beforePositionSet(eles, newPos, silent) {
  10036. for (var i = 0; i < eles.length; i++) {
  10037. var ele = eles[i];
  10038. if (!ele.locked()) {
  10039. var oldPos = ele._private.position;
  10040. var delta = {
  10041. x: newPos.x != null ? newPos.x - oldPos.x : 0,
  10042. y: newPos.y != null ? newPos.y - oldPos.y : 0
  10043. };
  10044. if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {
  10045. ele.children().shift(delta, silent);
  10046. }
  10047. ele.dirtyBoundingBoxCache();
  10048. }
  10049. }
  10050. };
  10051. var positionDef = {
  10052. field: 'position',
  10053. bindingEvent: 'position',
  10054. allowBinding: true,
  10055. allowSetting: true,
  10056. settingEvent: 'position',
  10057. settingTriggersEvent: true,
  10058. triggerFnName: 'emitAndNotify',
  10059. allowGetting: true,
  10060. validKeys: ['x', 'y'],
  10061. beforeGet: function beforeGet(ele) {
  10062. ele.updateCompoundBounds();
  10063. },
  10064. beforeSet: function beforeSet(eles, newPos) {
  10065. beforePositionSet(eles, newPos, false);
  10066. },
  10067. onSet: function onSet(eles) {
  10068. eles.dirtyCompoundBoundsCache();
  10069. },
  10070. canSet: function canSet(ele) {
  10071. return !ele.locked();
  10072. }
  10073. };
  10074. fn$4 = elesfn$c = {
  10075. position: define.data(positionDef),
  10076. // position but no notification to renderer
  10077. silentPosition: define.data(extend({}, positionDef, {
  10078. allowBinding: false,
  10079. allowSetting: true,
  10080. settingTriggersEvent: false,
  10081. allowGetting: false,
  10082. beforeSet: function beforeSet(eles, newPos) {
  10083. beforePositionSet(eles, newPos, true);
  10084. },
  10085. onSet: function onSet(eles) {
  10086. eles.dirtyCompoundBoundsCache();
  10087. }
  10088. })),
  10089. positions: function positions(pos, silent) {
  10090. if (plainObject(pos)) {
  10091. if (silent) {
  10092. this.silentPosition(pos);
  10093. } else {
  10094. this.position(pos);
  10095. }
  10096. } else if (fn$6(pos)) {
  10097. var _fn = pos;
  10098. var cy = this.cy();
  10099. cy.startBatch();
  10100. for (var i = 0; i < this.length; i++) {
  10101. var ele = this[i];
  10102. var _pos = undefined;
  10103. if (_pos = _fn(ele, i)) {
  10104. if (silent) {
  10105. ele.silentPosition(_pos);
  10106. } else {
  10107. ele.position(_pos);
  10108. }
  10109. }
  10110. }
  10111. cy.endBatch();
  10112. }
  10113. return this; // chaining
  10114. },
  10115. silentPositions: function silentPositions(pos) {
  10116. return this.positions(pos, true);
  10117. },
  10118. shift: function shift(dim, val, silent) {
  10119. var delta;
  10120. if (plainObject(dim)) {
  10121. delta = {
  10122. x: number$1(dim.x) ? dim.x : 0,
  10123. y: number$1(dim.y) ? dim.y : 0
  10124. };
  10125. silent = val;
  10126. } else if (string(dim) && number$1(val)) {
  10127. delta = {
  10128. x: 0,
  10129. y: 0
  10130. };
  10131. delta[dim] = val;
  10132. }
  10133. if (delta != null) {
  10134. var cy = this.cy();
  10135. cy.startBatch();
  10136. for (var i = 0; i < this.length; i++) {
  10137. var ele = this[i];
  10138. // exclude any node that is a descendant of the calling collection
  10139. if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {
  10140. continue;
  10141. }
  10142. var pos = ele.position();
  10143. var newPos = {
  10144. x: pos.x + delta.x,
  10145. y: pos.y + delta.y
  10146. };
  10147. if (silent) {
  10148. ele.silentPosition(newPos);
  10149. } else {
  10150. ele.position(newPos);
  10151. }
  10152. }
  10153. cy.endBatch();
  10154. }
  10155. return this;
  10156. },
  10157. silentShift: function silentShift(dim, val) {
  10158. if (plainObject(dim)) {
  10159. this.shift(dim, true);
  10160. } else if (string(dim) && number$1(val)) {
  10161. this.shift(dim, val, true);
  10162. }
  10163. return this;
  10164. },
  10165. // get/set the rendered (i.e. on screen) positon of the element
  10166. renderedPosition: function renderedPosition(dim, val) {
  10167. var ele = this[0];
  10168. var cy = this.cy();
  10169. var zoom = cy.zoom();
  10170. var pan = cy.pan();
  10171. var rpos = plainObject(dim) ? dim : undefined;
  10172. var setting = rpos !== undefined || val !== undefined && string(dim);
  10173. if (ele && ele.isNode()) {
  10174. // must have an element and must be a node to return position
  10175. if (setting) {
  10176. for (var i = 0; i < this.length; i++) {
  10177. var _ele = this[i];
  10178. if (val !== undefined) {
  10179. // set one dimension
  10180. _ele.position(dim, (val - pan[dim]) / zoom);
  10181. } else if (rpos !== undefined) {
  10182. // set whole position
  10183. _ele.position(renderedToModelPosition(rpos, zoom, pan));
  10184. }
  10185. }
  10186. } else {
  10187. // getting
  10188. var pos = ele.position();
  10189. rpos = modelToRenderedPosition$1(pos, zoom, pan);
  10190. if (dim === undefined) {
  10191. // then return the whole rendered position
  10192. return rpos;
  10193. } else {
  10194. // then return the specified dimension
  10195. return rpos[dim];
  10196. }
  10197. }
  10198. } else if (!setting) {
  10199. return undefined; // for empty collection case
  10200. }
  10201. return this; // chaining
  10202. },
  10203. // get/set the position relative to the parent
  10204. relativePosition: function relativePosition(dim, val) {
  10205. var ele = this[0];
  10206. var cy = this.cy();
  10207. var ppos = plainObject(dim) ? dim : undefined;
  10208. var setting = ppos !== undefined || val !== undefined && string(dim);
  10209. var hasCompoundNodes = cy.hasCompoundNodes();
  10210. if (ele && ele.isNode()) {
  10211. // must have an element and must be a node to return position
  10212. if (setting) {
  10213. for (var i = 0; i < this.length; i++) {
  10214. var _ele2 = this[i];
  10215. var parent = hasCompoundNodes ? _ele2.parent() : null;
  10216. var hasParent = parent && parent.length > 0;
  10217. var relativeToParent = hasParent;
  10218. if (hasParent) {
  10219. parent = parent[0];
  10220. }
  10221. var origin = relativeToParent ? parent.position() : {
  10222. x: 0,
  10223. y: 0
  10224. };
  10225. if (val !== undefined) {
  10226. // set one dimension
  10227. _ele2.position(dim, val + origin[dim]);
  10228. } else if (ppos !== undefined) {
  10229. // set whole position
  10230. _ele2.position({
  10231. x: ppos.x + origin.x,
  10232. y: ppos.y + origin.y
  10233. });
  10234. }
  10235. }
  10236. } else {
  10237. // getting
  10238. var pos = ele.position();
  10239. var _parent = hasCompoundNodes ? ele.parent() : null;
  10240. var _hasParent = _parent && _parent.length > 0;
  10241. var _relativeToParent = _hasParent;
  10242. if (_hasParent) {
  10243. _parent = _parent[0];
  10244. }
  10245. var _origin = _relativeToParent ? _parent.position() : {
  10246. x: 0,
  10247. y: 0
  10248. };
  10249. ppos = {
  10250. x: pos.x - _origin.x,
  10251. y: pos.y - _origin.y
  10252. };
  10253. if (dim === undefined) {
  10254. // then return the whole rendered position
  10255. return ppos;
  10256. } else {
  10257. // then return the specified dimension
  10258. return ppos[dim];
  10259. }
  10260. }
  10261. } else if (!setting) {
  10262. return undefined; // for empty collection case
  10263. }
  10264. return this; // chaining
  10265. }
  10266. };
  10267. // aliases
  10268. fn$4.modelPosition = fn$4.point = fn$4.position;
  10269. fn$4.modelPositions = fn$4.points = fn$4.positions;
  10270. fn$4.renderedPoint = fn$4.renderedPosition;
  10271. fn$4.relativePoint = fn$4.relativePosition;
  10272. var position = elesfn$c;
  10273. var fn$3, elesfn$b;
  10274. fn$3 = elesfn$b = {};
  10275. elesfn$b.renderedBoundingBox = function (options) {
  10276. var bb = this.boundingBox(options);
  10277. var cy = this.cy();
  10278. var zoom = cy.zoom();
  10279. var pan = cy.pan();
  10280. var x1 = bb.x1 * zoom + pan.x;
  10281. var x2 = bb.x2 * zoom + pan.x;
  10282. var y1 = bb.y1 * zoom + pan.y;
  10283. var y2 = bb.y2 * zoom + pan.y;
  10284. return {
  10285. x1: x1,
  10286. x2: x2,
  10287. y1: y1,
  10288. y2: y2,
  10289. w: x2 - x1,
  10290. h: y2 - y1
  10291. };
  10292. };
  10293. elesfn$b.dirtyCompoundBoundsCache = function () {
  10294. var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  10295. var cy = this.cy();
  10296. if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
  10297. return this;
  10298. }
  10299. this.forEachUp(function (ele) {
  10300. if (ele.isParent()) {
  10301. var _p = ele._private;
  10302. _p.compoundBoundsClean = false;
  10303. _p.bbCache = null;
  10304. if (!silent) {
  10305. ele.emitAndNotify('bounds');
  10306. }
  10307. }
  10308. });
  10309. return this;
  10310. };
  10311. elesfn$b.updateCompoundBounds = function () {
  10312. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  10313. var cy = this.cy();
  10314. // not possible to do on non-compound graphs or with the style disabled
  10315. if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
  10316. return this;
  10317. }
  10318. // save cycles when batching -- but bounds will be stale (or not exist yet)
  10319. if (!force && cy.batching()) {
  10320. return this;
  10321. }
  10322. function update(parent) {
  10323. if (!parent.isParent()) {
  10324. return;
  10325. }
  10326. var _p = parent._private;
  10327. var children = parent.children();
  10328. var includeLabels = parent.pstyle('compound-sizing-wrt-labels').value === 'include';
  10329. var min = {
  10330. width: {
  10331. val: parent.pstyle('min-width').pfValue,
  10332. left: parent.pstyle('min-width-bias-left'),
  10333. right: parent.pstyle('min-width-bias-right')
  10334. },
  10335. height: {
  10336. val: parent.pstyle('min-height').pfValue,
  10337. top: parent.pstyle('min-height-bias-top'),
  10338. bottom: parent.pstyle('min-height-bias-bottom')
  10339. }
  10340. };
  10341. var bb = children.boundingBox({
  10342. includeLabels: includeLabels,
  10343. includeOverlays: false,
  10344. // updating the compound bounds happens outside of the regular
  10345. // cache cycle (i.e. before fired events)
  10346. useCache: false
  10347. });
  10348. var pos = _p.position;
  10349. // if children take up zero area then keep position and fall back on stylesheet w/h
  10350. if (bb.w === 0 || bb.h === 0) {
  10351. bb = {
  10352. w: parent.pstyle('width').pfValue,
  10353. h: parent.pstyle('height').pfValue
  10354. };
  10355. bb.x1 = pos.x - bb.w / 2;
  10356. bb.x2 = pos.x + bb.w / 2;
  10357. bb.y1 = pos.y - bb.h / 2;
  10358. bb.y2 = pos.y + bb.h / 2;
  10359. }
  10360. function computeBiasValues(propDiff, propBias, propBiasComplement) {
  10361. var biasDiff = 0;
  10362. var biasComplementDiff = 0;
  10363. var biasTotal = propBias + propBiasComplement;
  10364. if (propDiff > 0 && biasTotal > 0) {
  10365. biasDiff = propBias / biasTotal * propDiff;
  10366. biasComplementDiff = propBiasComplement / biasTotal * propDiff;
  10367. }
  10368. return {
  10369. biasDiff: biasDiff,
  10370. biasComplementDiff: biasComplementDiff
  10371. };
  10372. }
  10373. function computePaddingValues(width, height, paddingObject, relativeTo) {
  10374. // Assuming percentage is number from 0 to 1
  10375. if (paddingObject.units === '%') {
  10376. switch (relativeTo) {
  10377. case 'width':
  10378. return width > 0 ? paddingObject.pfValue * width : 0;
  10379. case 'height':
  10380. return height > 0 ? paddingObject.pfValue * height : 0;
  10381. case 'average':
  10382. return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;
  10383. case 'min':
  10384. return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;
  10385. case 'max':
  10386. return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;
  10387. default:
  10388. return 0;
  10389. }
  10390. } else if (paddingObject.units === 'px') {
  10391. return paddingObject.pfValue;
  10392. } else {
  10393. return 0;
  10394. }
  10395. }
  10396. var leftVal = min.width.left.value;
  10397. if (min.width.left.units === 'px' && min.width.val > 0) {
  10398. leftVal = leftVal * 100 / min.width.val;
  10399. }
  10400. var rightVal = min.width.right.value;
  10401. if (min.width.right.units === 'px' && min.width.val > 0) {
  10402. rightVal = rightVal * 100 / min.width.val;
  10403. }
  10404. var topVal = min.height.top.value;
  10405. if (min.height.top.units === 'px' && min.height.val > 0) {
  10406. topVal = topVal * 100 / min.height.val;
  10407. }
  10408. var bottomVal = min.height.bottom.value;
  10409. if (min.height.bottom.units === 'px' && min.height.val > 0) {
  10410. bottomVal = bottomVal * 100 / min.height.val;
  10411. }
  10412. var widthBiasDiffs = computeBiasValues(min.width.val - bb.w, leftVal, rightVal);
  10413. var diffLeft = widthBiasDiffs.biasDiff;
  10414. var diffRight = widthBiasDiffs.biasComplementDiff;
  10415. var heightBiasDiffs = computeBiasValues(min.height.val - bb.h, topVal, bottomVal);
  10416. var diffTop = heightBiasDiffs.biasDiff;
  10417. var diffBottom = heightBiasDiffs.biasComplementDiff;
  10418. _p.autoPadding = computePaddingValues(bb.w, bb.h, parent.pstyle('padding'), parent.pstyle('padding-relative-to').value);
  10419. _p.autoWidth = Math.max(bb.w, min.width.val);
  10420. pos.x = (-diffLeft + bb.x1 + bb.x2 + diffRight) / 2;
  10421. _p.autoHeight = Math.max(bb.h, min.height.val);
  10422. pos.y = (-diffTop + bb.y1 + bb.y2 + diffBottom) / 2;
  10423. }
  10424. for (var i = 0; i < this.length; i++) {
  10425. var ele = this[i];
  10426. var _p = ele._private;
  10427. if (!_p.compoundBoundsClean || force) {
  10428. update(ele);
  10429. if (!cy.batching()) {
  10430. _p.compoundBoundsClean = true;
  10431. }
  10432. }
  10433. }
  10434. return this;
  10435. };
  10436. var noninf = function noninf(x) {
  10437. if (x === Infinity || x === -Infinity) {
  10438. return 0;
  10439. }
  10440. return x;
  10441. };
  10442. var updateBounds = function updateBounds(b, x1, y1, x2, y2) {
  10443. // don't update with zero area boxes
  10444. if (x2 - x1 === 0 || y2 - y1 === 0) {
  10445. return;
  10446. }
  10447. // don't update with null dim
  10448. if (x1 == null || y1 == null || x2 == null || y2 == null) {
  10449. return;
  10450. }
  10451. b.x1 = x1 < b.x1 ? x1 : b.x1;
  10452. b.x2 = x2 > b.x2 ? x2 : b.x2;
  10453. b.y1 = y1 < b.y1 ? y1 : b.y1;
  10454. b.y2 = y2 > b.y2 ? y2 : b.y2;
  10455. b.w = b.x2 - b.x1;
  10456. b.h = b.y2 - b.y1;
  10457. };
  10458. var updateBoundsFromBox = function updateBoundsFromBox(b, b2) {
  10459. if (b2 == null) {
  10460. return b;
  10461. }
  10462. return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);
  10463. };
  10464. var prefixedProperty = function prefixedProperty(obj, field, prefix) {
  10465. return getPrefixedProperty(obj, field, prefix);
  10466. };
  10467. var updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {
  10468. if (ele.cy().headless()) {
  10469. return;
  10470. }
  10471. var _p = ele._private;
  10472. var rstyle = _p.rstyle;
  10473. var halfArW = rstyle.arrowWidth / 2;
  10474. var arrowType = ele.pstyle(prefix + '-arrow-shape').value;
  10475. var x;
  10476. var y;
  10477. if (arrowType !== 'none') {
  10478. if (prefix === 'source') {
  10479. x = rstyle.srcX;
  10480. y = rstyle.srcY;
  10481. } else if (prefix === 'target') {
  10482. x = rstyle.tgtX;
  10483. y = rstyle.tgtY;
  10484. } else {
  10485. x = rstyle.midX;
  10486. y = rstyle.midY;
  10487. }
  10488. // always store the individual arrow bounds
  10489. var bbs = _p.arrowBounds = _p.arrowBounds || {};
  10490. var bb = bbs[prefix] = bbs[prefix] || {};
  10491. bb.x1 = x - halfArW;
  10492. bb.y1 = y - halfArW;
  10493. bb.x2 = x + halfArW;
  10494. bb.y2 = y + halfArW;
  10495. bb.w = bb.x2 - bb.x1;
  10496. bb.h = bb.y2 - bb.y1;
  10497. expandBoundingBox(bb, 1);
  10498. updateBounds(bounds, bb.x1, bb.y1, bb.x2, bb.y2);
  10499. }
  10500. };
  10501. var updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {
  10502. if (ele.cy().headless()) {
  10503. return;
  10504. }
  10505. var prefixDash;
  10506. if (prefix) {
  10507. prefixDash = prefix + '-';
  10508. } else {
  10509. prefixDash = '';
  10510. }
  10511. var _p = ele._private;
  10512. var rstyle = _p.rstyle;
  10513. var label = ele.pstyle(prefixDash + 'label').strValue;
  10514. if (label) {
  10515. var halign = ele.pstyle('text-halign');
  10516. var valign = ele.pstyle('text-valign');
  10517. var labelWidth = prefixedProperty(rstyle, 'labelWidth', prefix);
  10518. var labelHeight = prefixedProperty(rstyle, 'labelHeight', prefix);
  10519. var labelX = prefixedProperty(rstyle, 'labelX', prefix);
  10520. var labelY = prefixedProperty(rstyle, 'labelY', prefix);
  10521. var marginX = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  10522. var marginY = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  10523. var isEdge = ele.isEdge();
  10524. var rotation = ele.pstyle(prefixDash + 'text-rotation');
  10525. var outlineWidth = ele.pstyle('text-outline-width').pfValue;
  10526. var borderWidth = ele.pstyle('text-border-width').pfValue;
  10527. var halfBorderWidth = borderWidth / 2;
  10528. var padding = ele.pstyle('text-background-padding').pfValue;
  10529. var marginOfError = 2; // expand to work around browser dimension inaccuracies
  10530. var lh = labelHeight;
  10531. var lw = labelWidth;
  10532. var lw_2 = lw / 2;
  10533. var lh_2 = lh / 2;
  10534. var lx1, lx2, ly1, ly2;
  10535. if (isEdge) {
  10536. lx1 = labelX - lw_2;
  10537. lx2 = labelX + lw_2;
  10538. ly1 = labelY - lh_2;
  10539. ly2 = labelY + lh_2;
  10540. } else {
  10541. switch (halign.value) {
  10542. case 'left':
  10543. lx1 = labelX - lw;
  10544. lx2 = labelX;
  10545. break;
  10546. case 'center':
  10547. lx1 = labelX - lw_2;
  10548. lx2 = labelX + lw_2;
  10549. break;
  10550. case 'right':
  10551. lx1 = labelX;
  10552. lx2 = labelX + lw;
  10553. break;
  10554. }
  10555. switch (valign.value) {
  10556. case 'top':
  10557. ly1 = labelY - lh;
  10558. ly2 = labelY;
  10559. break;
  10560. case 'center':
  10561. ly1 = labelY - lh_2;
  10562. ly2 = labelY + lh_2;
  10563. break;
  10564. case 'bottom':
  10565. ly1 = labelY;
  10566. ly2 = labelY + lh;
  10567. break;
  10568. }
  10569. }
  10570. // shift by margin and expand by outline and border
  10571. var leftPad = marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
  10572. var rightPad = marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
  10573. var topPad = marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
  10574. var botPad = marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
  10575. lx1 += leftPad;
  10576. lx2 += rightPad;
  10577. ly1 += topPad;
  10578. ly2 += botPad;
  10579. // always store the unrotated label bounds separately
  10580. var bbPrefix = prefix || 'main';
  10581. var bbs = _p.labelBounds;
  10582. var bb = bbs[bbPrefix] = bbs[bbPrefix] || {};
  10583. bb.x1 = lx1;
  10584. bb.y1 = ly1;
  10585. bb.x2 = lx2;
  10586. bb.y2 = ly2;
  10587. bb.w = lx2 - lx1;
  10588. bb.h = ly2 - ly1;
  10589. bb.leftPad = leftPad;
  10590. bb.rightPad = rightPad;
  10591. bb.topPad = topPad;
  10592. bb.botPad = botPad;
  10593. var isAutorotate = isEdge && rotation.strValue === 'autorotate';
  10594. var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;
  10595. if (isAutorotate || isPfValue) {
  10596. var theta = isAutorotate ? prefixedProperty(_p.rstyle, 'labelAngle', prefix) : rotation.pfValue;
  10597. var cos = Math.cos(theta);
  10598. var sin = Math.sin(theta);
  10599. // rotation point (default value for center-center)
  10600. var xo = (lx1 + lx2) / 2;
  10601. var yo = (ly1 + ly2) / 2;
  10602. if (!isEdge) {
  10603. switch (halign.value) {
  10604. case 'left':
  10605. xo = lx2;
  10606. break;
  10607. case 'right':
  10608. xo = lx1;
  10609. break;
  10610. }
  10611. switch (valign.value) {
  10612. case 'top':
  10613. yo = ly2;
  10614. break;
  10615. case 'bottom':
  10616. yo = ly1;
  10617. break;
  10618. }
  10619. }
  10620. var rotate = function rotate(x, y) {
  10621. x = x - xo;
  10622. y = y - yo;
  10623. return {
  10624. x: x * cos - y * sin + xo,
  10625. y: x * sin + y * cos + yo
  10626. };
  10627. };
  10628. var px1y1 = rotate(lx1, ly1);
  10629. var px1y2 = rotate(lx1, ly2);
  10630. var px2y1 = rotate(lx2, ly1);
  10631. var px2y2 = rotate(lx2, ly2);
  10632. lx1 = Math.min(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
  10633. lx2 = Math.max(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
  10634. ly1 = Math.min(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
  10635. ly2 = Math.max(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
  10636. }
  10637. var bbPrefixRot = bbPrefix + 'Rot';
  10638. var bbRot = bbs[bbPrefixRot] = bbs[bbPrefixRot] || {};
  10639. bbRot.x1 = lx1;
  10640. bbRot.y1 = ly1;
  10641. bbRot.x2 = lx2;
  10642. bbRot.y2 = ly2;
  10643. bbRot.w = lx2 - lx1;
  10644. bbRot.h = ly2 - ly1;
  10645. updateBounds(bounds, lx1, ly1, lx2, ly2);
  10646. updateBounds(_p.labelBounds.all, lx1, ly1, lx2, ly2);
  10647. }
  10648. return bounds;
  10649. };
  10650. var updateBoundsFromOutline = function updateBoundsFromOutline(bounds, ele) {
  10651. if (ele.cy().headless()) {
  10652. return;
  10653. }
  10654. var outlineOpacity = ele.pstyle('outline-opacity').value;
  10655. var outlineWidth = ele.pstyle('outline-width').value;
  10656. var outlineOffset = ele.pstyle('outline-offset').value;
  10657. var expansion = outlineWidth + outlineOffset;
  10658. updateBoundsFromMiter(bounds, ele, outlineOpacity, expansion, 'outside', expansion / 2);
  10659. };
  10660. var updateBoundsFromMiter = function updateBoundsFromMiter(bounds, ele, opacity, expansionSize, expansionPosition, useFallbackValue) {
  10661. if (opacity === 0 || expansionSize <= 0 || expansionPosition === 'inside') {
  10662. return;
  10663. }
  10664. var cy = ele.cy();
  10665. var r = cy.renderer();
  10666. var rshape = r.nodeShapes[r.getNodeShape(ele)];
  10667. if (!rshape) {
  10668. return;
  10669. }
  10670. var _ele$position = ele.position(),
  10671. x = _ele$position.x,
  10672. y = _ele$position.y;
  10673. var w = ele.width();
  10674. var h = ele.height();
  10675. if (rshape.hasMiterBounds) {
  10676. if (expansionPosition === 'center') {
  10677. expansionSize /= 2;
  10678. }
  10679. var mbb = rshape.miterBounds(x, y, w, h, expansionSize);
  10680. updateBoundsFromBox(bounds, mbb);
  10681. } else if (useFallbackValue != null && useFallbackValue > 0) {
  10682. expandBoundingBoxSides(bounds, [useFallbackValue, useFallbackValue, useFallbackValue, useFallbackValue]);
  10683. }
  10684. };
  10685. var updateBoundsFromMiterBorder = function updateBoundsFromMiterBorder(bounds, ele) {
  10686. if (ele.cy().headless()) {
  10687. return;
  10688. }
  10689. var borderOpacity = ele.pstyle('border-opacity').value;
  10690. var borderWidth = ele.pstyle('border-width').pfValue;
  10691. var borderPosition = ele.pstyle('border-position').value;
  10692. updateBoundsFromMiter(bounds, ele, borderOpacity, borderWidth, borderPosition);
  10693. };
  10694. // get the bounding box of the elements (in raw model position)
  10695. var boundingBoxImpl = function boundingBoxImpl(ele, options) {
  10696. var cy = ele._private.cy;
  10697. var styleEnabled = cy.styleEnabled();
  10698. var headless = cy.headless();
  10699. var bounds = makeBoundingBox();
  10700. var _p = ele._private;
  10701. var isNode = ele.isNode();
  10702. var isEdge = ele.isEdge();
  10703. var ex1, ex2, ey1, ey2; // extrema of body / lines
  10704. var x, y; // node pos
  10705. var rstyle = _p.rstyle;
  10706. var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0];
  10707. // must use `display` prop only, as reading `compound.width()` causes recursion
  10708. // (other factors like width values will be considered later in this function anyway)
  10709. var isDisplayed = function isDisplayed(ele) {
  10710. return ele.pstyle('display').value !== 'none';
  10711. };
  10712. var displayed = !styleEnabled || isDisplayed(ele)
  10713. // must take into account connected nodes b/c of implicit edge hiding on display:none node
  10714. && (!isEdge || isDisplayed(ele.source()) && isDisplayed(ele.target()));
  10715. if (displayed) {
  10716. // displayed suffices, since we will find zero area eles anyway
  10717. var overlayOpacity = 0;
  10718. var overlayPadding = 0;
  10719. if (styleEnabled && options.includeOverlays) {
  10720. overlayOpacity = ele.pstyle('overlay-opacity').value;
  10721. if (overlayOpacity !== 0) {
  10722. overlayPadding = ele.pstyle('overlay-padding').value;
  10723. }
  10724. }
  10725. var underlayOpacity = 0;
  10726. var underlayPadding = 0;
  10727. if (styleEnabled && options.includeUnderlays) {
  10728. underlayOpacity = ele.pstyle('underlay-opacity').value;
  10729. if (underlayOpacity !== 0) {
  10730. underlayPadding = ele.pstyle('underlay-padding').value;
  10731. }
  10732. }
  10733. var padding = Math.max(overlayPadding, underlayPadding);
  10734. var w = 0;
  10735. var wHalf = 0;
  10736. if (styleEnabled) {
  10737. w = ele.pstyle('width').pfValue;
  10738. wHalf = w / 2;
  10739. }
  10740. if (isNode && options.includeNodes) {
  10741. var pos = ele.position();
  10742. x = pos.x;
  10743. y = pos.y;
  10744. var _w = ele.outerWidth();
  10745. var halfW = _w / 2;
  10746. var h = ele.outerHeight();
  10747. var halfH = h / 2;
  10748. // handle node dimensions
  10749. /////////////////////////
  10750. ex1 = x - halfW;
  10751. ex2 = x + halfW;
  10752. ey1 = y - halfH;
  10753. ey2 = y + halfH;
  10754. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10755. if (styleEnabled) {
  10756. updateBoundsFromOutline(bounds, ele);
  10757. }
  10758. if (styleEnabled && options.includeOutlines && !headless) {
  10759. updateBoundsFromOutline(bounds, ele);
  10760. }
  10761. if (styleEnabled) {
  10762. updateBoundsFromMiterBorder(bounds, ele);
  10763. }
  10764. } else if (isEdge && options.includeEdges) {
  10765. if (styleEnabled && !headless) {
  10766. var curveStyle = ele.pstyle('curve-style').strValue;
  10767. // handle edge dimensions (rough box estimate)
  10768. //////////////////////////////////////////////
  10769. ex1 = Math.min(rstyle.srcX, rstyle.midX, rstyle.tgtX);
  10770. ex2 = Math.max(rstyle.srcX, rstyle.midX, rstyle.tgtX);
  10771. ey1 = Math.min(rstyle.srcY, rstyle.midY, rstyle.tgtY);
  10772. ey2 = Math.max(rstyle.srcY, rstyle.midY, rstyle.tgtY);
  10773. // take into account edge width
  10774. ex1 -= wHalf;
  10775. ex2 += wHalf;
  10776. ey1 -= wHalf;
  10777. ey2 += wHalf;
  10778. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10779. // precise edges
  10780. ////////////////
  10781. if (curveStyle === 'haystack') {
  10782. var hpts = rstyle.haystackPts;
  10783. if (hpts && hpts.length === 2) {
  10784. ex1 = hpts[0].x;
  10785. ey1 = hpts[0].y;
  10786. ex2 = hpts[1].x;
  10787. ey2 = hpts[1].y;
  10788. if (ex1 > ex2) {
  10789. var temp = ex1;
  10790. ex1 = ex2;
  10791. ex2 = temp;
  10792. }
  10793. if (ey1 > ey2) {
  10794. var _temp = ey1;
  10795. ey1 = ey2;
  10796. ey2 = _temp;
  10797. }
  10798. updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);
  10799. }
  10800. } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || endsWith(curveStyle, 'taxi')) {
  10801. var pts;
  10802. switch (curveStyle) {
  10803. case 'bezier':
  10804. case 'unbundled-bezier':
  10805. pts = rstyle.bezierPts;
  10806. break;
  10807. case 'segments':
  10808. case 'taxi':
  10809. case 'round-segments':
  10810. case 'round-taxi':
  10811. pts = rstyle.linePts;
  10812. break;
  10813. }
  10814. if (pts != null) {
  10815. for (var j = 0; j < pts.length; j++) {
  10816. var pt = pts[j];
  10817. ex1 = pt.x - wHalf;
  10818. ex2 = pt.x + wHalf;
  10819. ey1 = pt.y - wHalf;
  10820. ey2 = pt.y + wHalf;
  10821. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10822. }
  10823. }
  10824. } // bezier-like or segment-like edge
  10825. } else {
  10826. // headless or style disabled
  10827. // fallback on source and target positions
  10828. //////////////////////////////////////////
  10829. var n1 = ele.source();
  10830. var n1pos = n1.position();
  10831. var n2 = ele.target();
  10832. var n2pos = n2.position();
  10833. ex1 = n1pos.x;
  10834. ex2 = n2pos.x;
  10835. ey1 = n1pos.y;
  10836. ey2 = n2pos.y;
  10837. if (ex1 > ex2) {
  10838. var _temp2 = ex1;
  10839. ex1 = ex2;
  10840. ex2 = _temp2;
  10841. }
  10842. if (ey1 > ey2) {
  10843. var _temp3 = ey1;
  10844. ey1 = ey2;
  10845. ey2 = _temp3;
  10846. }
  10847. // take into account edge width
  10848. ex1 -= wHalf;
  10849. ex2 += wHalf;
  10850. ey1 -= wHalf;
  10851. ey2 += wHalf;
  10852. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10853. } // headless or style disabled
  10854. } // edges
  10855. // handle edge arrow size
  10856. /////////////////////////
  10857. if (styleEnabled && options.includeEdges && isEdge) {
  10858. updateBoundsFromArrow(bounds, ele, 'mid-source');
  10859. updateBoundsFromArrow(bounds, ele, 'mid-target');
  10860. updateBoundsFromArrow(bounds, ele, 'source');
  10861. updateBoundsFromArrow(bounds, ele, 'target');
  10862. }
  10863. // ghost
  10864. ////////
  10865. if (styleEnabled) {
  10866. var ghost = ele.pstyle('ghost').value === 'yes';
  10867. if (ghost) {
  10868. var gx = ele.pstyle('ghost-offset-x').pfValue;
  10869. var gy = ele.pstyle('ghost-offset-y').pfValue;
  10870. updateBounds(bounds, bounds.x1 + gx, bounds.y1 + gy, bounds.x2 + gx, bounds.y2 + gy);
  10871. }
  10872. }
  10873. // always store the body bounds separately from the labels
  10874. var bbBody = _p.bodyBounds = _p.bodyBounds || {};
  10875. assignBoundingBox(bbBody, bounds);
  10876. expandBoundingBoxSides(bbBody, manualExpansion);
  10877. expandBoundingBox(bbBody, 1); // expand to work around browser dimension inaccuracies
  10878. // overlay
  10879. //////////
  10880. if (styleEnabled) {
  10881. ex1 = bounds.x1;
  10882. ex2 = bounds.x2;
  10883. ey1 = bounds.y1;
  10884. ey2 = bounds.y2;
  10885. updateBounds(bounds, ex1 - padding, ey1 - padding, ex2 + padding, ey2 + padding);
  10886. }
  10887. // always store the body bounds separately from the labels
  10888. var bbOverlay = _p.overlayBounds = _p.overlayBounds || {};
  10889. assignBoundingBox(bbOverlay, bounds);
  10890. expandBoundingBoxSides(bbOverlay, manualExpansion);
  10891. expandBoundingBox(bbOverlay, 1); // expand to work around browser dimension inaccuracies
  10892. // handle label dimensions
  10893. //////////////////////////
  10894. var bbLabels = _p.labelBounds = _p.labelBounds || {};
  10895. if (bbLabels.all != null) {
  10896. clearBoundingBox(bbLabels.all);
  10897. } else {
  10898. bbLabels.all = makeBoundingBox();
  10899. }
  10900. if (styleEnabled && options.includeLabels) {
  10901. if (options.includeMainLabels) {
  10902. updateBoundsFromLabel(bounds, ele, null);
  10903. }
  10904. if (isEdge) {
  10905. if (options.includeSourceLabels) {
  10906. updateBoundsFromLabel(bounds, ele, 'source');
  10907. }
  10908. if (options.includeTargetLabels) {
  10909. updateBoundsFromLabel(bounds, ele, 'target');
  10910. }
  10911. }
  10912. } // style enabled for labels
  10913. } // if displayed
  10914. bounds.x1 = noninf(bounds.x1);
  10915. bounds.y1 = noninf(bounds.y1);
  10916. bounds.x2 = noninf(bounds.x2);
  10917. bounds.y2 = noninf(bounds.y2);
  10918. bounds.w = noninf(bounds.x2 - bounds.x1);
  10919. bounds.h = noninf(bounds.y2 - bounds.y1);
  10920. if (bounds.w > 0 && bounds.h > 0 && displayed) {
  10921. expandBoundingBoxSides(bounds, manualExpansion);
  10922. // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides
  10923. expandBoundingBox(bounds, 1);
  10924. }
  10925. return bounds;
  10926. };
  10927. var getKey = function getKey(opts) {
  10928. var i = 0;
  10929. var tf = function tf(val) {
  10930. return (val ? 1 : 0) << i++;
  10931. };
  10932. var key = 0;
  10933. key += tf(opts.incudeNodes);
  10934. key += tf(opts.includeEdges);
  10935. key += tf(opts.includeLabels);
  10936. key += tf(opts.includeMainLabels);
  10937. key += tf(opts.includeSourceLabels);
  10938. key += tf(opts.includeTargetLabels);
  10939. key += tf(opts.includeOverlays);
  10940. key += tf(opts.includeOutlines);
  10941. return key;
  10942. };
  10943. var getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {
  10944. var r = function r(x) {
  10945. return Math.round(x);
  10946. };
  10947. if (ele.isEdge()) {
  10948. var p1 = ele.source().position();
  10949. var p2 = ele.target().position();
  10950. return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);
  10951. } else {
  10952. var p = ele.position();
  10953. return hashIntsArray([r(p.x), r(p.y)]);
  10954. }
  10955. };
  10956. var cachedBoundingBoxImpl = function cachedBoundingBoxImpl(ele, opts) {
  10957. var _p = ele._private;
  10958. var bb;
  10959. var isEdge = ele.isEdge();
  10960. var key = opts == null ? defBbOptsKey : getKey(opts);
  10961. var usingDefOpts = key === defBbOptsKey;
  10962. if (_p.bbCache == null) {
  10963. bb = boundingBoxImpl(ele, defBbOpts);
  10964. _p.bbCache = bb;
  10965. _p.bbCachePosKey = getBoundingBoxPosKey(ele);
  10966. } else {
  10967. bb = _p.bbCache;
  10968. }
  10969. // not using def opts => need to build up bb from combination of sub bbs
  10970. if (!usingDefOpts) {
  10971. var isNode = ele.isNode();
  10972. bb = makeBoundingBox();
  10973. if (opts.includeNodes && isNode || opts.includeEdges && !isNode) {
  10974. if (opts.includeOverlays) {
  10975. updateBoundsFromBox(bb, _p.overlayBounds);
  10976. } else {
  10977. updateBoundsFromBox(bb, _p.bodyBounds);
  10978. }
  10979. }
  10980. if (opts.includeLabels) {
  10981. if (opts.includeMainLabels && (!isEdge || opts.includeSourceLabels && opts.includeTargetLabels)) {
  10982. updateBoundsFromBox(bb, _p.labelBounds.all);
  10983. } else {
  10984. if (opts.includeMainLabels) {
  10985. updateBoundsFromBox(bb, _p.labelBounds.mainRot);
  10986. }
  10987. if (opts.includeSourceLabels) {
  10988. updateBoundsFromBox(bb, _p.labelBounds.sourceRot);
  10989. }
  10990. if (opts.includeTargetLabels) {
  10991. updateBoundsFromBox(bb, _p.labelBounds.targetRot);
  10992. }
  10993. }
  10994. }
  10995. bb.w = bb.x2 - bb.x1;
  10996. bb.h = bb.y2 - bb.y1;
  10997. }
  10998. return bb;
  10999. };
  11000. var defBbOpts = {
  11001. includeNodes: true,
  11002. includeEdges: true,
  11003. includeLabels: true,
  11004. includeMainLabels: true,
  11005. includeSourceLabels: true,
  11006. includeTargetLabels: true,
  11007. includeOverlays: true,
  11008. includeUnderlays: true,
  11009. includeOutlines: true,
  11010. useCache: true
  11011. };
  11012. var defBbOptsKey = getKey(defBbOpts);
  11013. var filledBbOpts = defaults$g(defBbOpts);
  11014. elesfn$b.boundingBox = function (options) {
  11015. var bounds;
  11016. var useCache = options === undefined || options.useCache === undefined || options.useCache === true;
  11017. var isDirty = memoize(function (ele) {
  11018. var _p = ele._private;
  11019. return _p.bbCache == null || _p.styleDirty || _p.bbCachePosKey !== getBoundingBoxPosKey(ele);
  11020. }, function (ele) {
  11021. return ele.id();
  11022. });
  11023. // the main usecase is ele.boundingBox() for a single element with no/def options
  11024. // specified s.t. the cache is used, so check for this case to make it faster by
  11025. // avoiding the overhead of the rest of the function
  11026. if (useCache && this.length === 1 && !isDirty(this[0])) {
  11027. if (options === undefined) {
  11028. options = defBbOpts;
  11029. } else {
  11030. options = filledBbOpts(options);
  11031. }
  11032. bounds = cachedBoundingBoxImpl(this[0], options);
  11033. } else {
  11034. bounds = makeBoundingBox();
  11035. options = options || defBbOpts;
  11036. var opts = filledBbOpts(options);
  11037. var eles = this;
  11038. var cy = eles.cy();
  11039. var styleEnabled = cy.styleEnabled();
  11040. // cache the isDirty state for all eles, edges first since they depend on node state
  11041. this.edges().forEach(isDirty);
  11042. this.nodes().forEach(isDirty);
  11043. if (styleEnabled) {
  11044. this.recalculateRenderedStyle(useCache);
  11045. }
  11046. this.updateCompoundBounds(!useCache);
  11047. for (var i = 0; i < eles.length; i++) {
  11048. var ele = eles[i];
  11049. if (isDirty(ele)) {
  11050. ele.dirtyBoundingBoxCache();
  11051. }
  11052. updateBoundsFromBox(bounds, cachedBoundingBoxImpl(ele, opts));
  11053. }
  11054. }
  11055. bounds.x1 = noninf(bounds.x1);
  11056. bounds.y1 = noninf(bounds.y1);
  11057. bounds.x2 = noninf(bounds.x2);
  11058. bounds.y2 = noninf(bounds.y2);
  11059. bounds.w = noninf(bounds.x2 - bounds.x1);
  11060. bounds.h = noninf(bounds.y2 - bounds.y1);
  11061. return bounds;
  11062. };
  11063. elesfn$b.dirtyBoundingBoxCache = function () {
  11064. for (var i = 0; i < this.length; i++) {
  11065. var _p = this[i]._private;
  11066. _p.bbCache = null;
  11067. _p.bbCachePosKey = null;
  11068. _p.bodyBounds = null;
  11069. _p.overlayBounds = null;
  11070. _p.labelBounds.all = null;
  11071. _p.labelBounds.source = null;
  11072. _p.labelBounds.target = null;
  11073. _p.labelBounds.main = null;
  11074. _p.labelBounds.sourceRot = null;
  11075. _p.labelBounds.targetRot = null;
  11076. _p.labelBounds.mainRot = null;
  11077. _p.arrowBounds.source = null;
  11078. _p.arrowBounds.target = null;
  11079. _p.arrowBounds['mid-source'] = null;
  11080. _p.arrowBounds['mid-target'] = null;
  11081. }
  11082. this.emitAndNotify('bounds');
  11083. return this;
  11084. };
  11085. // private helper to get bounding box for custom node positions
  11086. // - good for perf in certain cases but currently requires dirtying the rendered style
  11087. // - would be better to not modify the nodes but the nodes are read directly everywhere in the renderer...
  11088. // - try to use for only things like discrete layouts where the node position would change anyway
  11089. elesfn$b.boundingBoxAt = function (fn) {
  11090. var nodes = this.nodes();
  11091. var cy = this.cy();
  11092. var hasCompoundNodes = cy.hasCompoundNodes();
  11093. var parents = cy.collection();
  11094. if (hasCompoundNodes) {
  11095. parents = nodes.filter(function (node) {
  11096. return node.isParent();
  11097. });
  11098. nodes = nodes.not(parents);
  11099. }
  11100. if (plainObject(fn)) {
  11101. var obj = fn;
  11102. fn = function fn() {
  11103. return obj;
  11104. };
  11105. }
  11106. var storeOldPos = function storeOldPos(node, i) {
  11107. return node._private.bbAtOldPos = fn(node, i);
  11108. };
  11109. var getOldPos = function getOldPos(node) {
  11110. return node._private.bbAtOldPos;
  11111. };
  11112. cy.startBatch();
  11113. nodes.forEach(storeOldPos).silentPositions(fn);
  11114. if (hasCompoundNodes) {
  11115. parents.dirtyCompoundBoundsCache();
  11116. parents.dirtyBoundingBoxCache();
  11117. parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  11118. }
  11119. var bb = copyBoundingBox(this.boundingBox({
  11120. useCache: false
  11121. }));
  11122. nodes.silentPositions(getOldPos);
  11123. if (hasCompoundNodes) {
  11124. parents.dirtyCompoundBoundsCache();
  11125. parents.dirtyBoundingBoxCache();
  11126. parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  11127. }
  11128. cy.endBatch();
  11129. return bb;
  11130. };
  11131. fn$3.boundingbox = fn$3.bb = fn$3.boundingBox;
  11132. fn$3.renderedBoundingbox = fn$3.renderedBoundingBox;
  11133. var bounds = elesfn$b;
  11134. var fn$2, elesfn$a;
  11135. fn$2 = elesfn$a = {};
  11136. var defineDimFns = function defineDimFns(opts) {
  11137. opts.uppercaseName = capitalize(opts.name);
  11138. opts.autoName = 'auto' + opts.uppercaseName;
  11139. opts.labelName = 'label' + opts.uppercaseName;
  11140. opts.outerName = 'outer' + opts.uppercaseName;
  11141. opts.uppercaseOuterName = capitalize(opts.outerName);
  11142. fn$2[opts.name] = function dimImpl() {
  11143. var ele = this[0];
  11144. var _p = ele._private;
  11145. var cy = _p.cy;
  11146. var styleEnabled = cy._private.styleEnabled;
  11147. if (ele) {
  11148. if (styleEnabled) {
  11149. if (ele.isParent()) {
  11150. ele.updateCompoundBounds();
  11151. return _p[opts.autoName] || 0;
  11152. }
  11153. var d = ele.pstyle(opts.name);
  11154. switch (d.strValue) {
  11155. case 'label':
  11156. ele.recalculateRenderedStyle();
  11157. return _p.rstyle[opts.labelName] || 0;
  11158. default:
  11159. return d.pfValue;
  11160. }
  11161. } else {
  11162. return 1;
  11163. }
  11164. }
  11165. };
  11166. fn$2['outer' + opts.uppercaseName] = function outerDimImpl() {
  11167. var ele = this[0];
  11168. var _p = ele._private;
  11169. var cy = _p.cy;
  11170. var styleEnabled = cy._private.styleEnabled;
  11171. if (ele) {
  11172. if (styleEnabled) {
  11173. var dim = ele[opts.name]();
  11174. var borderPos = ele.pstyle('border-position').value;
  11175. var border;
  11176. if (borderPos === 'center') {
  11177. border = ele.pstyle('border-width').pfValue; // n.b. 1/2 each side
  11178. } else if (borderPos === 'outside') {
  11179. border = 2 * ele.pstyle('border-width').pfValue;
  11180. } else {
  11181. // 'inside'
  11182. border = 0;
  11183. }
  11184. var padding = 2 * ele.padding();
  11185. return dim + border + padding;
  11186. } else {
  11187. return 1;
  11188. }
  11189. }
  11190. };
  11191. fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {
  11192. var ele = this[0];
  11193. if (ele) {
  11194. var d = ele[opts.name]();
  11195. return d * this.cy().zoom();
  11196. }
  11197. };
  11198. fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {
  11199. var ele = this[0];
  11200. if (ele) {
  11201. var od = ele[opts.outerName]();
  11202. return od * this.cy().zoom();
  11203. }
  11204. };
  11205. };
  11206. defineDimFns({
  11207. name: 'width'
  11208. });
  11209. defineDimFns({
  11210. name: 'height'
  11211. });
  11212. elesfn$a.padding = function () {
  11213. var ele = this[0];
  11214. var _p = ele._private;
  11215. if (ele.isParent()) {
  11216. ele.updateCompoundBounds();
  11217. if (_p.autoPadding !== undefined) {
  11218. return _p.autoPadding;
  11219. } else {
  11220. return ele.pstyle('padding').pfValue;
  11221. }
  11222. } else {
  11223. return ele.pstyle('padding').pfValue;
  11224. }
  11225. };
  11226. elesfn$a.paddedHeight = function () {
  11227. var ele = this[0];
  11228. return ele.height() + 2 * ele.padding();
  11229. };
  11230. elesfn$a.paddedWidth = function () {
  11231. var ele = this[0];
  11232. return ele.width() + 2 * ele.padding();
  11233. };
  11234. var widthHeight = elesfn$a;
  11235. var ifEdge = function ifEdge(ele, getValue) {
  11236. if (ele.isEdge() && ele.takesUpSpace()) {
  11237. return getValue(ele);
  11238. }
  11239. };
  11240. var ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {
  11241. if (ele.isEdge() && ele.takesUpSpace()) {
  11242. var cy = ele.cy();
  11243. return modelToRenderedPosition$1(getPoint(ele), cy.zoom(), cy.pan());
  11244. }
  11245. };
  11246. var ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {
  11247. if (ele.isEdge() && ele.takesUpSpace()) {
  11248. var cy = ele.cy();
  11249. var pan = cy.pan();
  11250. var zoom = cy.zoom();
  11251. return getPoints(ele).map(function (p) {
  11252. return modelToRenderedPosition$1(p, zoom, pan);
  11253. });
  11254. }
  11255. };
  11256. var controlPoints = function controlPoints(ele) {
  11257. return ele.renderer().getControlPoints(ele);
  11258. };
  11259. var segmentPoints = function segmentPoints(ele) {
  11260. return ele.renderer().getSegmentPoints(ele);
  11261. };
  11262. var sourceEndpoint = function sourceEndpoint(ele) {
  11263. return ele.renderer().getSourceEndpoint(ele);
  11264. };
  11265. var targetEndpoint = function targetEndpoint(ele) {
  11266. return ele.renderer().getTargetEndpoint(ele);
  11267. };
  11268. var midpoint = function midpoint(ele) {
  11269. return ele.renderer().getEdgeMidpoint(ele);
  11270. };
  11271. var pts = {
  11272. controlPoints: {
  11273. get: controlPoints,
  11274. mult: true
  11275. },
  11276. segmentPoints: {
  11277. get: segmentPoints,
  11278. mult: true
  11279. },
  11280. sourceEndpoint: {
  11281. get: sourceEndpoint
  11282. },
  11283. targetEndpoint: {
  11284. get: targetEndpoint
  11285. },
  11286. midpoint: {
  11287. get: midpoint
  11288. }
  11289. };
  11290. var renderedName = function renderedName(name) {
  11291. return 'rendered' + name[0].toUpperCase() + name.substr(1);
  11292. };
  11293. var edgePoints = Object.keys(pts).reduce(function (obj, name) {
  11294. var spec = pts[name];
  11295. var rName = renderedName(name);
  11296. obj[name] = function () {
  11297. return ifEdge(this, spec.get);
  11298. };
  11299. if (spec.mult) {
  11300. obj[rName] = function () {
  11301. return ifEdgeRenderedPositions(this, spec.get);
  11302. };
  11303. } else {
  11304. obj[rName] = function () {
  11305. return ifEdgeRenderedPosition(this, spec.get);
  11306. };
  11307. }
  11308. return obj;
  11309. }, {});
  11310. var dimensions = extend({}, position, bounds, widthHeight, edgePoints);
  11311. /*!
  11312. Event object based on jQuery events, MIT license
  11313. https://jquery.org/license/
  11314. https://tldrlegal.com/license/mit-license
  11315. https://github.com/jquery/jquery/blob/master/src/event.js
  11316. */
  11317. var Event = function Event(src, props) {
  11318. this.recycle(src, props);
  11319. };
  11320. function returnFalse() {
  11321. return false;
  11322. }
  11323. function returnTrue() {
  11324. return true;
  11325. }
  11326. // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  11327. Event.prototype = {
  11328. instanceString: function instanceString() {
  11329. return 'event';
  11330. },
  11331. recycle: function recycle(src, props) {
  11332. this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;
  11333. if (src != null && src.preventDefault) {
  11334. // Browser Event object
  11335. this.type = src.type;
  11336. // Events bubbling up the document may have been marked as prevented
  11337. // by a handler lower down the tree; reflect the correct value.
  11338. this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse;
  11339. } else if (src != null && src.type) {
  11340. // Plain object containing all event details
  11341. props = src;
  11342. } else {
  11343. // Event string
  11344. this.type = src;
  11345. }
  11346. // Put explicitly provided properties onto the event object
  11347. if (props != null) {
  11348. // more efficient to manually copy fields we use
  11349. this.originalEvent = props.originalEvent;
  11350. this.type = props.type != null ? props.type : this.type;
  11351. this.cy = props.cy;
  11352. this.target = props.target;
  11353. this.position = props.position;
  11354. this.renderedPosition = props.renderedPosition;
  11355. this.namespace = props.namespace;
  11356. this.layout = props.layout;
  11357. }
  11358. if (this.cy != null && this.position != null && this.renderedPosition == null) {
  11359. // create a rendered position based on the passed position
  11360. var pos = this.position;
  11361. var zoom = this.cy.zoom();
  11362. var pan = this.cy.pan();
  11363. this.renderedPosition = {
  11364. x: pos.x * zoom + pan.x,
  11365. y: pos.y * zoom + pan.y
  11366. };
  11367. }
  11368. // Create a timestamp if incoming event doesn't have one
  11369. this.timeStamp = src && src.timeStamp || Date.now();
  11370. },
  11371. preventDefault: function preventDefault() {
  11372. this.isDefaultPrevented = returnTrue;
  11373. var e = this.originalEvent;
  11374. if (!e) {
  11375. return;
  11376. }
  11377. // if preventDefault exists run it on the original event
  11378. if (e.preventDefault) {
  11379. e.preventDefault();
  11380. }
  11381. },
  11382. stopPropagation: function stopPropagation() {
  11383. this.isPropagationStopped = returnTrue;
  11384. var e = this.originalEvent;
  11385. if (!e) {
  11386. return;
  11387. }
  11388. // if stopPropagation exists run it on the original event
  11389. if (e.stopPropagation) {
  11390. e.stopPropagation();
  11391. }
  11392. },
  11393. stopImmediatePropagation: function stopImmediatePropagation() {
  11394. this.isImmediatePropagationStopped = returnTrue;
  11395. this.stopPropagation();
  11396. },
  11397. isDefaultPrevented: returnFalse,
  11398. isPropagationStopped: returnFalse,
  11399. isImmediatePropagationStopped: returnFalse
  11400. };
  11401. var eventRegex = /^([^.]+)(\.(?:[^.]+))?$/; // regex for matching event strings (e.g. "click.namespace")
  11402. var universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally
  11403. var defaults$8 = {
  11404. qualifierCompare: function qualifierCompare(q1, q2) {
  11405. return q1 === q2;
  11406. },
  11407. eventMatches: function eventMatches(/*context, listener, eventObj*/
  11408. ) {
  11409. return true;
  11410. },
  11411. addEventFields: function addEventFields(/*context, evt*/
  11412. ) {},
  11413. callbackContext: function callbackContext(context /*, listener, eventObj*/) {
  11414. return context;
  11415. },
  11416. beforeEmit: function beforeEmit(/* context, listener, eventObj */
  11417. ) {},
  11418. afterEmit: function afterEmit(/* context, listener, eventObj */
  11419. ) {},
  11420. bubble: function bubble(/*context*/
  11421. ) {
  11422. return false;
  11423. },
  11424. parent: function parent(/*context*/
  11425. ) {
  11426. return null;
  11427. },
  11428. context: null
  11429. };
  11430. var defaultsKeys = Object.keys(defaults$8);
  11431. var emptyOpts = {};
  11432. function Emitter() {
  11433. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;
  11434. var context = arguments.length > 1 ? arguments[1] : undefined;
  11435. // micro-optimisation vs Object.assign() -- reduces Element instantiation time
  11436. for (var i = 0; i < defaultsKeys.length; i++) {
  11437. var key = defaultsKeys[i];
  11438. this[key] = opts[key] || defaults$8[key];
  11439. }
  11440. this.context = context || this.context;
  11441. this.listeners = [];
  11442. this.emitting = 0;
  11443. }
  11444. var p = Emitter.prototype;
  11445. var forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {
  11446. if (fn$6(qualifier)) {
  11447. callback = qualifier;
  11448. qualifier = null;
  11449. }
  11450. if (confOverrides) {
  11451. if (conf == null) {
  11452. conf = confOverrides;
  11453. } else {
  11454. conf = extend({}, conf, confOverrides);
  11455. }
  11456. }
  11457. var eventList = array(events) ? events : events.split(/\s+/);
  11458. for (var i = 0; i < eventList.length; i++) {
  11459. var evt = eventList[i];
  11460. if (emptyString(evt)) {
  11461. continue;
  11462. }
  11463. var match = evt.match(eventRegex); // type[.namespace]
  11464. if (match) {
  11465. var type = match[1];
  11466. var namespace = match[2] ? match[2] : null;
  11467. var ret = handler(self, evt, type, namespace, qualifier, callback, conf);
  11468. if (ret === false) {
  11469. break;
  11470. } // allow exiting early
  11471. }
  11472. }
  11473. };
  11474. var makeEventObj = function makeEventObj(self, obj) {
  11475. self.addEventFields(self.context, obj);
  11476. return new Event(obj.type, obj);
  11477. };
  11478. var forEachEventObj = function forEachEventObj(self, handler, events) {
  11479. if (event(events)) {
  11480. handler(self, events);
  11481. return;
  11482. } else if (plainObject(events)) {
  11483. handler(self, makeEventObj(self, events));
  11484. return;
  11485. }
  11486. var eventList = array(events) ? events : events.split(/\s+/);
  11487. for (var i = 0; i < eventList.length; i++) {
  11488. var evt = eventList[i];
  11489. if (emptyString(evt)) {
  11490. continue;
  11491. }
  11492. var match = evt.match(eventRegex); // type[.namespace]
  11493. if (match) {
  11494. var type = match[1];
  11495. var namespace = match[2] ? match[2] : null;
  11496. var eventObj = makeEventObj(self, {
  11497. type: type,
  11498. namespace: namespace,
  11499. target: self.context
  11500. });
  11501. handler(self, eventObj);
  11502. }
  11503. }
  11504. };
  11505. p.on = p.addListener = function (events, qualifier, callback, conf, confOverrides) {
  11506. forEachEvent(this, function (self, event, type, namespace, qualifier, callback, conf) {
  11507. if (fn$6(callback)) {
  11508. self.listeners.push({
  11509. event: event,
  11510. // full event string
  11511. callback: callback,
  11512. // callback to run
  11513. type: type,
  11514. // the event type (e.g. 'click')
  11515. namespace: namespace,
  11516. // the event namespace (e.g. ".foo")
  11517. qualifier: qualifier,
  11518. // a restriction on whether to match this emitter
  11519. conf: conf // additional configuration
  11520. });
  11521. }
  11522. }, events, qualifier, callback, conf, confOverrides);
  11523. return this;
  11524. };
  11525. p.one = function (events, qualifier, callback, conf) {
  11526. return this.on(events, qualifier, callback, conf, {
  11527. one: true
  11528. });
  11529. };
  11530. p.removeListener = p.off = function (events, qualifier, callback, conf) {
  11531. var _this = this;
  11532. if (this.emitting !== 0) {
  11533. this.listeners = copyArray(this.listeners);
  11534. }
  11535. var listeners = this.listeners;
  11536. var _loop = function _loop(i) {
  11537. var listener = listeners[i];
  11538. forEachEvent(_this, function (self, event, type, namespace, qualifier, callback /*, conf*/) {
  11539. if ((listener.type === type || events === '*') && (!namespace && listener.namespace !== '.*' || listener.namespace === namespace) && (!qualifier || self.qualifierCompare(listener.qualifier, qualifier)) && (!callback || listener.callback === callback)) {
  11540. listeners.splice(i, 1);
  11541. return false;
  11542. }
  11543. }, events, qualifier, callback, conf);
  11544. };
  11545. for (var i = listeners.length - 1; i >= 0; i--) {
  11546. _loop(i);
  11547. }
  11548. return this;
  11549. };
  11550. p.removeAllListeners = function () {
  11551. return this.removeListener('*');
  11552. };
  11553. p.emit = p.trigger = function (events, extraParams, manualCallback) {
  11554. var listeners = this.listeners;
  11555. var numListenersBeforeEmit = listeners.length;
  11556. this.emitting++;
  11557. if (!array(extraParams)) {
  11558. extraParams = [extraParams];
  11559. }
  11560. forEachEventObj(this, function (self, eventObj) {
  11561. if (manualCallback != null) {
  11562. listeners = [{
  11563. event: eventObj.event,
  11564. type: eventObj.type,
  11565. namespace: eventObj.namespace,
  11566. callback: manualCallback
  11567. }];
  11568. numListenersBeforeEmit = listeners.length;
  11569. }
  11570. var _loop2 = function _loop2() {
  11571. var listener = listeners[i];
  11572. if (listener.type === eventObj.type && (!listener.namespace || listener.namespace === eventObj.namespace || listener.namespace === universalNamespace) && self.eventMatches(self.context, listener, eventObj)) {
  11573. var args = [eventObj];
  11574. if (extraParams != null) {
  11575. push(args, extraParams);
  11576. }
  11577. self.beforeEmit(self.context, listener, eventObj);
  11578. if (listener.conf && listener.conf.one) {
  11579. self.listeners = self.listeners.filter(function (l) {
  11580. return l !== listener;
  11581. });
  11582. }
  11583. var context = self.callbackContext(self.context, listener, eventObj);
  11584. var ret = listener.callback.apply(context, args);
  11585. self.afterEmit(self.context, listener, eventObj);
  11586. if (ret === false) {
  11587. eventObj.stopPropagation();
  11588. eventObj.preventDefault();
  11589. }
  11590. } // if listener matches
  11591. };
  11592. for (var i = 0; i < numListenersBeforeEmit; i++) {
  11593. _loop2();
  11594. } // for listener
  11595. if (self.bubble(self.context) && !eventObj.isPropagationStopped()) {
  11596. self.parent(self.context).emit(eventObj, extraParams);
  11597. }
  11598. }, events);
  11599. this.emitting--;
  11600. return this;
  11601. };
  11602. var emitterOptions$1 = {
  11603. qualifierCompare: function qualifierCompare(selector1, selector2) {
  11604. if (selector1 == null || selector2 == null) {
  11605. return selector1 == null && selector2 == null;
  11606. } else {
  11607. return selector1.sameText(selector2);
  11608. }
  11609. },
  11610. eventMatches: function eventMatches(ele, listener, eventObj) {
  11611. var selector = listener.qualifier;
  11612. if (selector != null) {
  11613. return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
  11614. }
  11615. return true;
  11616. },
  11617. addEventFields: function addEventFields(ele, evt) {
  11618. evt.cy = ele.cy();
  11619. evt.target = ele;
  11620. },
  11621. callbackContext: function callbackContext(ele, listener, eventObj) {
  11622. return listener.qualifier != null ? eventObj.target : ele;
  11623. },
  11624. beforeEmit: function beforeEmit(context, listener /*, eventObj*/) {
  11625. if (listener.conf && listener.conf.once) {
  11626. listener.conf.onceCollection.removeListener(listener.event, listener.qualifier, listener.callback);
  11627. }
  11628. },
  11629. bubble: function bubble() {
  11630. return true;
  11631. },
  11632. parent: function parent(ele) {
  11633. return ele.isChild() ? ele.parent() : ele.cy();
  11634. }
  11635. };
  11636. var argSelector$1 = function argSelector(arg) {
  11637. if (string(arg)) {
  11638. return new Selector(arg);
  11639. } else {
  11640. return arg;
  11641. }
  11642. };
  11643. var elesfn$9 = {
  11644. createEmitter: function createEmitter() {
  11645. for (var i = 0; i < this.length; i++) {
  11646. var ele = this[i];
  11647. var _p = ele._private;
  11648. if (!_p.emitter) {
  11649. _p.emitter = new Emitter(emitterOptions$1, ele);
  11650. }
  11651. }
  11652. return this;
  11653. },
  11654. emitter: function emitter() {
  11655. return this._private.emitter;
  11656. },
  11657. on: function on(events, selector, callback) {
  11658. var argSel = argSelector$1(selector);
  11659. for (var i = 0; i < this.length; i++) {
  11660. var ele = this[i];
  11661. ele.emitter().on(events, argSel, callback);
  11662. }
  11663. return this;
  11664. },
  11665. removeListener: function removeListener(events, selector, callback) {
  11666. var argSel = argSelector$1(selector);
  11667. for (var i = 0; i < this.length; i++) {
  11668. var ele = this[i];
  11669. ele.emitter().removeListener(events, argSel, callback);
  11670. }
  11671. return this;
  11672. },
  11673. removeAllListeners: function removeAllListeners() {
  11674. for (var i = 0; i < this.length; i++) {
  11675. var ele = this[i];
  11676. ele.emitter().removeAllListeners();
  11677. }
  11678. return this;
  11679. },
  11680. one: function one(events, selector, callback) {
  11681. var argSel = argSelector$1(selector);
  11682. for (var i = 0; i < this.length; i++) {
  11683. var ele = this[i];
  11684. ele.emitter().one(events, argSel, callback);
  11685. }
  11686. return this;
  11687. },
  11688. once: function once(events, selector, callback) {
  11689. var argSel = argSelector$1(selector);
  11690. for (var i = 0; i < this.length; i++) {
  11691. var ele = this[i];
  11692. ele.emitter().on(events, argSel, callback, {
  11693. once: true,
  11694. onceCollection: this
  11695. });
  11696. }
  11697. },
  11698. emit: function emit(events, extraParams) {
  11699. for (var i = 0; i < this.length; i++) {
  11700. var ele = this[i];
  11701. ele.emitter().emit(events, extraParams);
  11702. }
  11703. return this;
  11704. },
  11705. emitAndNotify: function emitAndNotify(event, extraParams) {
  11706. // for internal use only
  11707. if (this.length === 0) {
  11708. return;
  11709. } // empty collections don't need to notify anything
  11710. // notify renderer
  11711. this.cy().notify(event, this);
  11712. this.emit(event, extraParams);
  11713. return this;
  11714. }
  11715. };
  11716. define.eventAliasesOn(elesfn$9);
  11717. var elesfn$8 = {
  11718. nodes: function nodes(selector) {
  11719. return this.filter(function (ele) {
  11720. return ele.isNode();
  11721. }).filter(selector);
  11722. },
  11723. edges: function edges(selector) {
  11724. return this.filter(function (ele) {
  11725. return ele.isEdge();
  11726. }).filter(selector);
  11727. },
  11728. // internal helper to get nodes and edges as separate collections with single iteration over elements
  11729. byGroup: function byGroup() {
  11730. var nodes = this.spawn();
  11731. var edges = this.spawn();
  11732. for (var i = 0; i < this.length; i++) {
  11733. var ele = this[i];
  11734. if (ele.isNode()) {
  11735. nodes.push(ele);
  11736. } else {
  11737. edges.push(ele);
  11738. }
  11739. }
  11740. return {
  11741. nodes: nodes,
  11742. edges: edges
  11743. };
  11744. },
  11745. filter: function filter(_filter, thisArg) {
  11746. if (_filter === undefined) {
  11747. // check this first b/c it's the most common/performant case
  11748. return this;
  11749. } else if (string(_filter) || elementOrCollection(_filter)) {
  11750. return new Selector(_filter).filter(this);
  11751. } else if (fn$6(_filter)) {
  11752. var filterEles = this.spawn();
  11753. var eles = this;
  11754. for (var i = 0; i < eles.length; i++) {
  11755. var ele = eles[i];
  11756. var include = thisArg ? _filter.apply(thisArg, [ele, i, eles]) : _filter(ele, i, eles);
  11757. if (include) {
  11758. filterEles.push(ele);
  11759. }
  11760. }
  11761. return filterEles;
  11762. }
  11763. return this.spawn(); // if not handled by above, give 'em an empty collection
  11764. },
  11765. not: function not(toRemove) {
  11766. if (!toRemove) {
  11767. return this;
  11768. } else {
  11769. if (string(toRemove)) {
  11770. toRemove = this.filter(toRemove);
  11771. }
  11772. var elements = this.spawn();
  11773. for (var i = 0; i < this.length; i++) {
  11774. var element = this[i];
  11775. var remove = toRemove.has(element);
  11776. if (!remove) {
  11777. elements.push(element);
  11778. }
  11779. }
  11780. return elements;
  11781. }
  11782. },
  11783. absoluteComplement: function absoluteComplement() {
  11784. var cy = this.cy();
  11785. return cy.mutableElements().not(this);
  11786. },
  11787. intersect: function intersect(other) {
  11788. // if a selector is specified, then filter by it instead
  11789. if (string(other)) {
  11790. var selector = other;
  11791. return this.filter(selector);
  11792. }
  11793. var elements = this.spawn();
  11794. var col1 = this;
  11795. var col2 = other;
  11796. var col1Smaller = this.length < other.length;
  11797. var colS = col1Smaller ? col1 : col2;
  11798. var colL = col1Smaller ? col2 : col1;
  11799. for (var i = 0; i < colS.length; i++) {
  11800. var ele = colS[i];
  11801. if (colL.has(ele)) {
  11802. elements.push(ele);
  11803. }
  11804. }
  11805. return elements;
  11806. },
  11807. xor: function xor(other) {
  11808. var cy = this._private.cy;
  11809. if (string(other)) {
  11810. other = cy.$(other);
  11811. }
  11812. var elements = this.spawn();
  11813. var col1 = this;
  11814. var col2 = other;
  11815. var add = function add(col, other) {
  11816. for (var i = 0; i < col.length; i++) {
  11817. var ele = col[i];
  11818. var id = ele._private.data.id;
  11819. var inOther = other.hasElementWithId(id);
  11820. if (!inOther) {
  11821. elements.push(ele);
  11822. }
  11823. }
  11824. };
  11825. add(col1, col2);
  11826. add(col2, col1);
  11827. return elements;
  11828. },
  11829. diff: function diff(other) {
  11830. var cy = this._private.cy;
  11831. if (string(other)) {
  11832. other = cy.$(other);
  11833. }
  11834. var left = this.spawn();
  11835. var right = this.spawn();
  11836. var both = this.spawn();
  11837. var col1 = this;
  11838. var col2 = other;
  11839. var add = function add(col, other, retEles) {
  11840. for (var i = 0; i < col.length; i++) {
  11841. var ele = col[i];
  11842. var id = ele._private.data.id;
  11843. var inOther = other.hasElementWithId(id);
  11844. if (inOther) {
  11845. both.merge(ele);
  11846. } else {
  11847. retEles.push(ele);
  11848. }
  11849. }
  11850. };
  11851. add(col1, col2, left);
  11852. add(col2, col1, right);
  11853. return {
  11854. left: left,
  11855. right: right,
  11856. both: both
  11857. };
  11858. },
  11859. add: function add(toAdd) {
  11860. var cy = this._private.cy;
  11861. if (!toAdd) {
  11862. return this;
  11863. }
  11864. if (string(toAdd)) {
  11865. var selector = toAdd;
  11866. toAdd = cy.mutableElements().filter(selector);
  11867. }
  11868. var elements = this.spawnSelf();
  11869. for (var i = 0; i < toAdd.length; i++) {
  11870. var ele = toAdd[i];
  11871. var add = !this.has(ele);
  11872. if (add) {
  11873. elements.push(ele);
  11874. }
  11875. }
  11876. return elements;
  11877. },
  11878. // in place merge on calling collection
  11879. merge: function merge(toAdd) {
  11880. var _p = this._private;
  11881. var cy = _p.cy;
  11882. if (!toAdd) {
  11883. return this;
  11884. }
  11885. if (toAdd && string(toAdd)) {
  11886. var selector = toAdd;
  11887. toAdd = cy.mutableElements().filter(selector);
  11888. }
  11889. var map = _p.map;
  11890. for (var i = 0; i < toAdd.length; i++) {
  11891. var toAddEle = toAdd[i];
  11892. var id = toAddEle._private.data.id;
  11893. var add = !map.has(id);
  11894. if (add) {
  11895. var index = this.length++;
  11896. this[index] = toAddEle;
  11897. map.set(id, {
  11898. ele: toAddEle,
  11899. index: index
  11900. });
  11901. }
  11902. }
  11903. return this; // chaining
  11904. },
  11905. unmergeAt: function unmergeAt(i) {
  11906. var ele = this[i];
  11907. var id = ele.id();
  11908. var _p = this._private;
  11909. var map = _p.map;
  11910. // remove ele
  11911. this[i] = undefined;
  11912. map["delete"](id);
  11913. var unmergedLastEle = i === this.length - 1;
  11914. // replace empty spot with last ele in collection
  11915. if (this.length > 1 && !unmergedLastEle) {
  11916. var lastEleI = this.length - 1;
  11917. var lastEle = this[lastEleI];
  11918. var lastEleId = lastEle._private.data.id;
  11919. this[lastEleI] = undefined;
  11920. this[i] = lastEle;
  11921. map.set(lastEleId, {
  11922. ele: lastEle,
  11923. index: i
  11924. });
  11925. }
  11926. // the collection is now 1 ele smaller
  11927. this.length--;
  11928. return this;
  11929. },
  11930. // remove single ele in place in calling collection
  11931. unmergeOne: function unmergeOne(ele) {
  11932. ele = ele[0];
  11933. var _p = this._private;
  11934. var id = ele._private.data.id;
  11935. var map = _p.map;
  11936. var entry = map.get(id);
  11937. if (!entry) {
  11938. return this; // no need to remove
  11939. }
  11940. var i = entry.index;
  11941. this.unmergeAt(i);
  11942. return this;
  11943. },
  11944. // remove eles in place on calling collection
  11945. unmerge: function unmerge(toRemove) {
  11946. var cy = this._private.cy;
  11947. if (!toRemove) {
  11948. return this;
  11949. }
  11950. if (toRemove && string(toRemove)) {
  11951. var selector = toRemove;
  11952. toRemove = cy.mutableElements().filter(selector);
  11953. }
  11954. for (var i = 0; i < toRemove.length; i++) {
  11955. this.unmergeOne(toRemove[i]);
  11956. }
  11957. return this; // chaining
  11958. },
  11959. unmergeBy: function unmergeBy(toRmFn) {
  11960. for (var i = this.length - 1; i >= 0; i--) {
  11961. var ele = this[i];
  11962. if (toRmFn(ele)) {
  11963. this.unmergeAt(i);
  11964. }
  11965. }
  11966. return this;
  11967. },
  11968. map: function map(mapFn, thisArg) {
  11969. var arr = [];
  11970. var eles = this;
  11971. for (var i = 0; i < eles.length; i++) {
  11972. var ele = eles[i];
  11973. var ret = thisArg ? mapFn.apply(thisArg, [ele, i, eles]) : mapFn(ele, i, eles);
  11974. arr.push(ret);
  11975. }
  11976. return arr;
  11977. },
  11978. reduce: function reduce(fn, initialValue) {
  11979. var val = initialValue;
  11980. var eles = this;
  11981. for (var i = 0; i < eles.length; i++) {
  11982. val = fn(val, eles[i], i, eles);
  11983. }
  11984. return val;
  11985. },
  11986. max: function max(valFn, thisArg) {
  11987. var max = -Infinity;
  11988. var maxEle;
  11989. var eles = this;
  11990. for (var i = 0; i < eles.length; i++) {
  11991. var ele = eles[i];
  11992. var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
  11993. if (val > max) {
  11994. max = val;
  11995. maxEle = ele;
  11996. }
  11997. }
  11998. return {
  11999. value: max,
  12000. ele: maxEle
  12001. };
  12002. },
  12003. min: function min(valFn, thisArg) {
  12004. var min = Infinity;
  12005. var minEle;
  12006. var eles = this;
  12007. for (var i = 0; i < eles.length; i++) {
  12008. var ele = eles[i];
  12009. var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
  12010. if (val < min) {
  12011. min = val;
  12012. minEle = ele;
  12013. }
  12014. }
  12015. return {
  12016. value: min,
  12017. ele: minEle
  12018. };
  12019. }
  12020. };
  12021. // aliases
  12022. var fn$1 = elesfn$8;
  12023. fn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;
  12024. fn$1['\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;
  12025. fn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;
  12026. fn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;
  12027. fn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;
  12028. fn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;
  12029. var elesfn$7 = {
  12030. isNode: function isNode() {
  12031. return this.group() === 'nodes';
  12032. },
  12033. isEdge: function isEdge() {
  12034. return this.group() === 'edges';
  12035. },
  12036. isLoop: function isLoop() {
  12037. return this.isEdge() && this.source()[0] === this.target()[0];
  12038. },
  12039. isSimple: function isSimple() {
  12040. return this.isEdge() && this.source()[0] !== this.target()[0];
  12041. },
  12042. group: function group() {
  12043. var ele = this[0];
  12044. if (ele) {
  12045. return ele._private.group;
  12046. }
  12047. }
  12048. };
  12049. /**
  12050. * Elements are drawn in a specific order based on compound depth (low to high), the element type (nodes above edges),
  12051. * and z-index (low to high). These styles affect how this applies:
  12052. *
  12053. * z-compound-depth: May be `bottom | orphan | auto | top`. The first drawn is `bottom`, then `orphan` which is the
  12054. * same depth as the root of the compound graph, followed by the default value `auto` which draws in order from
  12055. * root to leaves of the compound graph. The last drawn is `top`.
  12056. * z-index-compare: May be `auto | manual`. The default value is `auto` which always draws edges under nodes.
  12057. * `manual` ignores this convention and draws based on the `z-index` value setting.
  12058. * z-index: An integer value that affects the relative draw order of elements. In general, an element with a higher
  12059. * `z-index` will be drawn on top of an element with a lower `z-index`.
  12060. */
  12061. var zIndexSort = function zIndexSort(a, b) {
  12062. var cy = a.cy();
  12063. var hasCompoundNodes = cy.hasCompoundNodes();
  12064. function getDepth(ele) {
  12065. var style = ele.pstyle('z-compound-depth');
  12066. if (style.value === 'auto') {
  12067. return hasCompoundNodes ? ele.zDepth() : 0;
  12068. } else if (style.value === 'bottom') {
  12069. return -1;
  12070. } else if (style.value === 'top') {
  12071. return MAX_INT$1;
  12072. }
  12073. // 'orphan'
  12074. return 0;
  12075. }
  12076. var depthDiff = getDepth(a) - getDepth(b);
  12077. if (depthDiff !== 0) {
  12078. return depthDiff;
  12079. }
  12080. function getEleDepth(ele) {
  12081. var style = ele.pstyle('z-index-compare');
  12082. if (style.value === 'auto') {
  12083. return ele.isNode() ? 1 : 0;
  12084. }
  12085. // 'manual'
  12086. return 0;
  12087. }
  12088. var eleDiff = getEleDepth(a) - getEleDepth(b);
  12089. if (eleDiff !== 0) {
  12090. return eleDiff;
  12091. }
  12092. var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;
  12093. if (zDiff !== 0) {
  12094. return zDiff;
  12095. }
  12096. // compare indices in the core (order added to graph w/ last on top)
  12097. return a.poolIndex() - b.poolIndex();
  12098. };
  12099. var elesfn$6 = {
  12100. forEach: function forEach(fn, thisArg) {
  12101. if (fn$6(fn)) {
  12102. var N = this.length;
  12103. for (var i = 0; i < N; i++) {
  12104. var ele = this[i];
  12105. var ret = thisArg ? fn.apply(thisArg, [ele, i, this]) : fn(ele, i, this);
  12106. if (ret === false) {
  12107. break;
  12108. } // exit each early on return false
  12109. }
  12110. }
  12111. return this;
  12112. },
  12113. toArray: function toArray() {
  12114. var array = [];
  12115. for (var i = 0; i < this.length; i++) {
  12116. array.push(this[i]);
  12117. }
  12118. return array;
  12119. },
  12120. slice: function slice(start, end) {
  12121. var array = [];
  12122. var thisSize = this.length;
  12123. if (end == null) {
  12124. end = thisSize;
  12125. }
  12126. if (start == null) {
  12127. start = 0;
  12128. }
  12129. if (start < 0) {
  12130. start = thisSize + start;
  12131. }
  12132. if (end < 0) {
  12133. end = thisSize + end;
  12134. }
  12135. for (var i = start; i >= 0 && i < end && i < thisSize; i++) {
  12136. array.push(this[i]);
  12137. }
  12138. return this.spawn(array);
  12139. },
  12140. size: function size() {
  12141. return this.length;
  12142. },
  12143. eq: function eq(i) {
  12144. return this[i] || this.spawn();
  12145. },
  12146. first: function first() {
  12147. return this[0] || this.spawn();
  12148. },
  12149. last: function last() {
  12150. return this[this.length - 1] || this.spawn();
  12151. },
  12152. empty: function empty() {
  12153. return this.length === 0;
  12154. },
  12155. nonempty: function nonempty() {
  12156. return !this.empty();
  12157. },
  12158. sort: function sort(sortFn) {
  12159. if (!fn$6(sortFn)) {
  12160. return this;
  12161. }
  12162. var sorted = this.toArray().sort(sortFn);
  12163. return this.spawn(sorted);
  12164. },
  12165. sortByZIndex: function sortByZIndex() {
  12166. return this.sort(zIndexSort);
  12167. },
  12168. zDepth: function zDepth() {
  12169. var ele = this[0];
  12170. if (!ele) {
  12171. return undefined;
  12172. }
  12173. // let cy = ele.cy();
  12174. var _p = ele._private;
  12175. var group = _p.group;
  12176. if (group === 'nodes') {
  12177. var depth = _p.data.parent ? ele.parents().size() : 0;
  12178. if (!ele.isParent()) {
  12179. return MAX_INT$1 - 1; // childless nodes always on top
  12180. }
  12181. return depth;
  12182. } else {
  12183. var src = _p.source;
  12184. var tgt = _p.target;
  12185. var srcDepth = src.zDepth();
  12186. var tgtDepth = tgt.zDepth();
  12187. return Math.max(srcDepth, tgtDepth, 0); // depth of deepest parent
  12188. }
  12189. }
  12190. };
  12191. elesfn$6.each = elesfn$6.forEach;
  12192. var defineSymbolIterator = function defineSymbolIterator() {
  12193. var typeofUndef = "undefined" ;
  12194. var isIteratorSupported = (typeof Symbol === "undefined" ? "undefined" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef;
  12195. if (isIteratorSupported) {
  12196. elesfn$6[Symbol.iterator] = function () {
  12197. var _this = this;
  12198. var entry = {
  12199. value: undefined,
  12200. done: false
  12201. };
  12202. var i = 0;
  12203. var length = this.length;
  12204. return _defineProperty$1({
  12205. next: function next() {
  12206. if (i < length) {
  12207. entry.value = _this[i++];
  12208. } else {
  12209. entry.value = undefined;
  12210. entry.done = true;
  12211. }
  12212. return entry;
  12213. }
  12214. }, Symbol.iterator, function () {
  12215. return this;
  12216. });
  12217. };
  12218. }
  12219. };
  12220. defineSymbolIterator();
  12221. var getLayoutDimensionOptions = defaults$g({
  12222. nodeDimensionsIncludeLabels: false
  12223. });
  12224. var elesfn$5 = {
  12225. // Calculates and returns node dimensions { x, y } based on options given
  12226. layoutDimensions: function layoutDimensions(options) {
  12227. options = getLayoutDimensionOptions(options);
  12228. var dims;
  12229. if (!this.takesUpSpace()) {
  12230. dims = {
  12231. w: 0,
  12232. h: 0
  12233. };
  12234. } else if (options.nodeDimensionsIncludeLabels) {
  12235. var bbDim = this.boundingBox();
  12236. dims = {
  12237. w: bbDim.w,
  12238. h: bbDim.h
  12239. };
  12240. } else {
  12241. dims = {
  12242. w: this.outerWidth(),
  12243. h: this.outerHeight()
  12244. };
  12245. }
  12246. // sanitise the dimensions for external layouts (avoid division by zero)
  12247. if (dims.w === 0 || dims.h === 0) {
  12248. dims.w = dims.h = 1;
  12249. }
  12250. return dims;
  12251. },
  12252. // using standard layout options, apply position function (w/ or w/o animation)
  12253. layoutPositions: function layoutPositions(layout, options, fn) {
  12254. var nodes = this.nodes().filter(function (n) {
  12255. return !n.isParent();
  12256. });
  12257. var cy = this.cy();
  12258. var layoutEles = options.eles; // nodes & edges
  12259. var getMemoizeKey = function getMemoizeKey(node) {
  12260. return node.id();
  12261. };
  12262. var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function
  12263. layout.emit({
  12264. type: 'layoutstart',
  12265. layout: layout
  12266. });
  12267. layout.animations = [];
  12268. var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) {
  12269. var center = {
  12270. x: nodesBb.x1 + nodesBb.w / 2,
  12271. y: nodesBb.y1 + nodesBb.h / 2
  12272. };
  12273. var spacingVector = {
  12274. // scale from center of bounding box (not necessarily 0,0)
  12275. x: (pos.x - center.x) * spacing,
  12276. y: (pos.y - center.y) * spacing
  12277. };
  12278. return {
  12279. x: center.x + spacingVector.x,
  12280. y: center.y + spacingVector.y
  12281. };
  12282. };
  12283. var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;
  12284. var spacingBb = function spacingBb() {
  12285. if (!useSpacingFactor) {
  12286. return null;
  12287. }
  12288. var bb = makeBoundingBox();
  12289. for (var i = 0; i < nodes.length; i++) {
  12290. var node = nodes[i];
  12291. var pos = fnMem(node, i);
  12292. expandBoundingBoxByPoint(bb, pos.x, pos.y);
  12293. }
  12294. return bb;
  12295. };
  12296. var bb = spacingBb();
  12297. var getFinalPos = memoize(function (node, i) {
  12298. var newPos = fnMem(node, i);
  12299. if (useSpacingFactor) {
  12300. var spacing = Math.abs(options.spacingFactor);
  12301. newPos = calculateSpacing(spacing, bb, newPos);
  12302. }
  12303. if (options.transform != null) {
  12304. newPos = options.transform(node, newPos);
  12305. }
  12306. return newPos;
  12307. }, getMemoizeKey);
  12308. if (options.animate) {
  12309. for (var i = 0; i < nodes.length; i++) {
  12310. var node = nodes[i];
  12311. var newPos = getFinalPos(node, i);
  12312. var animateNode = options.animateFilter == null || options.animateFilter(node, i);
  12313. if (animateNode) {
  12314. var ani = node.animation({
  12315. position: newPos,
  12316. duration: options.animationDuration,
  12317. easing: options.animationEasing
  12318. });
  12319. layout.animations.push(ani);
  12320. } else {
  12321. node.position(newPos);
  12322. }
  12323. }
  12324. if (options.fit) {
  12325. var fitAni = cy.animation({
  12326. fit: {
  12327. boundingBox: layoutEles.boundingBoxAt(getFinalPos),
  12328. padding: options.padding
  12329. },
  12330. duration: options.animationDuration,
  12331. easing: options.animationEasing
  12332. });
  12333. layout.animations.push(fitAni);
  12334. } else if (options.zoom !== undefined && options.pan !== undefined) {
  12335. var zoomPanAni = cy.animation({
  12336. zoom: options.zoom,
  12337. pan: options.pan,
  12338. duration: options.animationDuration,
  12339. easing: options.animationEasing
  12340. });
  12341. layout.animations.push(zoomPanAni);
  12342. }
  12343. layout.animations.forEach(function (ani) {
  12344. return ani.play();
  12345. });
  12346. layout.one('layoutready', options.ready);
  12347. layout.emit({
  12348. type: 'layoutready',
  12349. layout: layout
  12350. });
  12351. Promise$1.all(layout.animations.map(function (ani) {
  12352. return ani.promise();
  12353. })).then(function () {
  12354. layout.one('layoutstop', options.stop);
  12355. layout.emit({
  12356. type: 'layoutstop',
  12357. layout: layout
  12358. });
  12359. });
  12360. } else {
  12361. nodes.positions(getFinalPos);
  12362. if (options.fit) {
  12363. cy.fit(options.eles, options.padding);
  12364. }
  12365. if (options.zoom != null) {
  12366. cy.zoom(options.zoom);
  12367. }
  12368. if (options.pan) {
  12369. cy.pan(options.pan);
  12370. }
  12371. layout.one('layoutready', options.ready);
  12372. layout.emit({
  12373. type: 'layoutready',
  12374. layout: layout
  12375. });
  12376. layout.one('layoutstop', options.stop);
  12377. layout.emit({
  12378. type: 'layoutstop',
  12379. layout: layout
  12380. });
  12381. }
  12382. return this; // chaining
  12383. },
  12384. layout: function layout(options) {
  12385. var cy = this.cy();
  12386. return cy.makeLayout(extend({}, options, {
  12387. eles: this
  12388. }));
  12389. }
  12390. };
  12391. // aliases:
  12392. elesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;
  12393. function styleCache(key, fn, ele) {
  12394. var _p = ele._private;
  12395. var cache = _p.styleCache = _p.styleCache || [];
  12396. var val;
  12397. if ((val = cache[key]) != null) {
  12398. return val;
  12399. } else {
  12400. val = cache[key] = fn(ele);
  12401. return val;
  12402. }
  12403. }
  12404. function cacheStyleFunction(key, fn) {
  12405. key = hashString(key);
  12406. return function cachedStyleFunction(ele) {
  12407. return styleCache(key, fn, ele);
  12408. };
  12409. }
  12410. function cachePrototypeStyleFunction(key, fn) {
  12411. key = hashString(key);
  12412. var selfFn = function selfFn(ele) {
  12413. return fn.call(ele);
  12414. };
  12415. return function cachedPrototypeStyleFunction() {
  12416. var ele = this[0];
  12417. if (ele) {
  12418. return styleCache(key, selfFn, ele);
  12419. }
  12420. };
  12421. }
  12422. var elesfn$4 = {
  12423. recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {
  12424. var cy = this.cy();
  12425. var renderer = cy.renderer();
  12426. var styleEnabled = cy.styleEnabled();
  12427. if (renderer && styleEnabled) {
  12428. renderer.recalculateRenderedStyle(this, useCache);
  12429. }
  12430. return this;
  12431. },
  12432. dirtyStyleCache: function dirtyStyleCache() {
  12433. var cy = this.cy();
  12434. var dirty = function dirty(ele) {
  12435. return ele._private.styleCache = null;
  12436. };
  12437. if (cy.hasCompoundNodes()) {
  12438. var eles;
  12439. eles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
  12440. eles.merge(eles.connectedEdges());
  12441. eles.forEach(dirty);
  12442. } else {
  12443. this.forEach(function (ele) {
  12444. dirty(ele);
  12445. ele.connectedEdges().forEach(dirty);
  12446. });
  12447. }
  12448. return this;
  12449. },
  12450. // fully updates (recalculates) the style for the elements
  12451. updateStyle: function updateStyle(notifyRenderer) {
  12452. var cy = this._private.cy;
  12453. if (!cy.styleEnabled()) {
  12454. return this;
  12455. }
  12456. if (cy.batching()) {
  12457. var bEles = cy._private.batchStyleEles;
  12458. bEles.merge(this);
  12459. return this; // chaining and exit early when batching
  12460. }
  12461. var hasCompounds = cy.hasCompoundNodes();
  12462. var updatedEles = this;
  12463. notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;
  12464. if (hasCompounds) {
  12465. // then add everything up and down for compound selector checks
  12466. updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
  12467. }
  12468. // let changedEles = style.apply( updatedEles );
  12469. var changedEles = updatedEles;
  12470. if (notifyRenderer) {
  12471. changedEles.emitAndNotify('style'); // let renderer know we changed style
  12472. } else {
  12473. changedEles.emit('style'); // just fire the event
  12474. }
  12475. updatedEles.forEach(function (ele) {
  12476. return ele._private.styleDirty = true;
  12477. });
  12478. return this; // chaining
  12479. },
  12480. // private: clears dirty flag and recalculates style
  12481. cleanStyle: function cleanStyle() {
  12482. var cy = this.cy();
  12483. if (!cy.styleEnabled()) {
  12484. return;
  12485. }
  12486. for (var i = 0; i < this.length; i++) {
  12487. var ele = this[i];
  12488. if (ele._private.styleDirty) {
  12489. // n.b. this flag should be set before apply() to avoid potential infinite recursion
  12490. ele._private.styleDirty = false;
  12491. cy.style().apply(ele);
  12492. }
  12493. }
  12494. },
  12495. // get the internal parsed style object for the specified property
  12496. parsedStyle: function parsedStyle(property) {
  12497. var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  12498. var ele = this[0];
  12499. var cy = ele.cy();
  12500. if (!cy.styleEnabled()) {
  12501. return;
  12502. }
  12503. if (ele) {
  12504. // this.cleanStyle();
  12505. // Inline the important part of cleanStyle(), for raw performance
  12506. if (ele._private.styleDirty) {
  12507. // n.b. this flag should be set before apply() to avoid potential infinite recursion
  12508. ele._private.styleDirty = false;
  12509. cy.style().apply(ele);
  12510. }
  12511. var overriddenStyle = ele._private.style[property];
  12512. if (overriddenStyle != null) {
  12513. return overriddenStyle;
  12514. } else if (includeNonDefault) {
  12515. return cy.style().getDefaultProperty(property);
  12516. } else {
  12517. return null;
  12518. }
  12519. }
  12520. },
  12521. numericStyle: function numericStyle(property) {
  12522. var ele = this[0];
  12523. if (!ele.cy().styleEnabled()) {
  12524. return;
  12525. }
  12526. if (ele) {
  12527. var pstyle = ele.pstyle(property);
  12528. return pstyle.pfValue !== undefined ? pstyle.pfValue : pstyle.value;
  12529. }
  12530. },
  12531. numericStyleUnits: function numericStyleUnits(property) {
  12532. var ele = this[0];
  12533. if (!ele.cy().styleEnabled()) {
  12534. return;
  12535. }
  12536. if (ele) {
  12537. return ele.pstyle(property).units;
  12538. }
  12539. },
  12540. // get the specified css property as a rendered value (i.e. on-screen value)
  12541. // or get the whole rendered style if no property specified (NB doesn't allow setting)
  12542. renderedStyle: function renderedStyle(property) {
  12543. var cy = this.cy();
  12544. if (!cy.styleEnabled()) {
  12545. return this;
  12546. }
  12547. var ele = this[0];
  12548. if (ele) {
  12549. return cy.style().getRenderedStyle(ele, property);
  12550. }
  12551. },
  12552. // read the calculated css style of the element or override the style (via a bypass)
  12553. style: function style(name, value) {
  12554. var cy = this.cy();
  12555. if (!cy.styleEnabled()) {
  12556. return this;
  12557. }
  12558. var updateTransitions = false;
  12559. var style = cy.style();
  12560. if (plainObject(name)) {
  12561. // then extend the bypass
  12562. var props = name;
  12563. style.applyBypass(this, props, updateTransitions);
  12564. this.emitAndNotify('style'); // let the renderer know we've updated style
  12565. } else if (string(name)) {
  12566. if (value === undefined) {
  12567. // then get the property from the style
  12568. var ele = this[0];
  12569. if (ele) {
  12570. return style.getStylePropertyValue(ele, name);
  12571. } else {
  12572. // empty collection => can't get any value
  12573. return;
  12574. }
  12575. } else {
  12576. // then set the bypass with the property value
  12577. style.applyBypass(this, name, value, updateTransitions);
  12578. this.emitAndNotify('style'); // let the renderer know we've updated style
  12579. }
  12580. } else if (name === undefined) {
  12581. var _ele = this[0];
  12582. if (_ele) {
  12583. return style.getRawStyle(_ele);
  12584. } else {
  12585. // empty collection => can't get any value
  12586. return;
  12587. }
  12588. }
  12589. return this; // chaining
  12590. },
  12591. removeStyle: function removeStyle(names) {
  12592. var cy = this.cy();
  12593. if (!cy.styleEnabled()) {
  12594. return this;
  12595. }
  12596. var updateTransitions = false;
  12597. var style = cy.style();
  12598. var eles = this;
  12599. if (names === undefined) {
  12600. for (var i = 0; i < eles.length; i++) {
  12601. var ele = eles[i];
  12602. style.removeAllBypasses(ele, updateTransitions);
  12603. }
  12604. } else {
  12605. names = names.split(/\s+/);
  12606. for (var _i = 0; _i < eles.length; _i++) {
  12607. var _ele2 = eles[_i];
  12608. style.removeBypasses(_ele2, names, updateTransitions);
  12609. }
  12610. }
  12611. this.emitAndNotify('style'); // let the renderer know we've updated style
  12612. return this; // chaining
  12613. },
  12614. show: function show() {
  12615. this.css('display', 'element');
  12616. return this; // chaining
  12617. },
  12618. hide: function hide() {
  12619. this.css('display', 'none');
  12620. return this; // chaining
  12621. },
  12622. effectiveOpacity: function effectiveOpacity() {
  12623. var cy = this.cy();
  12624. if (!cy.styleEnabled()) {
  12625. return 1;
  12626. }
  12627. var hasCompoundNodes = cy.hasCompoundNodes();
  12628. var ele = this[0];
  12629. if (ele) {
  12630. var _p = ele._private;
  12631. var parentOpacity = ele.pstyle('opacity').value;
  12632. if (!hasCompoundNodes) {
  12633. return parentOpacity;
  12634. }
  12635. var parents = !_p.data.parent ? null : ele.parents();
  12636. if (parents) {
  12637. for (var i = 0; i < parents.length; i++) {
  12638. var parent = parents[i];
  12639. var opacity = parent.pstyle('opacity').value;
  12640. parentOpacity = opacity * parentOpacity;
  12641. }
  12642. }
  12643. return parentOpacity;
  12644. }
  12645. },
  12646. transparent: function transparent() {
  12647. var cy = this.cy();
  12648. if (!cy.styleEnabled()) {
  12649. return false;
  12650. }
  12651. var ele = this[0];
  12652. var hasCompoundNodes = ele.cy().hasCompoundNodes();
  12653. if (ele) {
  12654. if (!hasCompoundNodes) {
  12655. return ele.pstyle('opacity').value === 0;
  12656. } else {
  12657. return ele.effectiveOpacity() === 0;
  12658. }
  12659. }
  12660. },
  12661. backgrounding: function backgrounding() {
  12662. var cy = this.cy();
  12663. if (!cy.styleEnabled()) {
  12664. return false;
  12665. }
  12666. var ele = this[0];
  12667. return ele._private.backgrounding ? true : false;
  12668. }
  12669. };
  12670. function checkCompound(ele, parentOk) {
  12671. var _p = ele._private;
  12672. var parents = _p.data.parent ? ele.parents() : null;
  12673. if (parents) {
  12674. for (var i = 0; i < parents.length; i++) {
  12675. var parent = parents[i];
  12676. if (!parentOk(parent)) {
  12677. return false;
  12678. }
  12679. }
  12680. }
  12681. return true;
  12682. }
  12683. function defineDerivedStateFunction(specs) {
  12684. var ok = specs.ok;
  12685. var edgeOkViaNode = specs.edgeOkViaNode || specs.ok;
  12686. var parentOk = specs.parentOk || specs.ok;
  12687. return function () {
  12688. var cy = this.cy();
  12689. if (!cy.styleEnabled()) {
  12690. return true;
  12691. }
  12692. var ele = this[0];
  12693. var hasCompoundNodes = cy.hasCompoundNodes();
  12694. if (ele) {
  12695. var _p = ele._private;
  12696. if (!ok(ele)) {
  12697. return false;
  12698. }
  12699. if (ele.isNode()) {
  12700. return !hasCompoundNodes || checkCompound(ele, parentOk);
  12701. } else {
  12702. var src = _p.source;
  12703. var tgt = _p.target;
  12704. return edgeOkViaNode(src) && (!hasCompoundNodes || checkCompound(src, edgeOkViaNode)) && (src === tgt || edgeOkViaNode(tgt) && (!hasCompoundNodes || checkCompound(tgt, edgeOkViaNode)));
  12705. }
  12706. }
  12707. };
  12708. }
  12709. var eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {
  12710. return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);
  12711. });
  12712. elesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({
  12713. ok: eleTakesUpSpace
  12714. }));
  12715. var eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {
  12716. return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);
  12717. });
  12718. var parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {
  12719. return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);
  12720. });
  12721. elesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({
  12722. ok: eleInteractive,
  12723. parentOk: parentInteractive,
  12724. edgeOkViaNode: eleTakesUpSpace
  12725. }));
  12726. elesfn$4.noninteractive = function () {
  12727. var ele = this[0];
  12728. if (ele) {
  12729. return !ele.interactive();
  12730. }
  12731. };
  12732. var eleVisible = cacheStyleFunction('eleVisible', function (ele) {
  12733. return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);
  12734. });
  12735. var edgeVisibleViaNode = eleTakesUpSpace;
  12736. elesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({
  12737. ok: eleVisible,
  12738. edgeOkViaNode: edgeVisibleViaNode
  12739. }));
  12740. elesfn$4.hidden = function () {
  12741. var ele = this[0];
  12742. if (ele) {
  12743. return !ele.visible();
  12744. }
  12745. };
  12746. elesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {
  12747. if (!this.cy().styleEnabled()) {
  12748. return false;
  12749. }
  12750. return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();
  12751. });
  12752. elesfn$4.bypass = elesfn$4.css = elesfn$4.style;
  12753. elesfn$4.renderedCss = elesfn$4.renderedStyle;
  12754. elesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;
  12755. elesfn$4.pstyle = elesfn$4.parsedStyle;
  12756. var elesfn$3 = {};
  12757. function defineSwitchFunction(params) {
  12758. return function () {
  12759. var args = arguments;
  12760. var changedEles = [];
  12761. // e.g. cy.nodes().select( data, handler )
  12762. if (args.length === 2) {
  12763. var data = args[0];
  12764. var handler = args[1];
  12765. this.on(params.event, data, handler);
  12766. }
  12767. // e.g. cy.nodes().select( handler )
  12768. else if (args.length === 1 && fn$6(args[0])) {
  12769. var _handler = args[0];
  12770. this.on(params.event, _handler);
  12771. }
  12772. // e.g. cy.nodes().select()
  12773. // e.g. (private) cy.nodes().select(['tapselect'])
  12774. else if (args.length === 0 || args.length === 1 && array(args[0])) {
  12775. var addlEvents = args.length === 1 ? args[0] : null;
  12776. for (var i = 0; i < this.length; i++) {
  12777. var ele = this[i];
  12778. var able = !params.ableField || ele._private[params.ableField];
  12779. var changed = ele._private[params.field] != params.value;
  12780. if (params.overrideAble) {
  12781. var overrideAble = params.overrideAble(ele);
  12782. if (overrideAble !== undefined) {
  12783. able = overrideAble;
  12784. if (!overrideAble) {
  12785. return this;
  12786. } // to save cycles assume not able for all on override
  12787. }
  12788. }
  12789. if (able) {
  12790. ele._private[params.field] = params.value;
  12791. if (changed) {
  12792. changedEles.push(ele);
  12793. }
  12794. }
  12795. }
  12796. var changedColl = this.spawn(changedEles);
  12797. changedColl.updateStyle(); // change of state => possible change of style
  12798. changedColl.emit(params.event);
  12799. if (addlEvents) {
  12800. changedColl.emit(addlEvents);
  12801. }
  12802. }
  12803. return this;
  12804. };
  12805. }
  12806. function defineSwitchSet(params) {
  12807. elesfn$3[params.field] = function () {
  12808. var ele = this[0];
  12809. if (ele) {
  12810. if (params.overrideField) {
  12811. var val = params.overrideField(ele);
  12812. if (val !== undefined) {
  12813. return val;
  12814. }
  12815. }
  12816. return ele._private[params.field];
  12817. }
  12818. };
  12819. elesfn$3[params.on] = defineSwitchFunction({
  12820. event: params.on,
  12821. field: params.field,
  12822. ableField: params.ableField,
  12823. overrideAble: params.overrideAble,
  12824. value: true
  12825. });
  12826. elesfn$3[params.off] = defineSwitchFunction({
  12827. event: params.off,
  12828. field: params.field,
  12829. ableField: params.ableField,
  12830. overrideAble: params.overrideAble,
  12831. value: false
  12832. });
  12833. }
  12834. defineSwitchSet({
  12835. field: 'locked',
  12836. overrideField: function overrideField(ele) {
  12837. return ele.cy().autolock() ? true : undefined;
  12838. },
  12839. on: 'lock',
  12840. off: 'unlock'
  12841. });
  12842. defineSwitchSet({
  12843. field: 'grabbable',
  12844. overrideField: function overrideField(ele) {
  12845. return ele.cy().autoungrabify() || ele.pannable() ? false : undefined;
  12846. },
  12847. on: 'grabify',
  12848. off: 'ungrabify'
  12849. });
  12850. defineSwitchSet({
  12851. field: 'selected',
  12852. ableField: 'selectable',
  12853. overrideAble: function overrideAble(ele) {
  12854. return ele.cy().autounselectify() ? false : undefined;
  12855. },
  12856. on: 'select',
  12857. off: 'unselect'
  12858. });
  12859. defineSwitchSet({
  12860. field: 'selectable',
  12861. overrideField: function overrideField(ele) {
  12862. return ele.cy().autounselectify() ? false : undefined;
  12863. },
  12864. on: 'selectify',
  12865. off: 'unselectify'
  12866. });
  12867. elesfn$3.deselect = elesfn$3.unselect;
  12868. elesfn$3.grabbed = function () {
  12869. var ele = this[0];
  12870. if (ele) {
  12871. return ele._private.grabbed;
  12872. }
  12873. };
  12874. defineSwitchSet({
  12875. field: 'active',
  12876. on: 'activate',
  12877. off: 'unactivate'
  12878. });
  12879. defineSwitchSet({
  12880. field: 'pannable',
  12881. on: 'panify',
  12882. off: 'unpanify'
  12883. });
  12884. elesfn$3.inactive = function () {
  12885. var ele = this[0];
  12886. if (ele) {
  12887. return !ele._private.active;
  12888. }
  12889. };
  12890. var elesfn$2 = {};
  12891. // DAG functions
  12892. ////////////////
  12893. var defineDagExtremity = function defineDagExtremity(params) {
  12894. return function dagExtremityImpl(selector) {
  12895. var eles = this;
  12896. var ret = [];
  12897. for (var i = 0; i < eles.length; i++) {
  12898. var ele = eles[i];
  12899. if (!ele.isNode()) {
  12900. continue;
  12901. }
  12902. var disqualified = false;
  12903. var edges = ele.connectedEdges();
  12904. for (var j = 0; j < edges.length; j++) {
  12905. var edge = edges[j];
  12906. var src = edge.source();
  12907. var tgt = edge.target();
  12908. if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {
  12909. disqualified = true;
  12910. break;
  12911. }
  12912. }
  12913. if (!disqualified) {
  12914. ret.push(ele);
  12915. }
  12916. }
  12917. return this.spawn(ret, true).filter(selector);
  12918. };
  12919. };
  12920. var defineDagOneHop = function defineDagOneHop(params) {
  12921. return function (selector) {
  12922. var eles = this;
  12923. var oEles = [];
  12924. for (var i = 0; i < eles.length; i++) {
  12925. var ele = eles[i];
  12926. if (!ele.isNode()) {
  12927. continue;
  12928. }
  12929. var edges = ele.connectedEdges();
  12930. for (var j = 0; j < edges.length; j++) {
  12931. var edge = edges[j];
  12932. var src = edge.source();
  12933. var tgt = edge.target();
  12934. if (params.outgoing && src === ele) {
  12935. oEles.push(edge);
  12936. oEles.push(tgt);
  12937. } else if (params.incoming && tgt === ele) {
  12938. oEles.push(edge);
  12939. oEles.push(src);
  12940. }
  12941. }
  12942. }
  12943. return this.spawn(oEles, true).filter(selector);
  12944. };
  12945. };
  12946. var defineDagAllHops = function defineDagAllHops(params) {
  12947. return function (selector) {
  12948. var eles = this;
  12949. var sEles = [];
  12950. var sElesIds = {};
  12951. for (;;) {
  12952. var next = params.outgoing ? eles.outgoers() : eles.incomers();
  12953. if (next.length === 0) {
  12954. break;
  12955. } // done if none left
  12956. var newNext = false;
  12957. for (var i = 0; i < next.length; i++) {
  12958. var n = next[i];
  12959. var nid = n.id();
  12960. if (!sElesIds[nid]) {
  12961. sElesIds[nid] = true;
  12962. sEles.push(n);
  12963. newNext = true;
  12964. }
  12965. }
  12966. if (!newNext) {
  12967. break;
  12968. } // done if touched all outgoers already
  12969. eles = next;
  12970. }
  12971. return this.spawn(sEles, true).filter(selector);
  12972. };
  12973. };
  12974. elesfn$2.clearTraversalCache = function () {
  12975. for (var i = 0; i < this.length; i++) {
  12976. this[i]._private.traversalCache = null;
  12977. }
  12978. };
  12979. extend(elesfn$2, {
  12980. // get the root nodes in the DAG
  12981. roots: defineDagExtremity({
  12982. noIncomingEdges: true
  12983. }),
  12984. // get the leaf nodes in the DAG
  12985. leaves: defineDagExtremity({
  12986. noOutgoingEdges: true
  12987. }),
  12988. // normally called children in graph theory
  12989. // these nodes =edges=> outgoing nodes
  12990. outgoers: cache(defineDagOneHop({
  12991. outgoing: true
  12992. }), 'outgoers'),
  12993. // aka DAG descendants
  12994. successors: defineDagAllHops({
  12995. outgoing: true
  12996. }),
  12997. // normally called parents in graph theory
  12998. // these nodes <=edges= incoming nodes
  12999. incomers: cache(defineDagOneHop({
  13000. incoming: true
  13001. }), 'incomers'),
  13002. // aka DAG ancestors
  13003. predecessors: defineDagAllHops({
  13004. })
  13005. });
  13006. // Neighbourhood functions
  13007. //////////////////////////
  13008. extend(elesfn$2, {
  13009. neighborhood: cache(function (selector) {
  13010. var elements = [];
  13011. var nodes = this.nodes();
  13012. for (var i = 0; i < nodes.length; i++) {
  13013. // for all nodes
  13014. var node = nodes[i];
  13015. var connectedEdges = node.connectedEdges();
  13016. // for each connected edge, add the edge and the other node
  13017. for (var j = 0; j < connectedEdges.length; j++) {
  13018. var edge = connectedEdges[j];
  13019. var src = edge.source();
  13020. var tgt = edge.target();
  13021. var otherNode = node === src ? tgt : src;
  13022. // need check in case of loop
  13023. if (otherNode.length > 0) {
  13024. elements.push(otherNode[0]); // add node 1 hop away
  13025. }
  13026. // add connected edge
  13027. elements.push(edge[0]);
  13028. }
  13029. }
  13030. return this.spawn(elements, true).filter(selector);
  13031. }, 'neighborhood'),
  13032. closedNeighborhood: function closedNeighborhood(selector) {
  13033. return this.neighborhood().add(this).filter(selector);
  13034. },
  13035. openNeighborhood: function openNeighborhood(selector) {
  13036. return this.neighborhood(selector);
  13037. }
  13038. });
  13039. // aliases
  13040. elesfn$2.neighbourhood = elesfn$2.neighborhood;
  13041. elesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;
  13042. elesfn$2.openNeighbourhood = elesfn$2.openNeighborhood;
  13043. // Edge functions
  13044. /////////////////
  13045. extend(elesfn$2, {
  13046. source: cache(function sourceImpl(selector) {
  13047. var ele = this[0];
  13048. var src;
  13049. if (ele) {
  13050. src = ele._private.source || ele.cy().collection();
  13051. }
  13052. return src && selector ? src.filter(selector) : src;
  13053. }, 'source'),
  13054. target: cache(function targetImpl(selector) {
  13055. var ele = this[0];
  13056. var tgt;
  13057. if (ele) {
  13058. tgt = ele._private.target || ele.cy().collection();
  13059. }
  13060. return tgt && selector ? tgt.filter(selector) : tgt;
  13061. }, 'target'),
  13062. sources: defineSourceFunction({
  13063. attr: 'source'
  13064. }),
  13065. targets: defineSourceFunction({
  13066. attr: 'target'
  13067. })
  13068. });
  13069. function defineSourceFunction(params) {
  13070. return function sourceImpl(selector) {
  13071. var sources = [];
  13072. for (var i = 0; i < this.length; i++) {
  13073. var ele = this[i];
  13074. var src = ele._private[params.attr];
  13075. if (src) {
  13076. sources.push(src);
  13077. }
  13078. }
  13079. return this.spawn(sources, true).filter(selector);
  13080. };
  13081. }
  13082. extend(elesfn$2, {
  13083. edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),
  13084. edgesTo: cache(defineEdgesWithFunction({
  13085. thisIsSrc: true
  13086. }), 'edgesTo')
  13087. });
  13088. function defineEdgesWithFunction(params) {
  13089. return function edgesWithImpl(otherNodes) {
  13090. var elements = [];
  13091. var cy = this._private.cy;
  13092. var p = params || {};
  13093. // get elements if a selector is specified
  13094. if (string(otherNodes)) {
  13095. otherNodes = cy.$(otherNodes);
  13096. }
  13097. for (var h = 0; h < otherNodes.length; h++) {
  13098. var edges = otherNodes[h]._private.edges;
  13099. for (var i = 0; i < edges.length; i++) {
  13100. var edge = edges[i];
  13101. var edgeData = edge._private.data;
  13102. var thisToOther = this.hasElementWithId(edgeData.source) && otherNodes.hasElementWithId(edgeData.target);
  13103. var otherToThis = otherNodes.hasElementWithId(edgeData.source) && this.hasElementWithId(edgeData.target);
  13104. var edgeConnectsThisAndOther = thisToOther || otherToThis;
  13105. if (!edgeConnectsThisAndOther) {
  13106. continue;
  13107. }
  13108. if (p.thisIsSrc || p.thisIsTgt) {
  13109. if (p.thisIsSrc && !thisToOther) {
  13110. continue;
  13111. }
  13112. if (p.thisIsTgt && !otherToThis) {
  13113. continue;
  13114. }
  13115. }
  13116. elements.push(edge);
  13117. }
  13118. }
  13119. return this.spawn(elements, true);
  13120. };
  13121. }
  13122. extend(elesfn$2, {
  13123. connectedEdges: cache(function (selector) {
  13124. var retEles = [];
  13125. var eles = this;
  13126. for (var i = 0; i < eles.length; i++) {
  13127. var node = eles[i];
  13128. if (!node.isNode()) {
  13129. continue;
  13130. }
  13131. var edges = node._private.edges;
  13132. for (var j = 0; j < edges.length; j++) {
  13133. var edge = edges[j];
  13134. retEles.push(edge);
  13135. }
  13136. }
  13137. return this.spawn(retEles, true).filter(selector);
  13138. }, 'connectedEdges'),
  13139. connectedNodes: cache(function (selector) {
  13140. var retEles = [];
  13141. var eles = this;
  13142. for (var i = 0; i < eles.length; i++) {
  13143. var edge = eles[i];
  13144. if (!edge.isEdge()) {
  13145. continue;
  13146. }
  13147. retEles.push(edge.source()[0]);
  13148. retEles.push(edge.target()[0]);
  13149. }
  13150. return this.spawn(retEles, true).filter(selector);
  13151. }, 'connectedNodes'),
  13152. parallelEdges: cache(defineParallelEdgesFunction(), 'parallelEdges'),
  13153. codirectedEdges: cache(defineParallelEdgesFunction({
  13154. codirected: true
  13155. }), 'codirectedEdges')
  13156. });
  13157. function defineParallelEdgesFunction(params) {
  13158. var defaults = {
  13159. codirected: false
  13160. };
  13161. params = extend({}, defaults, params);
  13162. return function parallelEdgesImpl(selector) {
  13163. // micro-optimised for renderer
  13164. var elements = [];
  13165. var edges = this.edges();
  13166. var p = params;
  13167. // look at all the edges in the collection
  13168. for (var i = 0; i < edges.length; i++) {
  13169. var edge1 = edges[i];
  13170. var edge1_p = edge1._private;
  13171. var src1 = edge1_p.source;
  13172. var srcid1 = src1._private.data.id;
  13173. var tgtid1 = edge1_p.data.target;
  13174. var srcEdges1 = src1._private.edges;
  13175. // look at edges connected to the src node of this edge
  13176. for (var j = 0; j < srcEdges1.length; j++) {
  13177. var edge2 = srcEdges1[j];
  13178. var edge2data = edge2._private.data;
  13179. var tgtid2 = edge2data.target;
  13180. var srcid2 = edge2data.source;
  13181. var codirected = tgtid2 === tgtid1 && srcid2 === srcid1;
  13182. var oppdirected = srcid1 === tgtid2 && tgtid1 === srcid2;
  13183. if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {
  13184. elements.push(edge2);
  13185. }
  13186. }
  13187. }
  13188. return this.spawn(elements, true).filter(selector);
  13189. };
  13190. }
  13191. // Misc functions
  13192. /////////////////
  13193. extend(elesfn$2, {
  13194. components: function components(root) {
  13195. var self = this;
  13196. var cy = self.cy();
  13197. var visited = cy.collection();
  13198. var unvisited = root == null ? self.nodes() : root.nodes();
  13199. var components = [];
  13200. if (root != null && unvisited.empty()) {
  13201. // root may contain only edges
  13202. unvisited = root.sources(); // doesn't matter which node to use (undirected), so just use the source sides
  13203. }
  13204. var visitInComponent = function visitInComponent(node, component) {
  13205. visited.merge(node);
  13206. unvisited.unmerge(node);
  13207. component.merge(node);
  13208. };
  13209. if (unvisited.empty()) {
  13210. return self.spawn();
  13211. }
  13212. var _loop = function _loop() {
  13213. // each iteration yields a component
  13214. var cmpt = cy.collection();
  13215. components.push(cmpt);
  13216. var root = unvisited[0];
  13217. visitInComponent(root, cmpt);
  13218. self.bfs({
  13219. directed: false,
  13220. roots: root,
  13221. visit: function visit(v) {
  13222. return visitInComponent(v, cmpt);
  13223. }
  13224. });
  13225. cmpt.forEach(function (node) {
  13226. node.connectedEdges().forEach(function (e) {
  13227. // connectedEdges() usually cached
  13228. if (self.has(e) && cmpt.has(e.source()) && cmpt.has(e.target())) {
  13229. // has() is cheap
  13230. cmpt.merge(e); // forEach() only considers nodes -- sets N at call time
  13231. }
  13232. });
  13233. });
  13234. };
  13235. do {
  13236. _loop();
  13237. } while (unvisited.length > 0);
  13238. return components;
  13239. },
  13240. component: function component() {
  13241. var ele = this[0];
  13242. return ele.cy().mutableElements().components(ele)[0];
  13243. }
  13244. });
  13245. elesfn$2.componentsOf = elesfn$2.components;
  13246. // represents a set of nodes, edges, or both together
  13247. var Collection = function Collection(cy, elements) {
  13248. var unique = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  13249. var removed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  13250. if (cy === undefined) {
  13251. error('A collection must have a reference to the core');
  13252. return;
  13253. }
  13254. var map = new Map$1();
  13255. var createdElements = false;
  13256. if (!elements) {
  13257. elements = [];
  13258. } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {
  13259. createdElements = true;
  13260. // make elements from json and restore all at once later
  13261. var eles = [];
  13262. var elesIds = new Set$1();
  13263. for (var i = 0, l = elements.length; i < l; i++) {
  13264. var json = elements[i];
  13265. if (json.data == null) {
  13266. json.data = {};
  13267. }
  13268. var _data = json.data;
  13269. // make sure newly created elements have valid ids
  13270. if (_data.id == null) {
  13271. _data.id = uuid();
  13272. } else if (cy.hasElementWithId(_data.id) || elesIds.has(_data.id)) {
  13273. continue; // can't create element if prior id already exists
  13274. }
  13275. var ele = new Element(cy, json, false);
  13276. eles.push(ele);
  13277. elesIds.add(_data.id);
  13278. }
  13279. elements = eles;
  13280. }
  13281. this.length = 0;
  13282. for (var _i = 0, _l = elements.length; _i < _l; _i++) {
  13283. var element$1 = elements[_i][0]; // [0] in case elements is an array of collections, rather than array of elements
  13284. if (element$1 == null) {
  13285. continue;
  13286. }
  13287. var id = element$1._private.data.id;
  13288. if (!unique || !map.has(id)) {
  13289. if (unique) {
  13290. map.set(id, {
  13291. index: this.length,
  13292. ele: element$1
  13293. });
  13294. }
  13295. this[this.length] = element$1;
  13296. this.length++;
  13297. }
  13298. }
  13299. this._private = {
  13300. eles: this,
  13301. cy: cy,
  13302. get map() {
  13303. if (this.lazyMap == null) {
  13304. this.rebuildMap();
  13305. }
  13306. return this.lazyMap;
  13307. },
  13308. set map(m) {
  13309. this.lazyMap = m;
  13310. },
  13311. rebuildMap: function rebuildMap() {
  13312. var m = this.lazyMap = new Map$1();
  13313. var eles = this.eles;
  13314. for (var _i2 = 0; _i2 < eles.length; _i2++) {
  13315. var _ele = eles[_i2];
  13316. m.set(_ele.id(), {
  13317. index: _i2,
  13318. ele: _ele
  13319. });
  13320. }
  13321. }
  13322. };
  13323. if (unique) {
  13324. this._private.map = map;
  13325. }
  13326. // restore the elements if we created them from json
  13327. if (createdElements && !removed) {
  13328. this.restore();
  13329. }
  13330. };
  13331. // Functions
  13332. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13333. // keep the prototypes in sync (an element has the same functions as a collection)
  13334. // and use elefn and elesfn as shorthands to the prototypes
  13335. var elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);
  13336. elesfn$1.instanceString = function () {
  13337. return 'collection';
  13338. };
  13339. elesfn$1.spawn = function (eles, unique) {
  13340. return new Collection(this.cy(), eles, unique);
  13341. };
  13342. elesfn$1.spawnSelf = function () {
  13343. return this.spawn(this);
  13344. };
  13345. elesfn$1.cy = function () {
  13346. return this._private.cy;
  13347. };
  13348. elesfn$1.renderer = function () {
  13349. return this._private.cy.renderer();
  13350. };
  13351. elesfn$1.element = function () {
  13352. return this[0];
  13353. };
  13354. elesfn$1.collection = function () {
  13355. if (collection(this)) {
  13356. return this;
  13357. } else {
  13358. // an element
  13359. return new Collection(this._private.cy, [this]);
  13360. }
  13361. };
  13362. elesfn$1.unique = function () {
  13363. return new Collection(this._private.cy, this, true);
  13364. };
  13365. elesfn$1.hasElementWithId = function (id) {
  13366. id = '' + id; // id must be string
  13367. return this._private.map.has(id);
  13368. };
  13369. elesfn$1.getElementById = function (id) {
  13370. id = '' + id; // id must be string
  13371. var cy = this._private.cy;
  13372. var entry = this._private.map.get(id);
  13373. return entry ? entry.ele : new Collection(cy); // get ele or empty collection
  13374. };
  13375. elesfn$1.$id = elesfn$1.getElementById;
  13376. elesfn$1.poolIndex = function () {
  13377. var cy = this._private.cy;
  13378. var eles = cy._private.elements;
  13379. var id = this[0]._private.data.id;
  13380. return eles._private.map.get(id).index;
  13381. };
  13382. elesfn$1.indexOf = function (ele) {
  13383. var id = ele[0]._private.data.id;
  13384. return this._private.map.get(id).index;
  13385. };
  13386. elesfn$1.indexOfId = function (id) {
  13387. id = '' + id; // id must be string
  13388. return this._private.map.get(id).index;
  13389. };
  13390. elesfn$1.json = function (obj) {
  13391. var ele = this.element();
  13392. var cy = this.cy();
  13393. if (ele == null && obj) {
  13394. return this;
  13395. } // can't set to no eles
  13396. if (ele == null) {
  13397. return undefined;
  13398. } // can't get from no eles
  13399. var p = ele._private;
  13400. if (plainObject(obj)) {
  13401. // set
  13402. cy.startBatch();
  13403. if (obj.data) {
  13404. ele.data(obj.data);
  13405. var _data2 = p.data;
  13406. if (ele.isEdge()) {
  13407. // source and target are immutable via data()
  13408. var move = false;
  13409. var spec = {};
  13410. var src = obj.data.source;
  13411. var tgt = obj.data.target;
  13412. if (src != null && src != _data2.source) {
  13413. spec.source = '' + src; // id must be string
  13414. move = true;
  13415. }
  13416. if (tgt != null && tgt != _data2.target) {
  13417. spec.target = '' + tgt; // id must be string
  13418. move = true;
  13419. }
  13420. if (move) {
  13421. ele = ele.move(spec);
  13422. }
  13423. } else {
  13424. // parent is immutable via data()
  13425. var newParentValSpecd = 'parent' in obj.data;
  13426. var parent = obj.data.parent;
  13427. if (newParentValSpecd && (parent != null || _data2.parent != null) && parent != _data2.parent) {
  13428. if (parent === undefined) {
  13429. // can't set undefined imperatively, so use null
  13430. parent = null;
  13431. }
  13432. if (parent != null) {
  13433. parent = '' + parent; // id must be string
  13434. }
  13435. ele = ele.move({
  13436. parent: parent
  13437. });
  13438. }
  13439. }
  13440. }
  13441. if (obj.position) {
  13442. ele.position(obj.position);
  13443. }
  13444. // ignore group -- immutable
  13445. var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {
  13446. var obj_k = obj[k];
  13447. if (obj_k != null && obj_k !== p[k]) {
  13448. if (obj_k) {
  13449. ele[trueFnName]();
  13450. } else {
  13451. ele[falseFnName]();
  13452. }
  13453. }
  13454. };
  13455. checkSwitch('removed', 'remove', 'restore');
  13456. checkSwitch('selected', 'select', 'unselect');
  13457. checkSwitch('selectable', 'selectify', 'unselectify');
  13458. checkSwitch('locked', 'lock', 'unlock');
  13459. checkSwitch('grabbable', 'grabify', 'ungrabify');
  13460. checkSwitch('pannable', 'panify', 'unpanify');
  13461. if (obj.classes != null) {
  13462. ele.classes(obj.classes);
  13463. }
  13464. cy.endBatch();
  13465. return this;
  13466. } else if (obj === undefined) {
  13467. // get
  13468. var json = {
  13469. data: copy(p.data),
  13470. position: copy(p.position),
  13471. group: p.group,
  13472. removed: p.removed,
  13473. selected: p.selected,
  13474. selectable: p.selectable,
  13475. locked: p.locked,
  13476. grabbable: p.grabbable,
  13477. pannable: p.pannable,
  13478. classes: null
  13479. };
  13480. json.classes = '';
  13481. var i = 0;
  13482. p.classes.forEach(function (cls) {
  13483. return json.classes += i++ === 0 ? cls : ' ' + cls;
  13484. });
  13485. return json;
  13486. }
  13487. };
  13488. elesfn$1.jsons = function () {
  13489. var jsons = [];
  13490. for (var i = 0; i < this.length; i++) {
  13491. var ele = this[i];
  13492. var json = ele.json();
  13493. jsons.push(json);
  13494. }
  13495. return jsons;
  13496. };
  13497. elesfn$1.clone = function () {
  13498. var cy = this.cy();
  13499. var elesArr = [];
  13500. for (var i = 0; i < this.length; i++) {
  13501. var ele = this[i];
  13502. var json = ele.json();
  13503. var clone = new Element(cy, json, false); // NB no restore
  13504. elesArr.push(clone);
  13505. }
  13506. return new Collection(cy, elesArr);
  13507. };
  13508. elesfn$1.copy = elesfn$1.clone;
  13509. elesfn$1.restore = function () {
  13510. var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  13511. var addToPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  13512. var self = this;
  13513. var cy = self.cy();
  13514. var cy_p = cy._private;
  13515. // create arrays of nodes and edges, since we need to
  13516. // restore the nodes first
  13517. var nodes = [];
  13518. var edges = [];
  13519. var elements;
  13520. for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {
  13521. var ele = self[_i3];
  13522. if (addToPool && !ele.removed()) {
  13523. // don't need to handle this ele
  13524. continue;
  13525. }
  13526. // keep nodes first in the array and edges after
  13527. if (ele.isNode()) {
  13528. // put to front of array if node
  13529. nodes.push(ele);
  13530. } else {
  13531. // put to end of array if edge
  13532. edges.push(ele);
  13533. }
  13534. }
  13535. elements = nodes.concat(edges);
  13536. var i;
  13537. var removeFromElements = function removeFromElements() {
  13538. elements.splice(i, 1);
  13539. i--;
  13540. };
  13541. // now, restore each element
  13542. for (i = 0; i < elements.length; i++) {
  13543. var _ele2 = elements[i];
  13544. var _private = _ele2._private;
  13545. var _data3 = _private.data;
  13546. // the traversal cache should start fresh when ele is added
  13547. _ele2.clearTraversalCache();
  13548. // set id and validate
  13549. if (!addToPool && !_private.removed) ; else if (_data3.id === undefined) {
  13550. _data3.id = uuid();
  13551. } else if (number$1(_data3.id)) {
  13552. _data3.id = '' + _data3.id; // now it's a string
  13553. } else if (emptyString(_data3.id) || !string(_data3.id)) {
  13554. error('Can not create element with invalid string ID `' + _data3.id + '`');
  13555. // can't create element if it has empty string as id or non-string id
  13556. removeFromElements();
  13557. continue;
  13558. } else if (cy.hasElementWithId(_data3.id)) {
  13559. error('Can not create second element with ID `' + _data3.id + '`');
  13560. // can't create element if one already has that id
  13561. removeFromElements();
  13562. continue;
  13563. }
  13564. var id = _data3.id; // id is finalised, now let's keep a ref
  13565. if (_ele2.isNode()) {
  13566. // extra checks for nodes
  13567. var pos = _private.position;
  13568. // make sure the nodes have a defined position
  13569. if (pos.x == null) {
  13570. pos.x = 0;
  13571. }
  13572. if (pos.y == null) {
  13573. pos.y = 0;
  13574. }
  13575. }
  13576. if (_ele2.isEdge()) {
  13577. // extra checks for edges
  13578. var edge = _ele2;
  13579. var fields = ['source', 'target'];
  13580. var fieldsLength = fields.length;
  13581. var badSourceOrTarget = false;
  13582. for (var j = 0; j < fieldsLength; j++) {
  13583. var field = fields[j];
  13584. var val = _data3[field];
  13585. if (number$1(val)) {
  13586. val = _data3[field] = '' + _data3[field]; // now string
  13587. }
  13588. if (val == null || val === '') {
  13589. // can't create if source or target is not defined properly
  13590. error('Can not create edge `' + id + '` with unspecified ' + field);
  13591. badSourceOrTarget = true;
  13592. } else if (!cy.hasElementWithId(val)) {
  13593. // can't create edge if one of its nodes doesn't exist
  13594. error('Can not create edge `' + id + '` with nonexistent ' + field + ' `' + val + '`');
  13595. badSourceOrTarget = true;
  13596. }
  13597. }
  13598. if (badSourceOrTarget) {
  13599. removeFromElements();
  13600. continue;
  13601. } // can't create this
  13602. var src = cy.getElementById(_data3.source);
  13603. var tgt = cy.getElementById(_data3.target);
  13604. // only one edge in node if loop
  13605. if (src.same(tgt)) {
  13606. src._private.edges.push(edge);
  13607. } else {
  13608. src._private.edges.push(edge);
  13609. tgt._private.edges.push(edge);
  13610. }
  13611. edge._private.source = src;
  13612. edge._private.target = tgt;
  13613. } // if is edge
  13614. // create mock ids / indexes maps for element so it can be used like collections
  13615. _private.map = new Map$1();
  13616. _private.map.set(id, {
  13617. ele: _ele2,
  13618. index: 0
  13619. });
  13620. _private.removed = false;
  13621. if (addToPool) {
  13622. cy.addToPool(_ele2);
  13623. }
  13624. } // for each element
  13625. // do compound node sanity checks
  13626. for (var _i4 = 0; _i4 < nodes.length; _i4++) {
  13627. // each node
  13628. var node = nodes[_i4];
  13629. var _data4 = node._private.data;
  13630. if (number$1(_data4.parent)) {
  13631. // then automake string
  13632. _data4.parent = '' + _data4.parent;
  13633. }
  13634. var parentId = _data4.parent;
  13635. var specifiedParent = parentId != null;
  13636. if (specifiedParent || node._private.parent) {
  13637. var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);
  13638. if (parent.empty()) {
  13639. // non-existant parent; just remove it
  13640. _data4.parent = undefined;
  13641. } else if (parent[0].removed()) {
  13642. warn('Node added with missing parent, reference to parent removed');
  13643. _data4.parent = undefined;
  13644. node._private.parent = null;
  13645. } else {
  13646. var selfAsParent = false;
  13647. var ancestor = parent;
  13648. while (!ancestor.empty()) {
  13649. if (node.same(ancestor)) {
  13650. // mark self as parent and remove from data
  13651. selfAsParent = true;
  13652. _data4.parent = undefined; // remove parent reference
  13653. // exit or we loop forever
  13654. break;
  13655. }
  13656. ancestor = ancestor.parent();
  13657. }
  13658. if (!selfAsParent) {
  13659. // connect with children
  13660. parent[0]._private.children.push(node);
  13661. node._private.parent = parent[0];
  13662. // let the core know we have a compound graph
  13663. cy_p.hasCompoundNodes = true;
  13664. }
  13665. } // else
  13666. } // if specified parent
  13667. } // for each node
  13668. if (elements.length > 0) {
  13669. var restored = elements.length === self.length ? self : new Collection(cy, elements);
  13670. for (var _i5 = 0; _i5 < restored.length; _i5++) {
  13671. var _ele3 = restored[_i5];
  13672. if (_ele3.isNode()) {
  13673. continue;
  13674. }
  13675. // adding an edge invalidates the traversal caches for the parallel edges
  13676. _ele3.parallelEdges().clearTraversalCache();
  13677. // adding an edge invalidates the traversal cache for the connected nodes
  13678. _ele3.source().clearTraversalCache();
  13679. _ele3.target().clearTraversalCache();
  13680. }
  13681. var toUpdateStyle;
  13682. if (cy_p.hasCompoundNodes) {
  13683. toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());
  13684. } else {
  13685. toUpdateStyle = restored;
  13686. }
  13687. toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);
  13688. if (notifyRenderer) {
  13689. restored.emitAndNotify('add');
  13690. } else if (addToPool) {
  13691. restored.emit('add');
  13692. }
  13693. }
  13694. return self; // chainability
  13695. };
  13696. elesfn$1.removed = function () {
  13697. var ele = this[0];
  13698. return ele && ele._private.removed;
  13699. };
  13700. elesfn$1.inside = function () {
  13701. var ele = this[0];
  13702. return ele && !ele._private.removed;
  13703. };
  13704. elesfn$1.remove = function () {
  13705. var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  13706. var removeFromPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  13707. var self = this;
  13708. var elesToRemove = [];
  13709. var elesToRemoveIds = {};
  13710. var cy = self._private.cy;
  13711. // add connected edges
  13712. function addConnectedEdges(node) {
  13713. var edges = node._private.edges;
  13714. for (var i = 0; i < edges.length; i++) {
  13715. add(edges[i]);
  13716. }
  13717. }
  13718. // add descendant nodes
  13719. function addChildren(node) {
  13720. var children = node._private.children;
  13721. for (var i = 0; i < children.length; i++) {
  13722. add(children[i]);
  13723. }
  13724. }
  13725. function add(ele) {
  13726. var alreadyAdded = elesToRemoveIds[ele.id()];
  13727. if (removeFromPool && ele.removed() || alreadyAdded) {
  13728. return;
  13729. } else {
  13730. elesToRemoveIds[ele.id()] = true;
  13731. }
  13732. if (ele.isNode()) {
  13733. elesToRemove.push(ele); // nodes are removed last
  13734. addConnectedEdges(ele);
  13735. addChildren(ele);
  13736. } else {
  13737. elesToRemove.unshift(ele); // edges are removed first
  13738. }
  13739. }
  13740. // make the list of elements to remove
  13741. // (may be removing more than specified due to connected edges etc)
  13742. for (var i = 0, l = self.length; i < l; i++) {
  13743. var ele = self[i];
  13744. add(ele);
  13745. }
  13746. function removeEdgeRef(node, edge) {
  13747. var connectedEdges = node._private.edges;
  13748. removeFromArray(connectedEdges, edge);
  13749. // removing an edges invalidates the traversal cache for its nodes
  13750. node.clearTraversalCache();
  13751. }
  13752. function removeParallelRef(pllEdge) {
  13753. // removing an edge invalidates the traversal caches for the parallel edges
  13754. pllEdge.clearTraversalCache();
  13755. }
  13756. var alteredParents = [];
  13757. alteredParents.ids = {};
  13758. function removeChildRef(parent, ele) {
  13759. ele = ele[0];
  13760. parent = parent[0];
  13761. var children = parent._private.children;
  13762. var pid = parent.id();
  13763. removeFromArray(children, ele); // remove parent => child ref
  13764. ele._private.parent = null; // remove child => parent ref
  13765. if (!alteredParents.ids[pid]) {
  13766. alteredParents.ids[pid] = true;
  13767. alteredParents.push(parent);
  13768. }
  13769. }
  13770. self.dirtyCompoundBoundsCache();
  13771. if (removeFromPool) {
  13772. cy.removeFromPool(elesToRemove); // remove from core pool
  13773. }
  13774. for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {
  13775. var _ele4 = elesToRemove[_i6];
  13776. if (_ele4.isEdge()) {
  13777. // remove references to this edge in its connected nodes
  13778. var src = _ele4.source()[0];
  13779. var tgt = _ele4.target()[0];
  13780. removeEdgeRef(src, _ele4);
  13781. removeEdgeRef(tgt, _ele4);
  13782. var pllEdges = _ele4.parallelEdges();
  13783. for (var j = 0; j < pllEdges.length; j++) {
  13784. var pllEdge = pllEdges[j];
  13785. removeParallelRef(pllEdge);
  13786. if (pllEdge.isBundledBezier()) {
  13787. pllEdge.dirtyBoundingBoxCache();
  13788. }
  13789. }
  13790. } else {
  13791. // remove reference to parent
  13792. var parent = _ele4.parent();
  13793. if (parent.length !== 0) {
  13794. removeChildRef(parent, _ele4);
  13795. }
  13796. }
  13797. if (removeFromPool) {
  13798. // mark as removed
  13799. _ele4._private.removed = true;
  13800. }
  13801. }
  13802. // check to see if we have a compound graph or not
  13803. var elesStillInside = cy._private.elements;
  13804. cy._private.hasCompoundNodes = false;
  13805. for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {
  13806. var _ele5 = elesStillInside[_i7];
  13807. if (_ele5.isParent()) {
  13808. cy._private.hasCompoundNodes = true;
  13809. break;
  13810. }
  13811. }
  13812. var removedElements = new Collection(this.cy(), elesToRemove);
  13813. if (removedElements.size() > 0) {
  13814. // must manually notify since trigger won't do this automatically once removed
  13815. if (notifyRenderer) {
  13816. removedElements.emitAndNotify('remove');
  13817. } else if (removeFromPool) {
  13818. removedElements.emit('remove');
  13819. }
  13820. }
  13821. // the parents who were modified by the removal need their style updated
  13822. for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {
  13823. var _ele6 = alteredParents[_i8];
  13824. if (!removeFromPool || !_ele6.removed()) {
  13825. _ele6.updateStyle();
  13826. }
  13827. }
  13828. return removedElements;
  13829. };
  13830. elesfn$1.move = function (struct) {
  13831. var cy = this._private.cy;
  13832. var eles = this;
  13833. // just clean up refs, caches, etc. in the same way as when removing and then restoring
  13834. // (our calls to remove/restore do not remove from the graph or make events)
  13835. var notifyRenderer = false;
  13836. var modifyPool = false;
  13837. var toString = function toString(id) {
  13838. return id == null ? id : '' + id;
  13839. }; // id must be string
  13840. if (struct.source !== undefined || struct.target !== undefined) {
  13841. var srcId = toString(struct.source);
  13842. var tgtId = toString(struct.target);
  13843. var srcExists = srcId != null && cy.hasElementWithId(srcId);
  13844. var tgtExists = tgtId != null && cy.hasElementWithId(tgtId);
  13845. if (srcExists || tgtExists) {
  13846. cy.batch(function () {
  13847. // avoid duplicate style updates
  13848. eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
  13849. eles.emitAndNotify('moveout');
  13850. for (var i = 0; i < eles.length; i++) {
  13851. var ele = eles[i];
  13852. var _data5 = ele._private.data;
  13853. if (ele.isEdge()) {
  13854. if (srcExists) {
  13855. _data5.source = srcId;
  13856. }
  13857. if (tgtExists) {
  13858. _data5.target = tgtId;
  13859. }
  13860. }
  13861. }
  13862. eles.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
  13863. });
  13864. eles.emitAndNotify('move');
  13865. }
  13866. } else if (struct.parent !== undefined) {
  13867. // move node to new parent
  13868. var parentId = toString(struct.parent);
  13869. var parentExists = parentId === null || cy.hasElementWithId(parentId);
  13870. if (parentExists) {
  13871. var pidToAssign = parentId === null ? undefined : parentId;
  13872. cy.batch(function () {
  13873. // avoid duplicate style updates
  13874. var updated = eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
  13875. updated.emitAndNotify('moveout');
  13876. for (var i = 0; i < eles.length; i++) {
  13877. var ele = eles[i];
  13878. var _data6 = ele._private.data;
  13879. if (ele.isNode()) {
  13880. _data6.parent = pidToAssign;
  13881. }
  13882. }
  13883. updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
  13884. });
  13885. eles.emitAndNotify('move');
  13886. }
  13887. }
  13888. return this;
  13889. };
  13890. [elesfn$j, elesfn$i, elesfn$h, elesfn$g, elesfn$f, data, elesfn$d, dimensions, elesfn$9, elesfn$8, elesfn$7, elesfn$6, elesfn$5, elesfn$4, elesfn$3, elesfn$2].forEach(function (props) {
  13891. extend(elesfn$1, props);
  13892. });
  13893. var corefn$9 = {
  13894. add: function add(opts) {
  13895. var elements;
  13896. var cy = this;
  13897. // add the elements
  13898. if (elementOrCollection(opts)) {
  13899. var eles = opts;
  13900. if (eles._private.cy === cy) {
  13901. // same instance => just restore
  13902. elements = eles.restore();
  13903. } else {
  13904. // otherwise, copy from json
  13905. var jsons = [];
  13906. for (var i = 0; i < eles.length; i++) {
  13907. var ele = eles[i];
  13908. jsons.push(ele.json());
  13909. }
  13910. elements = new Collection(cy, jsons);
  13911. }
  13912. }
  13913. // specify an array of options
  13914. else if (array(opts)) {
  13915. var _jsons = opts;
  13916. elements = new Collection(cy, _jsons);
  13917. }
  13918. // specify via opts.nodes and opts.edges
  13919. else if (plainObject(opts) && (array(opts.nodes) || array(opts.edges))) {
  13920. var elesByGroup = opts;
  13921. var _jsons2 = [];
  13922. var grs = ['nodes', 'edges'];
  13923. for (var _i = 0, il = grs.length; _i < il; _i++) {
  13924. var group = grs[_i];
  13925. var elesArray = elesByGroup[group];
  13926. if (array(elesArray)) {
  13927. for (var j = 0, jl = elesArray.length; j < jl; j++) {
  13928. var json = extend({
  13929. group: group
  13930. }, elesArray[j]);
  13931. _jsons2.push(json);
  13932. }
  13933. }
  13934. }
  13935. elements = new Collection(cy, _jsons2);
  13936. }
  13937. // specify options for one element
  13938. else {
  13939. var _json = opts;
  13940. elements = new Element(cy, _json).collection();
  13941. }
  13942. return elements;
  13943. },
  13944. remove: function remove(collection) {
  13945. if (elementOrCollection(collection)) ; else if (string(collection)) {
  13946. var selector = collection;
  13947. collection = this.$(selector);
  13948. }
  13949. return collection.remove();
  13950. }
  13951. };
  13952. /* global Float32Array */
  13953. /*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
  13954. function generateCubicBezier(mX1, mY1, mX2, mY2) {
  13955. var NEWTON_ITERATIONS = 4,
  13956. NEWTON_MIN_SLOPE = 0.001,
  13957. SUBDIVISION_PRECISION = 0.0000001,
  13958. SUBDIVISION_MAX_ITERATIONS = 10,
  13959. kSplineTableSize = 11,
  13960. kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
  13961. float32ArraySupported = typeof Float32Array !== 'undefined';
  13962. /* Must contain four arguments. */
  13963. if (arguments.length !== 4) {
  13964. return false;
  13965. }
  13966. /* Arguments must be numbers. */
  13967. for (var i = 0; i < 4; ++i) {
  13968. if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
  13969. return false;
  13970. }
  13971. }
  13972. /* X values must be in the [0, 1] range. */
  13973. mX1 = Math.min(mX1, 1);
  13974. mX2 = Math.min(mX2, 1);
  13975. mX1 = Math.max(mX1, 0);
  13976. mX2 = Math.max(mX2, 0);
  13977. var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  13978. function A(aA1, aA2) {
  13979. return 1.0 - 3.0 * aA2 + 3.0 * aA1;
  13980. }
  13981. function B(aA1, aA2) {
  13982. return 3.0 * aA2 - 6.0 * aA1;
  13983. }
  13984. function C(aA1) {
  13985. return 3.0 * aA1;
  13986. }
  13987. function calcBezier(aT, aA1, aA2) {
  13988. return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  13989. }
  13990. function getSlope(aT, aA1, aA2) {
  13991. return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  13992. }
  13993. function newtonRaphsonIterate(aX, aGuessT) {
  13994. for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {
  13995. var currentSlope = getSlope(aGuessT, mX1, mX2);
  13996. if (currentSlope === 0.0) {
  13997. return aGuessT;
  13998. }
  13999. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  14000. aGuessT -= currentX / currentSlope;
  14001. }
  14002. return aGuessT;
  14003. }
  14004. function calcSampleValues() {
  14005. for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {
  14006. mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);
  14007. }
  14008. }
  14009. function binarySubdivide(aX, aA, aB) {
  14010. var currentX,
  14011. currentT,
  14012. i = 0;
  14013. do {
  14014. currentT = aA + (aB - aA) / 2.0;
  14015. currentX = calcBezier(currentT, mX1, mX2) - aX;
  14016. if (currentX > 0.0) {
  14017. aB = currentT;
  14018. } else {
  14019. aA = currentT;
  14020. }
  14021. } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
  14022. return currentT;
  14023. }
  14024. function getTForX(aX) {
  14025. var intervalStart = 0.0,
  14026. currentSample = 1,
  14027. lastSample = kSplineTableSize - 1;
  14028. for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
  14029. intervalStart += kSampleStepSize;
  14030. }
  14031. --currentSample;
  14032. var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),
  14033. guessForT = intervalStart + dist * kSampleStepSize,
  14034. initialSlope = getSlope(guessForT, mX1, mX2);
  14035. if (initialSlope >= NEWTON_MIN_SLOPE) {
  14036. return newtonRaphsonIterate(aX, guessForT);
  14037. } else if (initialSlope === 0.0) {
  14038. return guessForT;
  14039. } else {
  14040. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
  14041. }
  14042. }
  14043. var _precomputed = false;
  14044. function precompute() {
  14045. _precomputed = true;
  14046. if (mX1 !== mY1 || mX2 !== mY2) {
  14047. calcSampleValues();
  14048. }
  14049. }
  14050. var f = function f(aX) {
  14051. if (!_precomputed) {
  14052. precompute();
  14053. }
  14054. if (mX1 === mY1 && mX2 === mY2) {
  14055. return aX;
  14056. }
  14057. if (aX === 0) {
  14058. return 0;
  14059. }
  14060. if (aX === 1) {
  14061. return 1;
  14062. }
  14063. return calcBezier(getTForX(aX), mY1, mY2);
  14064. };
  14065. f.getControlPoints = function () {
  14066. return [{
  14067. x: mX1,
  14068. y: mY1
  14069. }, {
  14070. x: mX2,
  14071. y: mY2
  14072. }];
  14073. };
  14074. var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
  14075. f.toString = function () {
  14076. return str;
  14077. };
  14078. return f;
  14079. }
  14080. /*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
  14081. /* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass
  14082. then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
  14083. var generateSpringRK4 = function () {
  14084. function springAccelerationForState(state) {
  14085. return -state.tension * state.x - state.friction * state.v;
  14086. }
  14087. function springEvaluateStateWithDerivative(initialState, dt, derivative) {
  14088. var state = {
  14089. x: initialState.x + derivative.dx * dt,
  14090. v: initialState.v + derivative.dv * dt,
  14091. tension: initialState.tension,
  14092. friction: initialState.friction
  14093. };
  14094. return {
  14095. dx: state.v,
  14096. dv: springAccelerationForState(state)
  14097. };
  14098. }
  14099. function springIntegrateState(state, dt) {
  14100. var a = {
  14101. dx: state.v,
  14102. dv: springAccelerationForState(state)
  14103. },
  14104. b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
  14105. c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
  14106. d = springEvaluateStateWithDerivative(state, dt, c),
  14107. dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
  14108. dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
  14109. state.x = state.x + dxdt * dt;
  14110. state.v = state.v + dvdt * dt;
  14111. return state;
  14112. }
  14113. return function springRK4Factory(tension, friction, duration) {
  14114. var initState = {
  14115. x: -1,
  14116. v: 0,
  14117. tension: null,
  14118. friction: null
  14119. },
  14120. path = [0],
  14121. time_lapsed = 0,
  14122. tolerance = 1 / 10000,
  14123. DT = 16 / 1000,
  14124. have_duration,
  14125. dt,
  14126. last_state;
  14127. tension = parseFloat(tension) || 500;
  14128. friction = parseFloat(friction) || 20;
  14129. duration = duration || null;
  14130. initState.tension = tension;
  14131. initState.friction = friction;
  14132. have_duration = duration !== null;
  14133. /* Calculate the actual time it takes for this animation to complete with the provided conditions. */
  14134. if (have_duration) {
  14135. /* Run the simulation without a duration. */
  14136. time_lapsed = springRK4Factory(tension, friction);
  14137. /* Compute the adjusted time delta. */
  14138. dt = time_lapsed / duration * DT;
  14139. } else {
  14140. dt = DT;
  14141. }
  14142. for (;;) {
  14143. /* Next/step function .*/
  14144. last_state = springIntegrateState(last_state || initState, dt);
  14145. /* Store the position. */
  14146. path.push(1 + last_state.x);
  14147. time_lapsed += 16;
  14148. /* If the change threshold is reached, break. */
  14149. if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
  14150. break;
  14151. }
  14152. }
  14153. /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
  14154. computed path and returns a snapshot of the position according to a given percentComplete. */
  14155. return !have_duration ? time_lapsed : function (percentComplete) {
  14156. return path[percentComplete * (path.length - 1) | 0];
  14157. };
  14158. };
  14159. }();
  14160. var cubicBezier = function cubicBezier(t1, p1, t2, p2) {
  14161. var bezier = generateCubicBezier(t1, p1, t2, p2);
  14162. return function (start, end, percent) {
  14163. return start + (end - start) * bezier(percent);
  14164. };
  14165. };
  14166. var easings = {
  14167. 'linear': function linear(start, end, percent) {
  14168. return start + (end - start) * percent;
  14169. },
  14170. // default easings
  14171. 'ease': cubicBezier(0.25, 0.1, 0.25, 1),
  14172. 'ease-in': cubicBezier(0.42, 0, 1, 1),
  14173. 'ease-out': cubicBezier(0, 0, 0.58, 1),
  14174. 'ease-in-out': cubicBezier(0.42, 0, 0.58, 1),
  14175. // sine
  14176. 'ease-in-sine': cubicBezier(0.47, 0, 0.745, 0.715),
  14177. 'ease-out-sine': cubicBezier(0.39, 0.575, 0.565, 1),
  14178. 'ease-in-out-sine': cubicBezier(0.445, 0.05, 0.55, 0.95),
  14179. // quad
  14180. 'ease-in-quad': cubicBezier(0.55, 0.085, 0.68, 0.53),
  14181. 'ease-out-quad': cubicBezier(0.25, 0.46, 0.45, 0.94),
  14182. 'ease-in-out-quad': cubicBezier(0.455, 0.03, 0.515, 0.955),
  14183. // cubic
  14184. 'ease-in-cubic': cubicBezier(0.55, 0.055, 0.675, 0.19),
  14185. 'ease-out-cubic': cubicBezier(0.215, 0.61, 0.355, 1),
  14186. 'ease-in-out-cubic': cubicBezier(0.645, 0.045, 0.355, 1),
  14187. // quart
  14188. 'ease-in-quart': cubicBezier(0.895, 0.03, 0.685, 0.22),
  14189. 'ease-out-quart': cubicBezier(0.165, 0.84, 0.44, 1),
  14190. 'ease-in-out-quart': cubicBezier(0.77, 0, 0.175, 1),
  14191. // quint
  14192. 'ease-in-quint': cubicBezier(0.755, 0.05, 0.855, 0.06),
  14193. 'ease-out-quint': cubicBezier(0.23, 1, 0.32, 1),
  14194. 'ease-in-out-quint': cubicBezier(0.86, 0, 0.07, 1),
  14195. // expo
  14196. 'ease-in-expo': cubicBezier(0.95, 0.05, 0.795, 0.035),
  14197. 'ease-out-expo': cubicBezier(0.19, 1, 0.22, 1),
  14198. 'ease-in-out-expo': cubicBezier(1, 0, 0, 1),
  14199. // circ
  14200. 'ease-in-circ': cubicBezier(0.6, 0.04, 0.98, 0.335),
  14201. 'ease-out-circ': cubicBezier(0.075, 0.82, 0.165, 1),
  14202. 'ease-in-out-circ': cubicBezier(0.785, 0.135, 0.15, 0.86),
  14203. // user param easings...
  14204. 'spring': function spring(tension, friction, duration) {
  14205. if (duration === 0) {
  14206. // can't get a spring w/ duration 0
  14207. return easings.linear; // duration 0 => jump to end so impl doesn't matter
  14208. }
  14209. var spring = generateSpringRK4(tension, friction, duration);
  14210. return function (start, end, percent) {
  14211. return start + (end - start) * spring(percent);
  14212. };
  14213. },
  14214. 'cubic-bezier': cubicBezier
  14215. };
  14216. function getEasedValue(type, start, end, percent, easingFn) {
  14217. if (percent === 1) {
  14218. return end;
  14219. }
  14220. if (start === end) {
  14221. return end;
  14222. }
  14223. var val = easingFn(start, end, percent);
  14224. if (type == null) {
  14225. return val;
  14226. }
  14227. if (type.roundValue || type.color) {
  14228. val = Math.round(val);
  14229. }
  14230. if (type.min !== undefined) {
  14231. val = Math.max(val, type.min);
  14232. }
  14233. if (type.max !== undefined) {
  14234. val = Math.min(val, type.max);
  14235. }
  14236. return val;
  14237. }
  14238. function getValue(prop, spec) {
  14239. if (prop.pfValue != null || prop.value != null) {
  14240. if (prop.pfValue != null && (spec == null || spec.type.units !== '%')) {
  14241. return prop.pfValue;
  14242. } else {
  14243. return prop.value;
  14244. }
  14245. } else {
  14246. return prop;
  14247. }
  14248. }
  14249. function ease(startProp, endProp, percent, easingFn, propSpec) {
  14250. var type = propSpec != null ? propSpec.type : null;
  14251. if (percent < 0) {
  14252. percent = 0;
  14253. } else if (percent > 1) {
  14254. percent = 1;
  14255. }
  14256. var start = getValue(startProp, propSpec);
  14257. var end = getValue(endProp, propSpec);
  14258. if (number$1(start) && number$1(end)) {
  14259. return getEasedValue(type, start, end, percent, easingFn);
  14260. } else if (array(start) && array(end)) {
  14261. var easedArr = [];
  14262. for (var i = 0; i < end.length; i++) {
  14263. var si = start[i];
  14264. var ei = end[i];
  14265. if (si != null && ei != null) {
  14266. var val = getEasedValue(type, si, ei, percent, easingFn);
  14267. easedArr.push(val);
  14268. } else {
  14269. easedArr.push(ei);
  14270. }
  14271. }
  14272. return easedArr;
  14273. }
  14274. return undefined;
  14275. }
  14276. function step$1(self, ani, now, isCore) {
  14277. var isEles = !isCore;
  14278. var _p = self._private;
  14279. var ani_p = ani._private;
  14280. var pEasing = ani_p.easing;
  14281. var startTime = ani_p.startTime;
  14282. var cy = isCore ? self : self.cy();
  14283. var style = cy.style();
  14284. if (!ani_p.easingImpl) {
  14285. if (pEasing == null) {
  14286. // use default
  14287. ani_p.easingImpl = easings['linear'];
  14288. } else {
  14289. // then define w/ name
  14290. var easingVals;
  14291. if (string(pEasing)) {
  14292. var easingProp = style.parse('transition-timing-function', pEasing);
  14293. easingVals = easingProp.value;
  14294. } else {
  14295. // then assume preparsed array
  14296. easingVals = pEasing;
  14297. }
  14298. var name, args;
  14299. if (string(easingVals)) {
  14300. name = easingVals;
  14301. args = [];
  14302. } else {
  14303. name = easingVals[1];
  14304. args = easingVals.slice(2).map(function (n) {
  14305. return +n;
  14306. });
  14307. }
  14308. if (args.length > 0) {
  14309. // create with args
  14310. if (name === 'spring') {
  14311. args.push(ani_p.duration); // need duration to generate spring
  14312. }
  14313. ani_p.easingImpl = easings[name].apply(null, args);
  14314. } else {
  14315. // static impl by name
  14316. ani_p.easingImpl = easings[name];
  14317. }
  14318. }
  14319. }
  14320. var easing = ani_p.easingImpl;
  14321. var percent;
  14322. if (ani_p.duration === 0) {
  14323. percent = 1;
  14324. } else {
  14325. percent = (now - startTime) / ani_p.duration;
  14326. }
  14327. if (ani_p.applying) {
  14328. percent = ani_p.progress;
  14329. }
  14330. if (percent < 0) {
  14331. percent = 0;
  14332. } else if (percent > 1) {
  14333. percent = 1;
  14334. }
  14335. if (ani_p.delay == null) {
  14336. // then update
  14337. var startPos = ani_p.startPosition;
  14338. var endPos = ani_p.position;
  14339. if (endPos && isEles && !self.locked()) {
  14340. var newPos = {};
  14341. if (valid(startPos.x, endPos.x)) {
  14342. newPos.x = ease(startPos.x, endPos.x, percent, easing);
  14343. }
  14344. if (valid(startPos.y, endPos.y)) {
  14345. newPos.y = ease(startPos.y, endPos.y, percent, easing);
  14346. }
  14347. self.position(newPos);
  14348. }
  14349. var startPan = ani_p.startPan;
  14350. var endPan = ani_p.pan;
  14351. var pan = _p.pan;
  14352. var animatingPan = endPan != null && isCore;
  14353. if (animatingPan) {
  14354. if (valid(startPan.x, endPan.x)) {
  14355. pan.x = ease(startPan.x, endPan.x, percent, easing);
  14356. }
  14357. if (valid(startPan.y, endPan.y)) {
  14358. pan.y = ease(startPan.y, endPan.y, percent, easing);
  14359. }
  14360. self.emit('pan');
  14361. }
  14362. var startZoom = ani_p.startZoom;
  14363. var endZoom = ani_p.zoom;
  14364. var animatingZoom = endZoom != null && isCore;
  14365. if (animatingZoom) {
  14366. if (valid(startZoom, endZoom)) {
  14367. _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);
  14368. }
  14369. self.emit('zoom');
  14370. }
  14371. if (animatingPan || animatingZoom) {
  14372. self.emit('viewport');
  14373. }
  14374. var props = ani_p.style;
  14375. if (props && props.length > 0 && isEles) {
  14376. for (var i = 0; i < props.length; i++) {
  14377. var prop = props[i];
  14378. var _name = prop.name;
  14379. var end = prop;
  14380. var start = ani_p.startStyle[_name];
  14381. var propSpec = style.properties[start.name];
  14382. var easedVal = ease(start, end, percent, easing, propSpec);
  14383. style.overrideBypass(self, _name, easedVal);
  14384. } // for props
  14385. self.emit('style');
  14386. } // if
  14387. }
  14388. ani_p.progress = percent;
  14389. return percent;
  14390. }
  14391. function valid(start, end) {
  14392. if (start == null || end == null) {
  14393. return false;
  14394. }
  14395. if (number$1(start) && number$1(end)) {
  14396. return true;
  14397. } else if (start && end) {
  14398. return true;
  14399. }
  14400. return false;
  14401. }
  14402. function startAnimation(self, ani, now, isCore) {
  14403. var ani_p = ani._private;
  14404. ani_p.started = true;
  14405. ani_p.startTime = now - ani_p.progress * ani_p.duration;
  14406. }
  14407. function stepAll(now, cy) {
  14408. var eles = cy._private.aniEles;
  14409. var doneEles = [];
  14410. function stepOne(ele, isCore) {
  14411. var _p = ele._private;
  14412. var current = _p.animation.current;
  14413. var queue = _p.animation.queue;
  14414. var ranAnis = false;
  14415. // if nothing currently animating, get something from the queue
  14416. if (current.length === 0) {
  14417. var next = queue.shift();
  14418. if (next) {
  14419. current.push(next);
  14420. }
  14421. }
  14422. var callbacks = function callbacks(_callbacks) {
  14423. for (var j = _callbacks.length - 1; j >= 0; j--) {
  14424. var cb = _callbacks[j];
  14425. cb();
  14426. }
  14427. _callbacks.splice(0, _callbacks.length);
  14428. };
  14429. // step and remove if done
  14430. for (var i = current.length - 1; i >= 0; i--) {
  14431. var ani = current[i];
  14432. var ani_p = ani._private;
  14433. if (ani_p.stopped) {
  14434. current.splice(i, 1);
  14435. ani_p.hooked = false;
  14436. ani_p.playing = false;
  14437. ani_p.started = false;
  14438. callbacks(ani_p.frames);
  14439. continue;
  14440. }
  14441. if (!ani_p.playing && !ani_p.applying) {
  14442. continue;
  14443. }
  14444. // an apply() while playing shouldn't do anything
  14445. if (ani_p.playing && ani_p.applying) {
  14446. ani_p.applying = false;
  14447. }
  14448. if (!ani_p.started) {
  14449. startAnimation(ele, ani, now);
  14450. }
  14451. step$1(ele, ani, now, isCore);
  14452. if (ani_p.applying) {
  14453. ani_p.applying = false;
  14454. }
  14455. callbacks(ani_p.frames);
  14456. if (ani_p.step != null) {
  14457. ani_p.step(now);
  14458. }
  14459. if (ani.completed()) {
  14460. current.splice(i, 1);
  14461. ani_p.hooked = false;
  14462. ani_p.playing = false;
  14463. ani_p.started = false;
  14464. callbacks(ani_p.completes);
  14465. }
  14466. ranAnis = true;
  14467. }
  14468. if (!isCore && current.length === 0 && queue.length === 0) {
  14469. doneEles.push(ele);
  14470. }
  14471. return ranAnis;
  14472. } // stepElement
  14473. // handle all eles
  14474. var ranEleAni = false;
  14475. for (var e = 0; e < eles.length; e++) {
  14476. var ele = eles[e];
  14477. var handledThisEle = stepOne(ele);
  14478. ranEleAni = ranEleAni || handledThisEle;
  14479. } // each element
  14480. var ranCoreAni = stepOne(cy, true);
  14481. // notify renderer
  14482. if (ranEleAni || ranCoreAni) {
  14483. if (eles.length > 0) {
  14484. cy.notify('draw', eles);
  14485. } else {
  14486. cy.notify('draw');
  14487. }
  14488. }
  14489. // remove elements from list of currently animating if its queues are empty
  14490. eles.unmerge(doneEles);
  14491. cy.emit('step');
  14492. } // stepAll
  14493. var corefn$8 = {
  14494. // pull in animation functions
  14495. animate: define.animate(),
  14496. animation: define.animation(),
  14497. animated: define.animated(),
  14498. clearQueue: define.clearQueue(),
  14499. delay: define.delay(),
  14500. delayAnimation: define.delayAnimation(),
  14501. stop: define.stop(),
  14502. addToAnimationPool: function addToAnimationPool(eles) {
  14503. var cy = this;
  14504. if (!cy.styleEnabled()) {
  14505. return;
  14506. } // save cycles when no style used
  14507. cy._private.aniEles.merge(eles);
  14508. },
  14509. stopAnimationLoop: function stopAnimationLoop() {
  14510. this._private.animationsRunning = false;
  14511. },
  14512. startAnimationLoop: function startAnimationLoop() {
  14513. var cy = this;
  14514. cy._private.animationsRunning = true;
  14515. if (!cy.styleEnabled()) {
  14516. return;
  14517. } // save cycles when no style used
  14518. // NB the animation loop will exec in headless environments if style enabled
  14519. // and explicit cy.destroy() is necessary to stop the loop
  14520. function headlessStep() {
  14521. if (!cy._private.animationsRunning) {
  14522. return;
  14523. }
  14524. requestAnimationFrame(function animationStep(now) {
  14525. stepAll(now, cy);
  14526. headlessStep();
  14527. });
  14528. }
  14529. var renderer = cy.renderer();
  14530. if (renderer && renderer.beforeRender) {
  14531. // let the renderer schedule animations
  14532. renderer.beforeRender(function rendererAnimationStep(willDraw, now) {
  14533. stepAll(now, cy);
  14534. }, renderer.beforeRenderPriorities.animations);
  14535. } else {
  14536. // manage the animation loop ourselves
  14537. headlessStep(); // first call
  14538. }
  14539. }
  14540. };
  14541. var emitterOptions = {
  14542. qualifierCompare: function qualifierCompare(selector1, selector2) {
  14543. if (selector1 == null || selector2 == null) {
  14544. return selector1 == null && selector2 == null;
  14545. } else {
  14546. return selector1.sameText(selector2);
  14547. }
  14548. },
  14549. eventMatches: function eventMatches(cy, listener, eventObj) {
  14550. var selector = listener.qualifier;
  14551. if (selector != null) {
  14552. return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
  14553. }
  14554. return true;
  14555. },
  14556. addEventFields: function addEventFields(cy, evt) {
  14557. evt.cy = cy;
  14558. evt.target = cy;
  14559. },
  14560. callbackContext: function callbackContext(cy, listener, eventObj) {
  14561. return listener.qualifier != null ? eventObj.target : cy;
  14562. }
  14563. };
  14564. var argSelector = function argSelector(arg) {
  14565. if (string(arg)) {
  14566. return new Selector(arg);
  14567. } else {
  14568. return arg;
  14569. }
  14570. };
  14571. var elesfn = {
  14572. createEmitter: function createEmitter() {
  14573. var _p = this._private;
  14574. if (!_p.emitter) {
  14575. _p.emitter = new Emitter(emitterOptions, this);
  14576. }
  14577. return this;
  14578. },
  14579. emitter: function emitter() {
  14580. return this._private.emitter;
  14581. },
  14582. on: function on(events, selector, callback) {
  14583. this.emitter().on(events, argSelector(selector), callback);
  14584. return this;
  14585. },
  14586. removeListener: function removeListener(events, selector, callback) {
  14587. this.emitter().removeListener(events, argSelector(selector), callback);
  14588. return this;
  14589. },
  14590. removeAllListeners: function removeAllListeners() {
  14591. this.emitter().removeAllListeners();
  14592. return this;
  14593. },
  14594. one: function one(events, selector, callback) {
  14595. this.emitter().one(events, argSelector(selector), callback);
  14596. return this;
  14597. },
  14598. once: function once(events, selector, callback) {
  14599. this.emitter().one(events, argSelector(selector), callback);
  14600. return this;
  14601. },
  14602. emit: function emit(events, extraParams) {
  14603. this.emitter().emit(events, extraParams);
  14604. return this;
  14605. },
  14606. emitAndNotify: function emitAndNotify(event, eles) {
  14607. this.emit(event);
  14608. this.notify(event, eles);
  14609. return this;
  14610. }
  14611. };
  14612. define.eventAliasesOn(elesfn);
  14613. var corefn$7 = {
  14614. png: function png(options) {
  14615. var renderer = this._private.renderer;
  14616. options = options || {};
  14617. return renderer.png(options);
  14618. },
  14619. jpg: function jpg(options) {
  14620. var renderer = this._private.renderer;
  14621. options = options || {};
  14622. options.bg = options.bg || '#fff';
  14623. return renderer.jpg(options);
  14624. }
  14625. };
  14626. corefn$7.jpeg = corefn$7.jpg;
  14627. var corefn$6 = {
  14628. layout: function layout(options) {
  14629. var cy = this;
  14630. if (options == null) {
  14631. error('Layout options must be specified to make a layout');
  14632. return;
  14633. }
  14634. if (options.name == null) {
  14635. error('A `name` must be specified to make a layout');
  14636. return;
  14637. }
  14638. var name = options.name;
  14639. var Layout = cy.extension('layout', name);
  14640. if (Layout == null) {
  14641. error('No such layout `' + name + '` found. Did you forget to import it and `cytoscape.use()` it?');
  14642. return;
  14643. }
  14644. var eles;
  14645. if (string(options.eles)) {
  14646. eles = cy.$(options.eles);
  14647. } else {
  14648. eles = options.eles != null ? options.eles : cy.$();
  14649. }
  14650. var layout = new Layout(extend({}, options, {
  14651. cy: cy,
  14652. eles: eles
  14653. }));
  14654. return layout;
  14655. }
  14656. };
  14657. corefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;
  14658. var corefn$5 = {
  14659. notify: function notify(eventName, eventEles) {
  14660. var _p = this._private;
  14661. if (this.batching()) {
  14662. _p.batchNotifications = _p.batchNotifications || {};
  14663. var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();
  14664. if (eventEles != null) {
  14665. eles.merge(eventEles);
  14666. }
  14667. return; // notifications are disabled during batching
  14668. }
  14669. if (!_p.notificationsEnabled) {
  14670. return;
  14671. } // exit on disabled
  14672. var renderer = this.renderer();
  14673. // exit if destroy() called on core or renderer in between frames #1499 #1528
  14674. if (this.destroyed() || !renderer) {
  14675. return;
  14676. }
  14677. renderer.notify(eventName, eventEles);
  14678. },
  14679. notifications: function notifications(bool) {
  14680. var p = this._private;
  14681. if (bool === undefined) {
  14682. return p.notificationsEnabled;
  14683. } else {
  14684. p.notificationsEnabled = bool ? true : false;
  14685. }
  14686. return this;
  14687. },
  14688. noNotifications: function noNotifications(callback) {
  14689. this.notifications(false);
  14690. callback();
  14691. this.notifications(true);
  14692. },
  14693. batching: function batching() {
  14694. return this._private.batchCount > 0;
  14695. },
  14696. startBatch: function startBatch() {
  14697. var _p = this._private;
  14698. if (_p.batchCount == null) {
  14699. _p.batchCount = 0;
  14700. }
  14701. if (_p.batchCount === 0) {
  14702. _p.batchStyleEles = this.collection();
  14703. _p.batchNotifications = {};
  14704. }
  14705. _p.batchCount++;
  14706. return this;
  14707. },
  14708. endBatch: function endBatch() {
  14709. var _p = this._private;
  14710. if (_p.batchCount === 0) {
  14711. return this;
  14712. }
  14713. _p.batchCount--;
  14714. if (_p.batchCount === 0) {
  14715. // update style for dirty eles
  14716. _p.batchStyleEles.updateStyle();
  14717. var renderer = this.renderer();
  14718. // notify the renderer of queued eles and event types
  14719. Object.keys(_p.batchNotifications).forEach(function (eventName) {
  14720. var eles = _p.batchNotifications[eventName];
  14721. if (eles.empty()) {
  14722. renderer.notify(eventName);
  14723. } else {
  14724. renderer.notify(eventName, eles);
  14725. }
  14726. });
  14727. }
  14728. return this;
  14729. },
  14730. batch: function batch(callback) {
  14731. this.startBatch();
  14732. callback();
  14733. this.endBatch();
  14734. return this;
  14735. },
  14736. // for backwards compatibility
  14737. batchData: function batchData(map) {
  14738. var cy = this;
  14739. return this.batch(function () {
  14740. var ids = Object.keys(map);
  14741. for (var i = 0; i < ids.length; i++) {
  14742. var id = ids[i];
  14743. var data = map[id];
  14744. var ele = cy.getElementById(id);
  14745. ele.data(data);
  14746. }
  14747. });
  14748. }
  14749. };
  14750. var rendererDefaults = defaults$g({
  14751. hideEdgesOnViewport: false,
  14752. textureOnViewport: false,
  14753. motionBlur: false,
  14754. motionBlurOpacity: 0.05,
  14755. pixelRatio: undefined,
  14756. desktopTapThreshold: 4,
  14757. touchTapThreshold: 8,
  14758. wheelSensitivity: 1,
  14759. debug: false,
  14760. showFps: false,
  14761. // webgl options
  14762. webgl: false,
  14763. webglDebug: false,
  14764. webglDebugShowAtlases: false,
  14765. // defaults good for mobile
  14766. webglTexSize: 2048,
  14767. webglTexRows: 36,
  14768. webglTexRowsNodes: 18,
  14769. webglBatchSize: 2048,
  14770. webglTexPerBatch: 14,
  14771. webglBgColor: [255, 255, 255]
  14772. });
  14773. var corefn$4 = {
  14774. renderTo: function renderTo(context, zoom, pan, pxRatio) {
  14775. var r = this._private.renderer;
  14776. r.renderTo(context, zoom, pan, pxRatio);
  14777. return this;
  14778. },
  14779. renderer: function renderer() {
  14780. return this._private.renderer;
  14781. },
  14782. forceRender: function forceRender() {
  14783. this.notify('draw');
  14784. return this;
  14785. },
  14786. resize: function resize() {
  14787. this.invalidateSize();
  14788. this.emitAndNotify('resize');
  14789. return this;
  14790. },
  14791. initRenderer: function initRenderer(options) {
  14792. var cy = this;
  14793. var RendererProto = cy.extension('renderer', options.name);
  14794. if (RendererProto == null) {
  14795. error("Can not initialise: No such renderer `".concat(options.name, "` found. Did you forget to import it and `cytoscape.use()` it?"));
  14796. return;
  14797. }
  14798. if (options.wheelSensitivity !== undefined) {
  14799. warn("You have set a custom wheel sensitivity. This will make your app zoom unnaturally when using mainstream mice. You should change this value from the default only if you can guarantee that all your users will use the same hardware and OS configuration as your current machine.");
  14800. }
  14801. var rOpts = rendererDefaults(options);
  14802. rOpts.cy = cy;
  14803. cy._private.renderer = new RendererProto(rOpts);
  14804. this.notify('init');
  14805. },
  14806. destroyRenderer: function destroyRenderer() {
  14807. var cy = this;
  14808. cy.notify('destroy'); // destroy the renderer
  14809. var domEle = cy.container();
  14810. if (domEle) {
  14811. domEle._cyreg = null;
  14812. while (domEle.childNodes.length > 0) {
  14813. domEle.removeChild(domEle.childNodes[0]);
  14814. }
  14815. }
  14816. cy._private.renderer = null; // to be extra safe, remove the ref
  14817. cy.mutableElements().forEach(function (ele) {
  14818. var _p = ele._private;
  14819. _p.rscratch = {};
  14820. _p.rstyle = {};
  14821. _p.animation.current = [];
  14822. _p.animation.queue = [];
  14823. });
  14824. },
  14825. onRender: function onRender(fn) {
  14826. return this.on('render', fn);
  14827. },
  14828. offRender: function offRender(fn) {
  14829. return this.off('render', fn);
  14830. }
  14831. };
  14832. corefn$4.invalidateDimensions = corefn$4.resize;
  14833. var corefn$3 = {
  14834. // get a collection
  14835. // - empty collection on no args
  14836. // - collection of elements in the graph on selector arg
  14837. // - guarantee a returned collection when elements or collection specified
  14838. collection: function collection(eles, opts) {
  14839. if (string(eles)) {
  14840. return this.$(eles);
  14841. } else if (elementOrCollection(eles)) {
  14842. return eles.collection();
  14843. } else if (array(eles)) {
  14844. if (!opts) {
  14845. opts = {};
  14846. }
  14847. return new Collection(this, eles, opts.unique, opts.removed);
  14848. }
  14849. return new Collection(this);
  14850. },
  14851. nodes: function nodes(selector) {
  14852. var nodes = this.$(function (ele) {
  14853. return ele.isNode();
  14854. });
  14855. if (selector) {
  14856. return nodes.filter(selector);
  14857. }
  14858. return nodes;
  14859. },
  14860. edges: function edges(selector) {
  14861. var edges = this.$(function (ele) {
  14862. return ele.isEdge();
  14863. });
  14864. if (selector) {
  14865. return edges.filter(selector);
  14866. }
  14867. return edges;
  14868. },
  14869. // search the graph like jQuery
  14870. $: function $(selector) {
  14871. var eles = this._private.elements;
  14872. if (selector) {
  14873. return eles.filter(selector);
  14874. } else {
  14875. return eles.spawnSelf();
  14876. }
  14877. },
  14878. mutableElements: function mutableElements() {
  14879. return this._private.elements;
  14880. }
  14881. };
  14882. // aliases
  14883. corefn$3.elements = corefn$3.filter = corefn$3.$;
  14884. var styfn$8 = {};
  14885. // keys for style blocks, e.g. ttfftt
  14886. var TRUE = 't';
  14887. var FALSE = 'f';
  14888. // (potentially expensive calculation)
  14889. // apply the style to the element based on
  14890. // - its bypass
  14891. // - what selectors match it
  14892. styfn$8.apply = function (eles) {
  14893. var self = this;
  14894. var _p = self._private;
  14895. var cy = _p.cy;
  14896. var updatedEles = cy.collection();
  14897. for (var ie = 0; ie < eles.length; ie++) {
  14898. var ele = eles[ie];
  14899. var cxtMeta = self.getContextMeta(ele);
  14900. if (cxtMeta.empty) {
  14901. continue;
  14902. }
  14903. var cxtStyle = self.getContextStyle(cxtMeta);
  14904. var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);
  14905. if (ele._private.appliedInitStyle) {
  14906. self.updateTransitions(ele, app.diffProps);
  14907. } else {
  14908. ele._private.appliedInitStyle = true;
  14909. }
  14910. var hintsDiff = self.updateStyleHints(ele);
  14911. if (hintsDiff) {
  14912. updatedEles.push(ele);
  14913. }
  14914. } // for elements
  14915. return updatedEles;
  14916. };
  14917. styfn$8.getPropertiesDiff = function (oldCxtKey, newCxtKey) {
  14918. var self = this;
  14919. var cache = self._private.propDiffs = self._private.propDiffs || {};
  14920. var dualCxtKey = oldCxtKey + '-' + newCxtKey;
  14921. var cachedVal = cache[dualCxtKey];
  14922. if (cachedVal) {
  14923. return cachedVal;
  14924. }
  14925. var diffProps = [];
  14926. var addedProp = {};
  14927. for (var i = 0; i < self.length; i++) {
  14928. var cxt = self[i];
  14929. var oldHasCxt = oldCxtKey[i] === TRUE;
  14930. var newHasCxt = newCxtKey[i] === TRUE;
  14931. var cxtHasDiffed = oldHasCxt !== newHasCxt;
  14932. var cxtHasMappedProps = cxt.mappedProperties.length > 0;
  14933. if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {
  14934. var props = undefined;
  14935. if (cxtHasDiffed && cxtHasMappedProps) {
  14936. props = cxt.properties; // suffices b/c mappedProperties is a subset of properties
  14937. } else if (cxtHasDiffed) {
  14938. props = cxt.properties; // need to check them all
  14939. } else if (cxtHasMappedProps) {
  14940. props = cxt.mappedProperties; // only need to check mapped
  14941. }
  14942. for (var j = 0; j < props.length; j++) {
  14943. var prop = props[j];
  14944. var name = prop.name;
  14945. // if a later context overrides this property, then the fact that this context has switched/diffed doesn't matter
  14946. // (semi expensive check since it makes this function O(n^2) on context length, but worth it since overall result
  14947. // is cached)
  14948. var laterCxtOverrides = false;
  14949. for (var k = i + 1; k < self.length; k++) {
  14950. var laterCxt = self[k];
  14951. var hasLaterCxt = newCxtKey[k] === TRUE;
  14952. if (!hasLaterCxt) {
  14953. continue;
  14954. } // can't override unless the context is active
  14955. laterCxtOverrides = laterCxt.properties[prop.name] != null;
  14956. if (laterCxtOverrides) {
  14957. break;
  14958. } // exit early as long as one later context overrides
  14959. }
  14960. if (!addedProp[name] && !laterCxtOverrides) {
  14961. addedProp[name] = true;
  14962. diffProps.push(name);
  14963. }
  14964. } // for props
  14965. } // if
  14966. } // for contexts
  14967. cache[dualCxtKey] = diffProps;
  14968. return diffProps;
  14969. };
  14970. styfn$8.getContextMeta = function (ele) {
  14971. var self = this;
  14972. var cxtKey = '';
  14973. var diffProps;
  14974. var prevKey = ele._private.styleCxtKey || '';
  14975. // get the cxt key
  14976. for (var i = 0; i < self.length; i++) {
  14977. var context = self[i];
  14978. var contextSelectorMatches = context.selector && context.selector.matches(ele); // NB: context.selector may be null for 'core'
  14979. if (contextSelectorMatches) {
  14980. cxtKey += TRUE;
  14981. } else {
  14982. cxtKey += FALSE;
  14983. }
  14984. } // for context
  14985. diffProps = self.getPropertiesDiff(prevKey, cxtKey);
  14986. ele._private.styleCxtKey = cxtKey;
  14987. return {
  14988. key: cxtKey,
  14989. diffPropNames: diffProps,
  14990. empty: diffProps.length === 0
  14991. };
  14992. };
  14993. // gets a computed ele style object based on matched contexts
  14994. styfn$8.getContextStyle = function (cxtMeta) {
  14995. var cxtKey = cxtMeta.key;
  14996. var self = this;
  14997. var cxtStyles = this._private.contextStyles = this._private.contextStyles || {};
  14998. // if already computed style, returned cached copy
  14999. if (cxtStyles[cxtKey]) {
  15000. return cxtStyles[cxtKey];
  15001. }
  15002. var style = {
  15003. _private: {
  15004. key: cxtKey
  15005. }
  15006. };
  15007. for (var i = 0; i < self.length; i++) {
  15008. var cxt = self[i];
  15009. var hasCxt = cxtKey[i] === TRUE;
  15010. if (!hasCxt) {
  15011. continue;
  15012. }
  15013. for (var j = 0; j < cxt.properties.length; j++) {
  15014. var prop = cxt.properties[j];
  15015. style[prop.name] = prop;
  15016. }
  15017. }
  15018. cxtStyles[cxtKey] = style;
  15019. return style;
  15020. };
  15021. styfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {
  15022. var self = this;
  15023. var diffProps = cxtMeta.diffPropNames;
  15024. var retDiffProps = {};
  15025. var types = self.types;
  15026. for (var i = 0; i < diffProps.length; i++) {
  15027. var diffPropName = diffProps[i];
  15028. var cxtProp = cxtStyle[diffPropName];
  15029. var eleProp = ele.pstyle(diffPropName);
  15030. if (!cxtProp) {
  15031. // no context prop means delete
  15032. if (!eleProp) {
  15033. continue; // no existing prop means nothing needs to be removed
  15034. // nb affects initial application on mapped values like control-point-distances
  15035. } else if (eleProp.bypass) {
  15036. cxtProp = {
  15037. name: diffPropName,
  15038. deleteBypassed: true
  15039. };
  15040. } else {
  15041. cxtProp = {
  15042. name: diffPropName,
  15043. "delete": true
  15044. };
  15045. }
  15046. }
  15047. // save cycles when the context prop doesn't need to be applied
  15048. if (eleProp === cxtProp) {
  15049. continue;
  15050. }
  15051. // save cycles when a mapped context prop doesn't need to be applied
  15052. if (cxtProp.mapped === types.fn // context prop is function mapper
  15053. && eleProp != null // some props can be null even by default (e.g. a prop that overrides another one)
  15054. && eleProp.mapping != null // ele prop is a concrete value from from a mapper
  15055. && eleProp.mapping.value === cxtProp.value // the current prop on the ele is a flat prop value for the function mapper
  15056. ) {
  15057. // NB don't write to cxtProp, as it's shared among eles (stored in stylesheet)
  15058. var mapping = eleProp.mapping; // can write to mapping, as it's a per-ele copy
  15059. var fnValue = mapping.fnValue = cxtProp.value(ele); // temporarily cache the value in case of a miss
  15060. if (fnValue === mapping.prevFnValue) {
  15061. continue;
  15062. }
  15063. }
  15064. var retDiffProp = retDiffProps[diffPropName] = {
  15065. prev: eleProp
  15066. };
  15067. self.applyParsedProperty(ele, cxtProp);
  15068. retDiffProp.next = ele.pstyle(diffPropName);
  15069. if (retDiffProp.next && retDiffProp.next.bypass) {
  15070. retDiffProp.next = retDiffProp.next.bypassed;
  15071. }
  15072. }
  15073. return {
  15074. diffProps: retDiffProps
  15075. };
  15076. };
  15077. styfn$8.updateStyleHints = function (ele) {
  15078. var _p = ele._private;
  15079. var self = this;
  15080. var propNames = self.propertyGroupNames;
  15081. var propGrKeys = self.propertyGroupKeys;
  15082. var propHash = function propHash(ele, propNames, seedKey) {
  15083. return self.getPropertiesHash(ele, propNames, seedKey);
  15084. };
  15085. var oldStyleKey = _p.styleKey;
  15086. if (ele.removed()) {
  15087. return false;
  15088. }
  15089. var isNode = _p.group === 'nodes';
  15090. // get the style key hashes per prop group
  15091. // but lazily -- only use non-default prop values to reduce the number of hashes
  15092. //
  15093. var overriddenStyles = ele._private.style;
  15094. propNames = Object.keys(overriddenStyles);
  15095. for (var i = 0; i < propGrKeys.length; i++) {
  15096. var grKey = propGrKeys[i];
  15097. _p.styleKeys[grKey] = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  15098. }
  15099. var updateGrKey1 = function updateGrKey1(val, grKey) {
  15100. return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);
  15101. };
  15102. var updateGrKey2 = function updateGrKey2(val, grKey) {
  15103. return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);
  15104. };
  15105. var updateGrKey = function updateGrKey(val, grKey) {
  15106. updateGrKey1(val, grKey);
  15107. updateGrKey2(val, grKey);
  15108. };
  15109. var updateGrKeyWStr = function updateGrKeyWStr(strVal, grKey) {
  15110. for (var j = 0; j < strVal.length; j++) {
  15111. var ch = strVal.charCodeAt(j);
  15112. updateGrKey1(ch, grKey);
  15113. updateGrKey2(ch, grKey);
  15114. }
  15115. };
  15116. // - hashing works on 32 bit ints b/c we use bitwise ops
  15117. // - small numbers get cut off (e.g. 0.123 is seen as 0 by the hashing function)
  15118. // - raise up small numbers so more significant digits are seen by hashing
  15119. // - make small numbers larger than a normal value to avoid collisions
  15120. // - works in practice and it's relatively cheap
  15121. var N = 2000000000;
  15122. var cleanNum = function cleanNum(val) {
  15123. return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;
  15124. };
  15125. for (var _i = 0; _i < propNames.length; _i++) {
  15126. var name = propNames[_i];
  15127. var parsedProp = overriddenStyles[name];
  15128. if (parsedProp == null) {
  15129. continue;
  15130. }
  15131. var propInfo = this.properties[name];
  15132. var type = propInfo.type;
  15133. var _grKey = propInfo.groupKey;
  15134. var normalizedNumberVal = undefined;
  15135. if (propInfo.hashOverride != null) {
  15136. normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);
  15137. } else if (parsedProp.pfValue != null) {
  15138. normalizedNumberVal = parsedProp.pfValue;
  15139. }
  15140. // might not be a number if it allows enums
  15141. var numberVal = propInfo.enums == null ? parsedProp.value : null;
  15142. var haveNormNum = normalizedNumberVal != null;
  15143. var haveUnitedNum = numberVal != null;
  15144. var haveNum = haveNormNum || haveUnitedNum;
  15145. var units = parsedProp.units;
  15146. // numbers are cheaper to hash than strings
  15147. // 1 hash op vs n hash ops (for length n string)
  15148. if (type.number && haveNum && !type.multiple) {
  15149. var v = haveNormNum ? normalizedNumberVal : numberVal;
  15150. updateGrKey(cleanNum(v), _grKey);
  15151. if (!haveNormNum && units != null) {
  15152. updateGrKeyWStr(units, _grKey);
  15153. }
  15154. } else {
  15155. updateGrKeyWStr(parsedProp.strValue, _grKey);
  15156. }
  15157. }
  15158. // overall style key
  15159. //
  15160. var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  15161. for (var _i2 = 0; _i2 < propGrKeys.length; _i2++) {
  15162. var _grKey2 = propGrKeys[_i2];
  15163. var grHash = _p.styleKeys[_grKey2];
  15164. hash[0] = hashInt(grHash[0], hash[0]);
  15165. hash[1] = hashIntAlt(grHash[1], hash[1]);
  15166. }
  15167. _p.styleKey = combineHashes(hash[0], hash[1]);
  15168. // label dims
  15169. //
  15170. var sk = _p.styleKeys;
  15171. _p.labelDimsKey = combineHashesArray(sk.labelDimensions);
  15172. var labelKeys = propHash(ele, ['label'], sk.labelDimensions);
  15173. _p.labelKey = combineHashesArray(labelKeys);
  15174. _p.labelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, labelKeys));
  15175. if (!isNode) {
  15176. var sourceLabelKeys = propHash(ele, ['source-label'], sk.labelDimensions);
  15177. _p.sourceLabelKey = combineHashesArray(sourceLabelKeys);
  15178. _p.sourceLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, sourceLabelKeys));
  15179. var targetLabelKeys = propHash(ele, ['target-label'], sk.labelDimensions);
  15180. _p.targetLabelKey = combineHashesArray(targetLabelKeys);
  15181. _p.targetLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, targetLabelKeys));
  15182. }
  15183. // node
  15184. //
  15185. if (isNode) {
  15186. var _p$styleKeys = _p.styleKeys,
  15187. nodeBody = _p$styleKeys.nodeBody,
  15188. nodeBorder = _p$styleKeys.nodeBorder,
  15189. nodeOutline = _p$styleKeys.nodeOutline,
  15190. backgroundImage = _p$styleKeys.backgroundImage,
  15191. compound = _p$styleKeys.compound,
  15192. pie = _p$styleKeys.pie,
  15193. stripe = _p$styleKeys.stripe;
  15194. var nodeKeys = [nodeBody, nodeBorder, nodeOutline, backgroundImage, compound, pie, stripe].filter(function (k) {
  15195. return k != null;
  15196. }).reduce(hashArrays, [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT]);
  15197. _p.nodeKey = combineHashesArray(nodeKeys);
  15198. _p.hasPie = pie != null && pie[0] !== DEFAULT_HASH_SEED && pie[1] !== DEFAULT_HASH_SEED_ALT;
  15199. _p.hasStripe = stripe != null && stripe[0] !== DEFAULT_HASH_SEED && stripe[1] !== DEFAULT_HASH_SEED_ALT;
  15200. }
  15201. return oldStyleKey !== _p.styleKey;
  15202. };
  15203. styfn$8.clearStyleHints = function (ele) {
  15204. var _p = ele._private;
  15205. _p.styleCxtKey = '';
  15206. _p.styleKeys = {};
  15207. _p.styleKey = null;
  15208. _p.labelKey = null;
  15209. _p.labelStyleKey = null;
  15210. _p.sourceLabelKey = null;
  15211. _p.sourceLabelStyleKey = null;
  15212. _p.targetLabelKey = null;
  15213. _p.targetLabelStyleKey = null;
  15214. _p.nodeKey = null;
  15215. _p.hasPie = null;
  15216. _p.hasStripe = null;
  15217. };
  15218. // apply a property to the style (for internal use)
  15219. // returns whether application was successful
  15220. //
  15221. // now, this function flattens the property, and here's how:
  15222. //
  15223. // for parsedProp:{ bypass: true, deleteBypass: true }
  15224. // no property is generated, instead the bypass property in the
  15225. // element's style is replaced by what's pointed to by the `bypassed`
  15226. // field in the bypass property (i.e. restoring the property the
  15227. // bypass was overriding)
  15228. //
  15229. // for parsedProp:{ mapped: truthy }
  15230. // the generated flattenedProp:{ mapping: prop }
  15231. //
  15232. // for parsedProp:{ bypass: true }
  15233. // the generated flattenedProp:{ bypassed: parsedProp }
  15234. styfn$8.applyParsedProperty = function (ele, parsedProp) {
  15235. var self = this;
  15236. var prop = parsedProp;
  15237. var style = ele._private.style;
  15238. var flatProp;
  15239. var types = self.types;
  15240. var type = self.properties[prop.name].type;
  15241. var propIsBypass = prop.bypass;
  15242. var origProp = style[prop.name];
  15243. var origPropIsBypass = origProp && origProp.bypass;
  15244. var _p = ele._private;
  15245. var flatPropMapping = 'mapping';
  15246. var getVal = function getVal(p) {
  15247. if (p == null) {
  15248. return null;
  15249. } else if (p.pfValue != null) {
  15250. return p.pfValue;
  15251. } else {
  15252. return p.value;
  15253. }
  15254. };
  15255. var checkTriggers = function checkTriggers() {
  15256. var fromVal = getVal(origProp);
  15257. var toVal = getVal(prop);
  15258. self.checkTriggers(ele, prop.name, fromVal, toVal);
  15259. };
  15260. // edge sanity checks to prevent the client from making serious mistakes
  15261. if (parsedProp.name === 'curve-style' && ele.isEdge() && (
  15262. // loops must be bundled beziers
  15263. parsedProp.value !== 'bezier' && ele.isLoop() ||
  15264. // edges connected to compound nodes can not be haystacks
  15265. parsedProp.value === 'haystack' && (ele.source().isParent() || ele.target().isParent()))) {
  15266. prop = parsedProp = this.parse(parsedProp.name, 'bezier', propIsBypass);
  15267. }
  15268. if (prop["delete"]) {
  15269. // delete the property and use the default value on falsey value
  15270. style[prop.name] = undefined;
  15271. checkTriggers();
  15272. return true;
  15273. }
  15274. if (prop.deleteBypassed) {
  15275. // delete the property that the
  15276. if (!origProp) {
  15277. checkTriggers();
  15278. return true; // can't delete if no prop
  15279. } else if (origProp.bypass) {
  15280. // delete bypassed
  15281. origProp.bypassed = undefined;
  15282. checkTriggers();
  15283. return true;
  15284. } else {
  15285. return false; // we're unsuccessful deleting the bypassed
  15286. }
  15287. }
  15288. // check if we need to delete the current bypass
  15289. if (prop.deleteBypass) {
  15290. // then this property is just here to indicate we need to delete
  15291. if (!origProp) {
  15292. checkTriggers();
  15293. return true; // property is already not defined
  15294. } else if (origProp.bypass) {
  15295. // then replace the bypass property with the original
  15296. // because the bypassed property was already applied (and therefore parsed), we can just replace it (no reapplying necessary)
  15297. style[prop.name] = origProp.bypassed;
  15298. checkTriggers();
  15299. return true;
  15300. } else {
  15301. return false; // we're unsuccessful deleting the bypass
  15302. }
  15303. }
  15304. var printMappingErr = function printMappingErr() {
  15305. warn('Do not assign mappings to elements without corresponding data (i.e. ele `' + ele.id() + '` has no mapping for property `' + prop.name + '` with data field `' + prop.field + '`); try a `[' + prop.field + ']` selector to limit scope to elements with `' + prop.field + '` defined');
  15306. };
  15307. // put the property in the style objects
  15308. switch (prop.mapped) {
  15309. // flatten the property if mapped
  15310. case types.mapData:
  15311. {
  15312. // flatten the field (e.g. data.foo.bar)
  15313. var fields = prop.field.split('.');
  15314. var fieldVal = _p.data;
  15315. for (var i = 0; i < fields.length && fieldVal; i++) {
  15316. var field = fields[i];
  15317. fieldVal = fieldVal[field];
  15318. }
  15319. if (fieldVal == null) {
  15320. printMappingErr();
  15321. return false;
  15322. }
  15323. var percent;
  15324. if (!number$1(fieldVal)) {
  15325. // then don't apply and fall back on the existing style
  15326. warn('Do not use continuous mappers without specifying numeric data (i.e. `' + prop.field + ': ' + fieldVal + '` for `' + ele.id() + '` is non-numeric)');
  15327. return false;
  15328. } else {
  15329. var fieldWidth = prop.fieldMax - prop.fieldMin;
  15330. if (fieldWidth === 0) {
  15331. // safety check -- not strictly necessary as no props of zero range should be passed here
  15332. percent = 0;
  15333. } else {
  15334. percent = (fieldVal - prop.fieldMin) / fieldWidth;
  15335. }
  15336. }
  15337. // make sure to bound percent value
  15338. if (percent < 0) {
  15339. percent = 0;
  15340. } else if (percent > 1) {
  15341. percent = 1;
  15342. }
  15343. if (type.color) {
  15344. var r1 = prop.valueMin[0];
  15345. var r2 = prop.valueMax[0];
  15346. var g1 = prop.valueMin[1];
  15347. var g2 = prop.valueMax[1];
  15348. var b1 = prop.valueMin[2];
  15349. var b2 = prop.valueMax[2];
  15350. var a1 = prop.valueMin[3] == null ? 1 : prop.valueMin[3];
  15351. var a2 = prop.valueMax[3] == null ? 1 : prop.valueMax[3];
  15352. var clr = [Math.round(r1 + (r2 - r1) * percent), Math.round(g1 + (g2 - g1) * percent), Math.round(b1 + (b2 - b1) * percent), Math.round(a1 + (a2 - a1) * percent)];
  15353. flatProp = {
  15354. // colours are simple, so just create the flat property instead of expensive string parsing
  15355. bypass: prop.bypass,
  15356. // we're a bypass if the mapping property is a bypass
  15357. name: prop.name,
  15358. value: clr,
  15359. strValue: 'rgb(' + clr[0] + ', ' + clr[1] + ', ' + clr[2] + ')'
  15360. };
  15361. } else if (type.number) {
  15362. var calcValue = prop.valueMin + (prop.valueMax - prop.valueMin) * percent;
  15363. flatProp = this.parse(prop.name, calcValue, prop.bypass, flatPropMapping);
  15364. } else {
  15365. return false; // can only map to colours and numbers
  15366. }
  15367. if (!flatProp) {
  15368. // if we can't flatten the property, then don't apply the property and fall back on the existing style
  15369. printMappingErr();
  15370. return false;
  15371. }
  15372. flatProp.mapping = prop; // keep a reference to the mapping
  15373. prop = flatProp; // the flattened (mapped) property is the one we want
  15374. break;
  15375. }
  15376. // direct mapping
  15377. case types.data:
  15378. {
  15379. // flatten the field (e.g. data.foo.bar)
  15380. var _fields = prop.field.split('.');
  15381. var _fieldVal = _p.data;
  15382. for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {
  15383. var _field = _fields[_i3];
  15384. _fieldVal = _fieldVal[_field];
  15385. }
  15386. if (_fieldVal != null) {
  15387. flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);
  15388. }
  15389. if (!flatProp) {
  15390. // if we can't flatten the property, then don't apply and fall back on the existing style
  15391. printMappingErr();
  15392. return false;
  15393. }
  15394. flatProp.mapping = prop; // keep a reference to the mapping
  15395. prop = flatProp; // the flattened (mapped) property is the one we want
  15396. break;
  15397. }
  15398. case types.fn:
  15399. {
  15400. var fn = prop.value;
  15401. var fnRetVal = prop.fnValue != null ? prop.fnValue : fn(ele); // check for cached value before calling function
  15402. prop.prevFnValue = fnRetVal;
  15403. if (fnRetVal == null) {
  15404. warn('Custom function mappers may not return null (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is null)');
  15405. return false;
  15406. }
  15407. flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);
  15408. if (!flatProp) {
  15409. warn('Custom function mappers may not return invalid values for the property type (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is invalid)');
  15410. return false;
  15411. }
  15412. flatProp.mapping = copy(prop); // keep a reference to the mapping
  15413. prop = flatProp; // the flattened (mapped) property is the one we want
  15414. break;
  15415. }
  15416. case undefined:
  15417. break;
  15418. // just set the property
  15419. default:
  15420. return false;
  15421. // not a valid mapping
  15422. }
  15423. // if the property is a bypass property, then link the resultant property to the original one
  15424. if (propIsBypass) {
  15425. if (origPropIsBypass) {
  15426. // then this bypass overrides the existing one
  15427. prop.bypassed = origProp.bypassed; // steal bypassed prop from old bypass
  15428. } else {
  15429. // then link the orig prop to the new bypass
  15430. prop.bypassed = origProp;
  15431. }
  15432. style[prop.name] = prop; // and set
  15433. } else {
  15434. // prop is not bypass
  15435. if (origPropIsBypass) {
  15436. // then keep the orig prop (since it's a bypass) and link to the new prop
  15437. origProp.bypassed = prop;
  15438. } else {
  15439. // then just replace the old prop with the new one
  15440. style[prop.name] = prop;
  15441. }
  15442. }
  15443. checkTriggers();
  15444. return true;
  15445. };
  15446. styfn$8.cleanElements = function (eles, keepBypasses) {
  15447. for (var i = 0; i < eles.length; i++) {
  15448. var ele = eles[i];
  15449. this.clearStyleHints(ele);
  15450. ele.dirtyCompoundBoundsCache();
  15451. ele.dirtyBoundingBoxCache();
  15452. if (!keepBypasses) {
  15453. ele._private.style = {};
  15454. } else {
  15455. var style = ele._private.style;
  15456. var propNames = Object.keys(style);
  15457. for (var j = 0; j < propNames.length; j++) {
  15458. var propName = propNames[j];
  15459. var eleProp = style[propName];
  15460. if (eleProp != null) {
  15461. if (eleProp.bypass) {
  15462. eleProp.bypassed = null;
  15463. } else {
  15464. style[propName] = null;
  15465. }
  15466. }
  15467. }
  15468. }
  15469. }
  15470. };
  15471. // updates the visual style for all elements (useful for manual style modification after init)
  15472. styfn$8.update = function () {
  15473. var cy = this._private.cy;
  15474. var eles = cy.mutableElements();
  15475. eles.updateStyle();
  15476. };
  15477. // diffProps : { name => { prev, next } }
  15478. styfn$8.updateTransitions = function (ele, diffProps) {
  15479. var self = this;
  15480. var _p = ele._private;
  15481. var props = ele.pstyle('transition-property').value;
  15482. var duration = ele.pstyle('transition-duration').pfValue;
  15483. var delay = ele.pstyle('transition-delay').pfValue;
  15484. if (props.length > 0 && duration > 0) {
  15485. var style = {};
  15486. // build up the style to animate towards
  15487. var anyPrev = false;
  15488. for (var i = 0; i < props.length; i++) {
  15489. var prop = props[i];
  15490. var styProp = ele.pstyle(prop);
  15491. var diffProp = diffProps[prop];
  15492. if (!diffProp) {
  15493. continue;
  15494. }
  15495. var prevProp = diffProp.prev;
  15496. var fromProp = prevProp;
  15497. var toProp = diffProp.next != null ? diffProp.next : styProp;
  15498. var diff = false;
  15499. var initVal = undefined;
  15500. var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)
  15501. if (!fromProp) {
  15502. continue;
  15503. }
  15504. // consider px values
  15505. if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {
  15506. diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy
  15507. initVal = fromProp.pfValue + initDt * diff;
  15508. // consider numerical values
  15509. } else if (number$1(fromProp.value) && number$1(toProp.value)) {
  15510. diff = toProp.value - fromProp.value; // nonzero is truthy
  15511. initVal = fromProp.value + initDt * diff;
  15512. // consider colour values
  15513. } else if (array(fromProp.value) && array(toProp.value)) {
  15514. diff = fromProp.value[0] !== toProp.value[0] || fromProp.value[1] !== toProp.value[1] || fromProp.value[2] !== toProp.value[2];
  15515. initVal = fromProp.strValue;
  15516. }
  15517. // the previous value is good for an animation only if it's different
  15518. if (diff) {
  15519. style[prop] = toProp.strValue; // to val
  15520. this.applyBypass(ele, prop, initVal); // from val
  15521. anyPrev = true;
  15522. }
  15523. } // end if props allow ani
  15524. // can't transition if there's nothing previous to transition from
  15525. if (!anyPrev) {
  15526. return;
  15527. }
  15528. _p.transitioning = true;
  15529. new Promise$1(function (resolve) {
  15530. if (delay > 0) {
  15531. ele.delayAnimation(delay).play().promise().then(resolve);
  15532. } else {
  15533. resolve();
  15534. }
  15535. }).then(function () {
  15536. return ele.animation({
  15537. style: style,
  15538. duration: duration,
  15539. easing: ele.pstyle('transition-timing-function').value,
  15540. queue: false
  15541. }).play().promise();
  15542. }).then(function () {
  15543. // if( !isBypass ){
  15544. self.removeBypasses(ele, props);
  15545. ele.emitAndNotify('style');
  15546. // }
  15547. _p.transitioning = false;
  15548. });
  15549. } else if (_p.transitioning) {
  15550. this.removeBypasses(ele, props);
  15551. ele.emitAndNotify('style');
  15552. _p.transitioning = false;
  15553. }
  15554. };
  15555. styfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {
  15556. var prop = this.properties[name];
  15557. var triggerCheck = getTrigger(prop);
  15558. if (ele.removed()) {
  15559. return;
  15560. }
  15561. if (triggerCheck != null && triggerCheck(fromValue, toValue, ele)) {
  15562. onTrigger(prop);
  15563. }
  15564. };
  15565. styfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {
  15566. var _this = this;
  15567. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15568. return prop.triggersZOrder;
  15569. }, function () {
  15570. _this._private.cy.notify('zorder', ele);
  15571. });
  15572. };
  15573. styfn$8.checkBoundsTrigger = function (ele, name, fromValue, toValue) {
  15574. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15575. return prop.triggersBounds;
  15576. }, function (prop) {
  15577. ele.dirtyCompoundBoundsCache();
  15578. ele.dirtyBoundingBoxCache();
  15579. });
  15580. };
  15581. styfn$8.checkConnectedEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  15582. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15583. return prop.triggersBoundsOfConnectedEdges;
  15584. }, function (prop) {
  15585. ele.connectedEdges().forEach(function (edge) {
  15586. edge.dirtyBoundingBoxCache();
  15587. });
  15588. });
  15589. };
  15590. styfn$8.checkParallelEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  15591. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15592. return prop.triggersBoundsOfParallelEdges;
  15593. }, function (prop) {
  15594. ele.parallelEdges().forEach(function (pllEdge) {
  15595. pllEdge.dirtyBoundingBoxCache();
  15596. });
  15597. });
  15598. };
  15599. styfn$8.checkTriggers = function (ele, name, fromValue, toValue) {
  15600. ele.dirtyStyleCache();
  15601. this.checkZOrderTrigger(ele, name, fromValue, toValue);
  15602. this.checkBoundsTrigger(ele, name, fromValue, toValue);
  15603. this.checkConnectedEdgesBoundsTrigger(ele, name, fromValue, toValue);
  15604. this.checkParallelEdgesBoundsTrigger(ele, name, fromValue, toValue);
  15605. };
  15606. var styfn$7 = {};
  15607. // bypasses are applied to an existing style on an element, and just tacked on temporarily
  15608. // returns true iff application was successful for at least 1 specified property
  15609. styfn$7.applyBypass = function (eles, name, value, updateTransitions) {
  15610. var self = this;
  15611. var props = [];
  15612. var isBypass = true;
  15613. // put all the properties (can specify one or many) in an array after parsing them
  15614. if (name === '*' || name === '**') {
  15615. // apply to all property names
  15616. if (value !== undefined) {
  15617. for (var i = 0; i < self.properties.length; i++) {
  15618. var prop = self.properties[i];
  15619. var _name = prop.name;
  15620. var parsedProp = this.parse(_name, value, true);
  15621. if (parsedProp) {
  15622. props.push(parsedProp);
  15623. }
  15624. }
  15625. }
  15626. } else if (string(name)) {
  15627. // then parse the single property
  15628. var _parsedProp = this.parse(name, value, true);
  15629. if (_parsedProp) {
  15630. props.push(_parsedProp);
  15631. }
  15632. } else if (plainObject(name)) {
  15633. // then parse each property
  15634. var specifiedProps = name;
  15635. updateTransitions = value;
  15636. var names = Object.keys(specifiedProps);
  15637. for (var _i = 0; _i < names.length; _i++) {
  15638. var _name2 = names[_i];
  15639. var _value = specifiedProps[_name2];
  15640. if (_value === undefined) {
  15641. // try camel case name too
  15642. _value = specifiedProps[dash2camel(_name2)];
  15643. }
  15644. if (_value !== undefined) {
  15645. var _parsedProp2 = this.parse(_name2, _value, true);
  15646. if (_parsedProp2) {
  15647. props.push(_parsedProp2);
  15648. }
  15649. }
  15650. }
  15651. } else {
  15652. // can't do anything without well defined properties
  15653. return false;
  15654. }
  15655. // we've failed if there are no valid properties
  15656. if (props.length === 0) {
  15657. return false;
  15658. }
  15659. // now, apply the bypass properties on the elements
  15660. var ret = false; // return true if at least one succesful bypass applied
  15661. for (var _i2 = 0; _i2 < eles.length; _i2++) {
  15662. // for each ele
  15663. var ele = eles[_i2];
  15664. var diffProps = {};
  15665. var diffProp = undefined;
  15666. for (var j = 0; j < props.length; j++) {
  15667. // for each prop
  15668. var _prop = props[j];
  15669. if (updateTransitions) {
  15670. var prevProp = ele.pstyle(_prop.name);
  15671. diffProp = diffProps[_prop.name] = {
  15672. prev: prevProp
  15673. };
  15674. }
  15675. ret = this.applyParsedProperty(ele, copy(_prop)) || ret;
  15676. if (updateTransitions) {
  15677. diffProp.next = ele.pstyle(_prop.name);
  15678. }
  15679. } // for props
  15680. if (ret) {
  15681. this.updateStyleHints(ele);
  15682. }
  15683. if (updateTransitions) {
  15684. this.updateTransitions(ele, diffProps, isBypass);
  15685. }
  15686. } // for eles
  15687. return ret;
  15688. };
  15689. // only useful in specific cases like animation
  15690. styfn$7.overrideBypass = function (eles, name, value) {
  15691. name = camel2dash(name);
  15692. for (var i = 0; i < eles.length; i++) {
  15693. var ele = eles[i];
  15694. var prop = ele._private.style[name];
  15695. var type = this.properties[name].type;
  15696. var isColor = type.color;
  15697. var isMulti = type.mutiple;
  15698. var oldValue = !prop ? null : prop.pfValue != null ? prop.pfValue : prop.value;
  15699. if (!prop || !prop.bypass) {
  15700. // need a bypass if one doesn't exist
  15701. this.applyBypass(ele, name, value);
  15702. } else {
  15703. prop.value = value;
  15704. if (prop.pfValue != null) {
  15705. prop.pfValue = value;
  15706. }
  15707. if (isColor) {
  15708. prop.strValue = 'rgb(' + value.join(',') + ')';
  15709. } else if (isMulti) {
  15710. prop.strValue = value.join(' ');
  15711. } else {
  15712. prop.strValue = '' + value;
  15713. }
  15714. this.updateStyleHints(ele);
  15715. }
  15716. this.checkTriggers(ele, name, oldValue, value);
  15717. }
  15718. };
  15719. styfn$7.removeAllBypasses = function (eles, updateTransitions) {
  15720. return this.removeBypasses(eles, this.propertyNames, updateTransitions);
  15721. };
  15722. styfn$7.removeBypasses = function (eles, props, updateTransitions) {
  15723. var isBypass = true;
  15724. for (var j = 0; j < eles.length; j++) {
  15725. var ele = eles[j];
  15726. var diffProps = {};
  15727. for (var i = 0; i < props.length; i++) {
  15728. var name = props[i];
  15729. var prop = this.properties[name];
  15730. var prevProp = ele.pstyle(prop.name);
  15731. if (!prevProp || !prevProp.bypass) {
  15732. // if a bypass doesn't exist for the prop, nothing needs to be removed
  15733. continue;
  15734. }
  15735. var value = ''; // empty => remove bypass
  15736. var parsedProp = this.parse(name, value, true);
  15737. var diffProp = diffProps[prop.name] = {
  15738. prev: prevProp
  15739. };
  15740. this.applyParsedProperty(ele, parsedProp);
  15741. diffProp.next = ele.pstyle(prop.name);
  15742. } // for props
  15743. this.updateStyleHints(ele);
  15744. if (updateTransitions) {
  15745. this.updateTransitions(ele, diffProps, isBypass);
  15746. }
  15747. } // for eles
  15748. };
  15749. var styfn$6 = {};
  15750. // gets what an em size corresponds to in pixels relative to a dom element
  15751. styfn$6.getEmSizeInPixels = function () {
  15752. var px = this.containerCss('font-size');
  15753. if (px != null) {
  15754. return parseFloat(px);
  15755. } else {
  15756. return 1; // for headless
  15757. }
  15758. };
  15759. // gets css property from the core container
  15760. styfn$6.containerCss = function (propName) {
  15761. var cy = this._private.cy;
  15762. var domElement = cy.container();
  15763. var containerWindow = cy.window();
  15764. if (containerWindow && domElement && containerWindow.getComputedStyle) {
  15765. return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);
  15766. }
  15767. };
  15768. var styfn$5 = {};
  15769. // gets the rendered style for an element
  15770. styfn$5.getRenderedStyle = function (ele, prop) {
  15771. if (prop) {
  15772. return this.getStylePropertyValue(ele, prop, true);
  15773. } else {
  15774. return this.getRawStyle(ele, true);
  15775. }
  15776. };
  15777. // gets the raw style for an element
  15778. styfn$5.getRawStyle = function (ele, isRenderedVal) {
  15779. var self = this;
  15780. ele = ele[0]; // insure it's an element
  15781. if (ele) {
  15782. var rstyle = {};
  15783. for (var i = 0; i < self.properties.length; i++) {
  15784. var prop = self.properties[i];
  15785. var val = self.getStylePropertyValue(ele, prop.name, isRenderedVal);
  15786. if (val != null) {
  15787. rstyle[prop.name] = val;
  15788. rstyle[dash2camel(prop.name)] = val;
  15789. }
  15790. }
  15791. return rstyle;
  15792. }
  15793. };
  15794. styfn$5.getIndexedStyle = function (ele, property, subproperty, index) {
  15795. var pstyle = ele.pstyle(property)[subproperty][index];
  15796. return pstyle != null ? pstyle : ele.cy().style().getDefaultProperty(property)[subproperty][0];
  15797. };
  15798. styfn$5.getStylePropertyValue = function (ele, propName, isRenderedVal) {
  15799. var self = this;
  15800. ele = ele[0]; // insure it's an element
  15801. if (ele) {
  15802. var prop = self.properties[propName];
  15803. if (prop.alias) {
  15804. prop = prop.pointsTo;
  15805. }
  15806. var type = prop.type;
  15807. var styleProp = ele.pstyle(prop.name);
  15808. if (styleProp) {
  15809. var value = styleProp.value,
  15810. units = styleProp.units,
  15811. strValue = styleProp.strValue;
  15812. if (isRenderedVal && type.number && value != null && number$1(value)) {
  15813. var zoom = ele.cy().zoom();
  15814. var getRenderedValue = function getRenderedValue(val) {
  15815. return val * zoom;
  15816. };
  15817. var getValueStringWithUnits = function getValueStringWithUnits(val, units) {
  15818. return getRenderedValue(val) + units;
  15819. };
  15820. var isArrayValue = array(value);
  15821. var haveUnits = isArrayValue ? units.every(function (u) {
  15822. return u != null;
  15823. }) : units != null;
  15824. if (haveUnits) {
  15825. if (isArrayValue) {
  15826. return value.map(function (v, i) {
  15827. return getValueStringWithUnits(v, units[i]);
  15828. }).join(' ');
  15829. } else {
  15830. return getValueStringWithUnits(value, units);
  15831. }
  15832. } else {
  15833. if (isArrayValue) {
  15834. return value.map(function (v) {
  15835. return string(v) ? v : '' + getRenderedValue(v);
  15836. }).join(' ');
  15837. } else {
  15838. return '' + getRenderedValue(value);
  15839. }
  15840. }
  15841. } else if (strValue != null) {
  15842. return strValue;
  15843. }
  15844. }
  15845. return null;
  15846. }
  15847. };
  15848. styfn$5.getAnimationStartStyle = function (ele, aniProps) {
  15849. var rstyle = {};
  15850. for (var i = 0; i < aniProps.length; i++) {
  15851. var aniProp = aniProps[i];
  15852. var name = aniProp.name;
  15853. var styleProp = ele.pstyle(name);
  15854. if (styleProp !== undefined) {
  15855. // then make a prop of it
  15856. if (plainObject(styleProp)) {
  15857. styleProp = this.parse(name, styleProp.strValue);
  15858. } else {
  15859. styleProp = this.parse(name, styleProp);
  15860. }
  15861. }
  15862. if (styleProp) {
  15863. rstyle[name] = styleProp;
  15864. }
  15865. }
  15866. return rstyle;
  15867. };
  15868. styfn$5.getPropsList = function (propsObj) {
  15869. var self = this;
  15870. var rstyle = [];
  15871. var style = propsObj;
  15872. var props = self.properties;
  15873. if (style) {
  15874. var names = Object.keys(style);
  15875. for (var i = 0; i < names.length; i++) {
  15876. var name = names[i];
  15877. var val = style[name];
  15878. var prop = props[name] || props[camel2dash(name)];
  15879. var styleProp = this.parse(prop.name, val);
  15880. if (styleProp) {
  15881. rstyle.push(styleProp);
  15882. }
  15883. }
  15884. }
  15885. return rstyle;
  15886. };
  15887. styfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {
  15888. var hash = seed.slice();
  15889. var name, val, strVal, chVal;
  15890. var i, j;
  15891. for (i = 0; i < propNames.length; i++) {
  15892. name = propNames[i];
  15893. val = ele.pstyle(name, false);
  15894. if (val == null) {
  15895. continue;
  15896. } else if (val.pfValue != null) {
  15897. hash[0] = hashInt(chVal, hash[0]);
  15898. hash[1] = hashIntAlt(chVal, hash[1]);
  15899. } else {
  15900. strVal = val.strValue;
  15901. for (j = 0; j < strVal.length; j++) {
  15902. chVal = strVal.charCodeAt(j);
  15903. hash[0] = hashInt(chVal, hash[0]);
  15904. hash[1] = hashIntAlt(chVal, hash[1]);
  15905. }
  15906. }
  15907. }
  15908. return hash;
  15909. };
  15910. styfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;
  15911. var styfn$4 = {};
  15912. styfn$4.appendFromJson = function (json) {
  15913. var style = this;
  15914. for (var i = 0; i < json.length; i++) {
  15915. var context = json[i];
  15916. var selector = context.selector;
  15917. var props = context.style || context.css;
  15918. var names = Object.keys(props);
  15919. style.selector(selector); // apply selector
  15920. for (var j = 0; j < names.length; j++) {
  15921. var name = names[j];
  15922. var value = props[name];
  15923. style.css(name, value); // apply property
  15924. }
  15925. }
  15926. return style;
  15927. };
  15928. // accessible cy.style() function
  15929. styfn$4.fromJson = function (json) {
  15930. var style = this;
  15931. style.resetToDefault();
  15932. style.appendFromJson(json);
  15933. return style;
  15934. };
  15935. // get json from cy.style() api
  15936. styfn$4.json = function () {
  15937. var json = [];
  15938. for (var i = this.defaultLength; i < this.length; i++) {
  15939. var cxt = this[i];
  15940. var selector = cxt.selector;
  15941. var props = cxt.properties;
  15942. var css = {};
  15943. for (var j = 0; j < props.length; j++) {
  15944. var prop = props[j];
  15945. css[prop.name] = prop.strValue;
  15946. }
  15947. json.push({
  15948. selector: !selector ? 'core' : selector.toString(),
  15949. style: css
  15950. });
  15951. }
  15952. return json;
  15953. };
  15954. var styfn$3 = {};
  15955. styfn$3.appendFromString = function (string) {
  15956. var self = this;
  15957. var style = this;
  15958. var remaining = '' + string;
  15959. var selAndBlockStr;
  15960. var blockRem;
  15961. var propAndValStr;
  15962. // remove comments from the style string
  15963. remaining = remaining.replace(/[/][*](\s|.)+?[*][/]/g, '');
  15964. function removeSelAndBlockFromRemaining() {
  15965. // remove the parsed selector and block from the remaining text to parse
  15966. if (remaining.length > selAndBlockStr.length) {
  15967. remaining = remaining.substr(selAndBlockStr.length);
  15968. } else {
  15969. remaining = '';
  15970. }
  15971. }
  15972. function removePropAndValFromRem() {
  15973. // remove the parsed property and value from the remaining block text to parse
  15974. if (blockRem.length > propAndValStr.length) {
  15975. blockRem = blockRem.substr(propAndValStr.length);
  15976. } else {
  15977. blockRem = '';
  15978. }
  15979. }
  15980. for (;;) {
  15981. var nothingLeftToParse = remaining.match(/^\s*$/);
  15982. if (nothingLeftToParse) {
  15983. break;
  15984. }
  15985. var selAndBlock = remaining.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);
  15986. if (!selAndBlock) {
  15987. warn('Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: ' + remaining);
  15988. break;
  15989. }
  15990. selAndBlockStr = selAndBlock[0];
  15991. // parse the selector
  15992. var selectorStr = selAndBlock[1];
  15993. if (selectorStr !== 'core') {
  15994. var selector = new Selector(selectorStr);
  15995. if (selector.invalid) {
  15996. warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr);
  15997. // skip this selector and block
  15998. removeSelAndBlockFromRemaining();
  15999. continue;
  16000. }
  16001. }
  16002. // parse the block of properties and values
  16003. var blockStr = selAndBlock[2];
  16004. var invalidBlock = false;
  16005. blockRem = blockStr;
  16006. var props = [];
  16007. for (;;) {
  16008. var _nothingLeftToParse = blockRem.match(/^\s*$/);
  16009. if (_nothingLeftToParse) {
  16010. break;
  16011. }
  16012. var propAndVal = blockRem.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);
  16013. if (!propAndVal) {
  16014. warn('Skipping parsing of block: Invalid formatting of style property and value definitions found in:' + blockStr);
  16015. invalidBlock = true;
  16016. break;
  16017. }
  16018. propAndValStr = propAndVal[0];
  16019. var propStr = propAndVal[1];
  16020. var valStr = propAndVal[2];
  16021. var prop = self.properties[propStr];
  16022. if (!prop) {
  16023. warn('Skipping property: Invalid property name in: ' + propAndValStr);
  16024. // skip this property in the block
  16025. removePropAndValFromRem();
  16026. continue;
  16027. }
  16028. var parsedProp = style.parse(propStr, valStr);
  16029. if (!parsedProp) {
  16030. warn('Skipping property: Invalid property definition in: ' + propAndValStr);
  16031. // skip this property in the block
  16032. removePropAndValFromRem();
  16033. continue;
  16034. }
  16035. props.push({
  16036. name: propStr,
  16037. val: valStr
  16038. });
  16039. removePropAndValFromRem();
  16040. }
  16041. if (invalidBlock) {
  16042. removeSelAndBlockFromRemaining();
  16043. break;
  16044. }
  16045. // put the parsed block in the style
  16046. style.selector(selectorStr);
  16047. for (var i = 0; i < props.length; i++) {
  16048. var _prop = props[i];
  16049. style.css(_prop.name, _prop.val);
  16050. }
  16051. removeSelAndBlockFromRemaining();
  16052. }
  16053. return style;
  16054. };
  16055. styfn$3.fromString = function (string) {
  16056. var style = this;
  16057. style.resetToDefault();
  16058. style.appendFromString(string);
  16059. return style;
  16060. };
  16061. var styfn$2 = {};
  16062. (function () {
  16063. var number$1 = number;
  16064. var rgba = rgbaNoBackRefs;
  16065. var hsla = hslaNoBackRefs;
  16066. var hex3$1 = hex3;
  16067. var hex6$1 = hex6;
  16068. var data = function data(prefix) {
  16069. return '^' + prefix + '\\s*\\(\\s*([\\w\\.]+)\\s*\\)$';
  16070. };
  16071. var mapData = function mapData(prefix) {
  16072. var mapArg = number$1 + '|\\w+|' + rgba + '|' + hsla + '|' + hex3$1 + '|' + hex6$1;
  16073. return '^' + prefix + '\\s*\\(([\\w\\.]+)\\s*\\,\\s*(' + number$1 + ')\\s*\\,\\s*(' + number$1 + ')\\s*,\\s*(' + mapArg + ')\\s*\\,\\s*(' + mapArg + ')\\)$';
  16074. };
  16075. var urlRegexes = ['^url\\s*\\(\\s*[\'"]?(.+?)[\'"]?\\s*\\)$', '^(none)$', '^(.+)$'];
  16076. // each visual style property has a type and needs to be validated according to it
  16077. styfn$2.types = {
  16078. time: {
  16079. number: true,
  16080. min: 0,
  16081. units: 's|ms',
  16082. implicitUnits: 'ms'
  16083. },
  16084. percent: {
  16085. number: true,
  16086. min: 0,
  16087. max: 100,
  16088. units: '%',
  16089. implicitUnits: '%'
  16090. },
  16091. percentages: {
  16092. number: true,
  16093. min: 0,
  16094. max: 100,
  16095. units: '%',
  16096. implicitUnits: '%',
  16097. multiple: true
  16098. },
  16099. zeroOneNumber: {
  16100. number: true,
  16101. min: 0,
  16102. max: 1,
  16103. unitless: true
  16104. },
  16105. zeroOneNumbers: {
  16106. number: true,
  16107. min: 0,
  16108. max: 1,
  16109. unitless: true,
  16110. multiple: true
  16111. },
  16112. nOneOneNumber: {
  16113. number: true,
  16114. min: -1,
  16115. max: 1,
  16116. unitless: true
  16117. },
  16118. nonNegativeInt: {
  16119. number: true,
  16120. min: 0,
  16121. integer: true,
  16122. unitless: true
  16123. },
  16124. nonNegativeNumber: {
  16125. number: true,
  16126. min: 0,
  16127. unitless: true
  16128. },
  16129. position: {
  16130. enums: ['parent', 'origin']
  16131. },
  16132. nodeSize: {
  16133. number: true,
  16134. min: 0,
  16135. enums: ['label']
  16136. },
  16137. number: {
  16138. number: true,
  16139. unitless: true
  16140. },
  16141. numbers: {
  16142. number: true,
  16143. unitless: true,
  16144. multiple: true
  16145. },
  16146. positiveNumber: {
  16147. number: true,
  16148. unitless: true,
  16149. min: 0,
  16150. strictMin: true
  16151. },
  16152. size: {
  16153. number: true,
  16154. min: 0
  16155. },
  16156. bidirectionalSize: {
  16157. number: true
  16158. },
  16159. // allows negative
  16160. bidirectionalSizeMaybePercent: {
  16161. number: true,
  16162. allowPercent: true
  16163. },
  16164. // allows negative
  16165. bidirectionalSizes: {
  16166. number: true,
  16167. multiple: true
  16168. },
  16169. // allows negative
  16170. sizeMaybePercent: {
  16171. number: true,
  16172. min: 0,
  16173. allowPercent: true
  16174. },
  16175. axisDirection: {
  16176. enums: ['horizontal', 'leftward', 'rightward', 'vertical', 'upward', 'downward', 'auto']
  16177. },
  16178. axisDirectionExplicit: {
  16179. enums: ['leftward', 'rightward', 'upward', 'downward']
  16180. },
  16181. axisDirectionPrimary: {
  16182. enums: ['horizontal', 'vertical']
  16183. },
  16184. paddingRelativeTo: {
  16185. enums: ['width', 'height', 'average', 'min', 'max']
  16186. },
  16187. bgWH: {
  16188. number: true,
  16189. min: 0,
  16190. allowPercent: true,
  16191. enums: ['auto'],
  16192. multiple: true
  16193. },
  16194. bgPos: {
  16195. number: true,
  16196. allowPercent: true,
  16197. multiple: true
  16198. },
  16199. bgRelativeTo: {
  16200. enums: ['inner', 'include-padding'],
  16201. multiple: true
  16202. },
  16203. bgRepeat: {
  16204. enums: ['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],
  16205. multiple: true
  16206. },
  16207. bgFit: {
  16208. enums: ['none', 'contain', 'cover'],
  16209. multiple: true
  16210. },
  16211. bgCrossOrigin: {
  16212. enums: ['anonymous', 'use-credentials', 'null'],
  16213. multiple: true
  16214. },
  16215. bgClip: {
  16216. enums: ['none', 'node'],
  16217. multiple: true
  16218. },
  16219. bgContainment: {
  16220. enums: ['inside', 'over'],
  16221. multiple: true
  16222. },
  16223. boxSelection: {
  16224. enums: ['contain', 'overlap', 'none']
  16225. },
  16226. color: {
  16227. color: true
  16228. },
  16229. colors: {
  16230. color: true,
  16231. multiple: true
  16232. },
  16233. fill: {
  16234. enums: ['solid', 'linear-gradient', 'radial-gradient']
  16235. },
  16236. bool: {
  16237. enums: ['yes', 'no']
  16238. },
  16239. bools: {
  16240. enums: ['yes', 'no'],
  16241. multiple: true
  16242. },
  16243. lineStyle: {
  16244. enums: ['solid', 'dotted', 'dashed']
  16245. },
  16246. lineCap: {
  16247. enums: ['butt', 'round', 'square']
  16248. },
  16249. linePosition: {
  16250. enums: ['center', 'inside', 'outside']
  16251. },
  16252. lineJoin: {
  16253. enums: ['round', 'bevel', 'miter']
  16254. },
  16255. borderStyle: {
  16256. enums: ['solid', 'dotted', 'dashed', 'double']
  16257. },
  16258. curveStyle: {
  16259. enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi', 'round-segments', 'round-taxi']
  16260. },
  16261. radiusType: {
  16262. enums: ['arc-radius', 'influence-radius'],
  16263. multiple: true
  16264. },
  16265. fontFamily: {
  16266. regex: '^([\\w- \\"]+(?:\\s*,\\s*[\\w- \\"]+)*)$'
  16267. },
  16268. fontStyle: {
  16269. enums: ['italic', 'normal', 'oblique']
  16270. },
  16271. fontWeight: {
  16272. enums: ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '800', '900', 100, 200, 300, 400, 500, 600, 700, 800, 900]
  16273. },
  16274. textDecoration: {
  16275. enums: ['none', 'underline', 'overline', 'line-through']
  16276. },
  16277. textTransform: {
  16278. enums: ['none', 'uppercase', 'lowercase']
  16279. },
  16280. textWrap: {
  16281. enums: ['none', 'wrap', 'ellipsis']
  16282. },
  16283. textOverflowWrap: {
  16284. enums: ['whitespace', 'anywhere']
  16285. },
  16286. textBackgroundShape: {
  16287. enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'circle']
  16288. },
  16289. nodeShape: {
  16290. enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'cutrectangle', 'cut-rectangle', 'bottomroundrectangle', 'bottom-round-rectangle', 'barrel', 'ellipse', 'triangle', 'round-triangle', 'square', 'pentagon', 'round-pentagon', 'hexagon', 'round-hexagon', 'concavehexagon', 'concave-hexagon', 'heptagon', 'round-heptagon', 'octagon', 'round-octagon', 'tag', 'round-tag', 'star', 'diamond', 'round-diamond', 'vee', 'rhomboid', 'right-rhomboid', 'polygon']
  16291. },
  16292. overlayShape: {
  16293. enums: ['roundrectangle', 'round-rectangle', 'ellipse']
  16294. },
  16295. cornerRadius: {
  16296. number: true,
  16297. min: 0,
  16298. units: 'px|em',
  16299. implicitUnits: 'px',
  16300. enums: ['auto']
  16301. },
  16302. compoundIncludeLabels: {
  16303. enums: ['include', 'exclude']
  16304. },
  16305. arrowShape: {
  16306. enums: ['tee', 'triangle', 'triangle-tee', 'circle-triangle', 'triangle-cross', 'triangle-backcurve', 'vee', 'square', 'circle', 'diamond', 'chevron', 'none']
  16307. },
  16308. arrowFill: {
  16309. enums: ['filled', 'hollow']
  16310. },
  16311. arrowWidth: {
  16312. number: true,
  16313. units: '%|px|em',
  16314. implicitUnits: 'px',
  16315. enums: ['match-line']
  16316. },
  16317. display: {
  16318. enums: ['element', 'none']
  16319. },
  16320. visibility: {
  16321. enums: ['hidden', 'visible']
  16322. },
  16323. zCompoundDepth: {
  16324. enums: ['bottom', 'orphan', 'auto', 'top']
  16325. },
  16326. zIndexCompare: {
  16327. enums: ['auto', 'manual']
  16328. },
  16329. valign: {
  16330. enums: ['top', 'center', 'bottom']
  16331. },
  16332. halign: {
  16333. enums: ['left', 'center', 'right']
  16334. },
  16335. justification: {
  16336. enums: ['left', 'center', 'right', 'auto']
  16337. },
  16338. text: {
  16339. string: true
  16340. },
  16341. data: {
  16342. mapping: true,
  16343. regex: data('data')
  16344. },
  16345. layoutData: {
  16346. mapping: true,
  16347. regex: data('layoutData')
  16348. },
  16349. scratch: {
  16350. mapping: true,
  16351. regex: data('scratch')
  16352. },
  16353. mapData: {
  16354. mapping: true,
  16355. regex: mapData('mapData')
  16356. },
  16357. mapLayoutData: {
  16358. mapping: true,
  16359. regex: mapData('mapLayoutData')
  16360. },
  16361. mapScratch: {
  16362. mapping: true,
  16363. regex: mapData('mapScratch')
  16364. },
  16365. fn: {
  16366. mapping: true,
  16367. fn: true
  16368. },
  16369. url: {
  16370. regexes: urlRegexes,
  16371. singleRegexMatchValue: true
  16372. },
  16373. urls: {
  16374. regexes: urlRegexes,
  16375. singleRegexMatchValue: true,
  16376. multiple: true
  16377. },
  16378. propList: {
  16379. propList: true
  16380. },
  16381. angle: {
  16382. number: true,
  16383. units: 'deg|rad',
  16384. implicitUnits: 'rad'
  16385. },
  16386. textRotation: {
  16387. number: true,
  16388. units: 'deg|rad',
  16389. implicitUnits: 'rad',
  16390. enums: ['none', 'autorotate']
  16391. },
  16392. polygonPointList: {
  16393. number: true,
  16394. multiple: true,
  16395. evenMultiple: true,
  16396. min: -1,
  16397. max: 1,
  16398. unitless: true
  16399. },
  16400. edgeDistances: {
  16401. enums: ['intersection', 'node-position', 'endpoints']
  16402. },
  16403. edgeEndpoint: {
  16404. number: true,
  16405. multiple: true,
  16406. units: '%|px|em|deg|rad',
  16407. implicitUnits: 'px',
  16408. enums: ['inside-to-node', 'outside-to-node', 'outside-to-node-or-label', 'outside-to-line', 'outside-to-line-or-label'],
  16409. singleEnum: true,
  16410. validate: function validate(valArr, unitsArr) {
  16411. switch (valArr.length) {
  16412. case 2:
  16413. // can be % or px only
  16414. return unitsArr[0] !== 'deg' && unitsArr[0] !== 'rad' && unitsArr[1] !== 'deg' && unitsArr[1] !== 'rad';
  16415. case 1:
  16416. // can be enum, deg, or rad only
  16417. return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';
  16418. default:
  16419. return false;
  16420. }
  16421. }
  16422. },
  16423. easing: {
  16424. regexes: ['^(spring)\\s*\\(\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*\\)$', '^(cubic-bezier)\\s*\\(\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*,\\s*(' + number$1 + ')\\s*\\)$'],
  16425. enums: ['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'ease-in-sine', 'ease-out-sine', 'ease-in-out-sine', 'ease-in-quad', 'ease-out-quad', 'ease-in-out-quad', 'ease-in-cubic', 'ease-out-cubic', 'ease-in-out-cubic', 'ease-in-quart', 'ease-out-quart', 'ease-in-out-quart', 'ease-in-quint', 'ease-out-quint', 'ease-in-out-quint', 'ease-in-expo', 'ease-out-expo', 'ease-in-out-expo', 'ease-in-circ', 'ease-out-circ', 'ease-in-out-circ']
  16426. },
  16427. gradientDirection: {
  16428. enums: ['to-bottom', 'to-top', 'to-left', 'to-right', 'to-bottom-right', 'to-bottom-left', 'to-top-right', 'to-top-left', 'to-right-bottom', 'to-left-bottom', 'to-right-top', 'to-left-top' // different order
  16429. ]
  16430. },
  16431. boundsExpansion: {
  16432. number: true,
  16433. multiple: true,
  16434. min: 0,
  16435. validate: function validate(valArr) {
  16436. var length = valArr.length;
  16437. return length === 1 || length === 2 || length === 4;
  16438. }
  16439. }
  16440. };
  16441. var diff = {
  16442. zeroNonZero: function zeroNonZero(val1, val2) {
  16443. if ((val1 == null || val2 == null) && val1 !== val2) {
  16444. return true; // null cases could represent any value
  16445. }
  16446. if (val1 == 0 && val2 != 0) {
  16447. return true;
  16448. } else if (val1 != 0 && val2 == 0) {
  16449. return true;
  16450. } else {
  16451. return false;
  16452. }
  16453. },
  16454. any: function any(val1, val2) {
  16455. return val1 != val2;
  16456. },
  16457. emptyNonEmpty: function emptyNonEmpty(str1, str2) {
  16458. var empty1 = emptyString(str1);
  16459. var empty2 = emptyString(str2);
  16460. return empty1 && !empty2 || !empty1 && empty2;
  16461. }
  16462. };
  16463. // define visual style properties
  16464. //
  16465. // - n.b. adding a new group of props may require updates to updateStyleHints()
  16466. // - adding new props to an existing group gets handled automatically
  16467. var t = styfn$2.types;
  16468. var mainLabel = [{
  16469. name: 'label',
  16470. type: t.text,
  16471. triggersBounds: diff.any,
  16472. triggersZOrder: diff.emptyNonEmpty
  16473. }, {
  16474. name: 'text-rotation',
  16475. type: t.textRotation,
  16476. triggersBounds: diff.any
  16477. }, {
  16478. name: 'text-margin-x',
  16479. type: t.bidirectionalSize,
  16480. triggersBounds: diff.any
  16481. }, {
  16482. name: 'text-margin-y',
  16483. type: t.bidirectionalSize,
  16484. triggersBounds: diff.any
  16485. }];
  16486. var sourceLabel = [{
  16487. name: 'source-label',
  16488. type: t.text,
  16489. triggersBounds: diff.any
  16490. }, {
  16491. name: 'source-text-rotation',
  16492. type: t.textRotation,
  16493. triggersBounds: diff.any
  16494. }, {
  16495. name: 'source-text-margin-x',
  16496. type: t.bidirectionalSize,
  16497. triggersBounds: diff.any
  16498. }, {
  16499. name: 'source-text-margin-y',
  16500. type: t.bidirectionalSize,
  16501. triggersBounds: diff.any
  16502. }, {
  16503. name: 'source-text-offset',
  16504. type: t.size,
  16505. triggersBounds: diff.any
  16506. }];
  16507. var targetLabel = [{
  16508. name: 'target-label',
  16509. type: t.text,
  16510. triggersBounds: diff.any
  16511. }, {
  16512. name: 'target-text-rotation',
  16513. type: t.textRotation,
  16514. triggersBounds: diff.any
  16515. }, {
  16516. name: 'target-text-margin-x',
  16517. type: t.bidirectionalSize,
  16518. triggersBounds: diff.any
  16519. }, {
  16520. name: 'target-text-margin-y',
  16521. type: t.bidirectionalSize,
  16522. triggersBounds: diff.any
  16523. }, {
  16524. name: 'target-text-offset',
  16525. type: t.size,
  16526. triggersBounds: diff.any
  16527. }];
  16528. var labelDimensions = [{
  16529. name: 'font-family',
  16530. type: t.fontFamily,
  16531. triggersBounds: diff.any
  16532. }, {
  16533. name: 'font-style',
  16534. type: t.fontStyle,
  16535. triggersBounds: diff.any
  16536. }, {
  16537. name: 'font-weight',
  16538. type: t.fontWeight,
  16539. triggersBounds: diff.any
  16540. }, {
  16541. name: 'font-size',
  16542. type: t.size,
  16543. triggersBounds: diff.any
  16544. }, {
  16545. name: 'text-transform',
  16546. type: t.textTransform,
  16547. triggersBounds: diff.any
  16548. }, {
  16549. name: 'text-wrap',
  16550. type: t.textWrap,
  16551. triggersBounds: diff.any
  16552. }, {
  16553. name: 'text-overflow-wrap',
  16554. type: t.textOverflowWrap,
  16555. triggersBounds: diff.any
  16556. }, {
  16557. name: 'text-max-width',
  16558. type: t.size,
  16559. triggersBounds: diff.any
  16560. }, {
  16561. name: 'text-outline-width',
  16562. type: t.size,
  16563. triggersBounds: diff.any
  16564. }, {
  16565. name: 'line-height',
  16566. type: t.positiveNumber,
  16567. triggersBounds: diff.any
  16568. }];
  16569. var commonLabel = [{
  16570. name: 'text-valign',
  16571. type: t.valign,
  16572. triggersBounds: diff.any
  16573. }, {
  16574. name: 'text-halign',
  16575. type: t.halign,
  16576. triggersBounds: diff.any
  16577. }, {
  16578. name: 'color',
  16579. type: t.color
  16580. }, {
  16581. name: 'text-outline-color',
  16582. type: t.color
  16583. }, {
  16584. name: 'text-outline-opacity',
  16585. type: t.zeroOneNumber
  16586. }, {
  16587. name: 'text-background-color',
  16588. type: t.color
  16589. }, {
  16590. name: 'text-background-opacity',
  16591. type: t.zeroOneNumber
  16592. }, {
  16593. name: 'text-background-padding',
  16594. type: t.size,
  16595. triggersBounds: diff.any
  16596. }, {
  16597. name: 'text-border-opacity',
  16598. type: t.zeroOneNumber
  16599. }, {
  16600. name: 'text-border-color',
  16601. type: t.color
  16602. }, {
  16603. name: 'text-border-width',
  16604. type: t.size,
  16605. triggersBounds: diff.any
  16606. }, {
  16607. name: 'text-border-style',
  16608. type: t.borderStyle,
  16609. triggersBounds: diff.any
  16610. }, {
  16611. name: 'text-background-shape',
  16612. type: t.textBackgroundShape,
  16613. triggersBounds: diff.any
  16614. }, {
  16615. name: 'text-justification',
  16616. type: t.justification
  16617. }, {
  16618. name: 'box-select-labels',
  16619. type: t.bool,
  16620. triggersBounds: diff.any
  16621. }];
  16622. var behavior = [{
  16623. name: 'events',
  16624. type: t.bool,
  16625. triggersZOrder: diff.any
  16626. }, {
  16627. name: 'text-events',
  16628. type: t.bool,
  16629. triggersZOrder: diff.any
  16630. }, {
  16631. name: 'box-selection',
  16632. type: t.boxSelection,
  16633. triggersZOrder: diff.any
  16634. }];
  16635. var visibility = [{
  16636. name: 'display',
  16637. type: t.display,
  16638. triggersZOrder: diff.any,
  16639. triggersBounds: diff.any,
  16640. triggersBoundsOfConnectedEdges: diff.any,
  16641. triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue, ele) {
  16642. if (fromValue === toValue) {
  16643. return false;
  16644. }
  16645. // only if edge is bundled bezier (so as not to affect performance of other edges)
  16646. return ele.pstyle('curve-style').value === 'bezier';
  16647. }
  16648. }, {
  16649. name: 'visibility',
  16650. type: t.visibility,
  16651. triggersZOrder: diff.any
  16652. }, {
  16653. name: 'opacity',
  16654. type: t.zeroOneNumber,
  16655. triggersZOrder: diff.zeroNonZero
  16656. }, {
  16657. name: 'text-opacity',
  16658. type: t.zeroOneNumber
  16659. }, {
  16660. name: 'min-zoomed-font-size',
  16661. type: t.size
  16662. }, {
  16663. name: 'z-compound-depth',
  16664. type: t.zCompoundDepth,
  16665. triggersZOrder: diff.any
  16666. }, {
  16667. name: 'z-index-compare',
  16668. type: t.zIndexCompare,
  16669. triggersZOrder: diff.any
  16670. }, {
  16671. name: 'z-index',
  16672. type: t.number,
  16673. triggersZOrder: diff.any
  16674. }];
  16675. var overlay = [{
  16676. name: 'overlay-padding',
  16677. type: t.size,
  16678. triggersBounds: diff.any
  16679. }, {
  16680. name: 'overlay-color',
  16681. type: t.color
  16682. }, {
  16683. name: 'overlay-opacity',
  16684. type: t.zeroOneNumber,
  16685. triggersBounds: diff.zeroNonZero
  16686. }, {
  16687. name: 'overlay-shape',
  16688. type: t.overlayShape,
  16689. triggersBounds: diff.any
  16690. }, {
  16691. name: 'overlay-corner-radius',
  16692. type: t.cornerRadius
  16693. }];
  16694. var underlay = [{
  16695. name: 'underlay-padding',
  16696. type: t.size,
  16697. triggersBounds: diff.any
  16698. }, {
  16699. name: 'underlay-color',
  16700. type: t.color
  16701. }, {
  16702. name: 'underlay-opacity',
  16703. type: t.zeroOneNumber,
  16704. triggersBounds: diff.zeroNonZero
  16705. }, {
  16706. name: 'underlay-shape',
  16707. type: t.overlayShape,
  16708. triggersBounds: diff.any
  16709. }, {
  16710. name: 'underlay-corner-radius',
  16711. type: t.cornerRadius
  16712. }];
  16713. var transition = [{
  16714. name: 'transition-property',
  16715. type: t.propList
  16716. }, {
  16717. name: 'transition-duration',
  16718. type: t.time
  16719. }, {
  16720. name: 'transition-delay',
  16721. type: t.time
  16722. }, {
  16723. name: 'transition-timing-function',
  16724. type: t.easing
  16725. }];
  16726. var nodeSizeHashOverride = function nodeSizeHashOverride(ele, parsedProp) {
  16727. if (parsedProp.value === 'label') {
  16728. return -ele.poolIndex(); // no hash key hits is using label size (hitrate for perf probably low anyway)
  16729. } else {
  16730. return parsedProp.pfValue;
  16731. }
  16732. };
  16733. var nodeBody = [{
  16734. name: 'height',
  16735. type: t.nodeSize,
  16736. triggersBounds: diff.any,
  16737. hashOverride: nodeSizeHashOverride
  16738. }, {
  16739. name: 'width',
  16740. type: t.nodeSize,
  16741. triggersBounds: diff.any,
  16742. hashOverride: nodeSizeHashOverride
  16743. }, {
  16744. name: 'shape',
  16745. type: t.nodeShape,
  16746. triggersBounds: diff.any
  16747. }, {
  16748. name: 'shape-polygon-points',
  16749. type: t.polygonPointList,
  16750. triggersBounds: diff.any
  16751. }, {
  16752. name: 'corner-radius',
  16753. type: t.cornerRadius
  16754. }, {
  16755. name: 'background-color',
  16756. type: t.color
  16757. }, {
  16758. name: 'background-fill',
  16759. type: t.fill
  16760. }, {
  16761. name: 'background-opacity',
  16762. type: t.zeroOneNumber
  16763. }, {
  16764. name: 'background-blacken',
  16765. type: t.nOneOneNumber
  16766. }, {
  16767. name: 'background-gradient-stop-colors',
  16768. type: t.colors
  16769. }, {
  16770. name: 'background-gradient-stop-positions',
  16771. type: t.percentages
  16772. }, {
  16773. name: 'background-gradient-direction',
  16774. type: t.gradientDirection
  16775. }, {
  16776. name: 'padding',
  16777. type: t.sizeMaybePercent,
  16778. triggersBounds: diff.any
  16779. }, {
  16780. name: 'padding-relative-to',
  16781. type: t.paddingRelativeTo,
  16782. triggersBounds: diff.any
  16783. }, {
  16784. name: 'bounds-expansion',
  16785. type: t.boundsExpansion,
  16786. triggersBounds: diff.any
  16787. }];
  16788. var nodeBorder = [{
  16789. name: 'border-color',
  16790. type: t.color
  16791. }, {
  16792. name: 'border-opacity',
  16793. type: t.zeroOneNumber
  16794. }, {
  16795. name: 'border-width',
  16796. type: t.size,
  16797. triggersBounds: diff.any
  16798. }, {
  16799. name: 'border-style',
  16800. type: t.borderStyle
  16801. }, {
  16802. name: 'border-cap',
  16803. type: t.lineCap
  16804. }, {
  16805. name: 'border-join',
  16806. type: t.lineJoin
  16807. }, {
  16808. name: 'border-dash-pattern',
  16809. type: t.numbers
  16810. }, {
  16811. name: 'border-dash-offset',
  16812. type: t.number
  16813. }, {
  16814. name: 'border-position',
  16815. type: t.linePosition
  16816. }];
  16817. var nodeOutline = [{
  16818. name: 'outline-color',
  16819. type: t.color
  16820. }, {
  16821. name: 'outline-opacity',
  16822. type: t.zeroOneNumber
  16823. }, {
  16824. name: 'outline-width',
  16825. type: t.size,
  16826. triggersBounds: diff.any
  16827. }, {
  16828. name: 'outline-style',
  16829. type: t.borderStyle
  16830. }, {
  16831. name: 'outline-offset',
  16832. type: t.size,
  16833. triggersBounds: diff.any
  16834. }];
  16835. var backgroundImage = [{
  16836. name: 'background-image',
  16837. type: t.urls
  16838. }, {
  16839. name: 'background-image-crossorigin',
  16840. type: t.bgCrossOrigin
  16841. }, {
  16842. name: 'background-image-opacity',
  16843. type: t.zeroOneNumbers
  16844. }, {
  16845. name: 'background-image-containment',
  16846. type: t.bgContainment
  16847. }, {
  16848. name: 'background-image-smoothing',
  16849. type: t.bools
  16850. }, {
  16851. name: 'background-position-x',
  16852. type: t.bgPos
  16853. }, {
  16854. name: 'background-position-y',
  16855. type: t.bgPos
  16856. }, {
  16857. name: 'background-width-relative-to',
  16858. type: t.bgRelativeTo
  16859. }, {
  16860. name: 'background-height-relative-to',
  16861. type: t.bgRelativeTo
  16862. }, {
  16863. name: 'background-repeat',
  16864. type: t.bgRepeat
  16865. }, {
  16866. name: 'background-fit',
  16867. type: t.bgFit
  16868. }, {
  16869. name: 'background-clip',
  16870. type: t.bgClip
  16871. }, {
  16872. name: 'background-width',
  16873. type: t.bgWH
  16874. }, {
  16875. name: 'background-height',
  16876. type: t.bgWH
  16877. }, {
  16878. name: 'background-offset-x',
  16879. type: t.bgPos
  16880. }, {
  16881. name: 'background-offset-y',
  16882. type: t.bgPos
  16883. }];
  16884. var compound = [{
  16885. name: 'position',
  16886. type: t.position,
  16887. triggersBounds: diff.any
  16888. }, {
  16889. name: 'compound-sizing-wrt-labels',
  16890. type: t.compoundIncludeLabels,
  16891. triggersBounds: diff.any
  16892. }, {
  16893. name: 'min-width',
  16894. type: t.size,
  16895. triggersBounds: diff.any
  16896. }, {
  16897. name: 'min-width-bias-left',
  16898. type: t.sizeMaybePercent,
  16899. triggersBounds: diff.any
  16900. }, {
  16901. name: 'min-width-bias-right',
  16902. type: t.sizeMaybePercent,
  16903. triggersBounds: diff.any
  16904. }, {
  16905. name: 'min-height',
  16906. type: t.size,
  16907. triggersBounds: diff.any
  16908. }, {
  16909. name: 'min-height-bias-top',
  16910. type: t.sizeMaybePercent,
  16911. triggersBounds: diff.any
  16912. }, {
  16913. name: 'min-height-bias-bottom',
  16914. type: t.sizeMaybePercent,
  16915. triggersBounds: diff.any
  16916. }];
  16917. var edgeLine = [{
  16918. name: 'line-style',
  16919. type: t.lineStyle
  16920. }, {
  16921. name: 'line-color',
  16922. type: t.color
  16923. }, {
  16924. name: 'line-fill',
  16925. type: t.fill
  16926. }, {
  16927. name: 'line-cap',
  16928. type: t.lineCap
  16929. }, {
  16930. name: 'line-opacity',
  16931. type: t.zeroOneNumber
  16932. }, {
  16933. name: 'line-dash-pattern',
  16934. type: t.numbers
  16935. }, {
  16936. name: 'line-dash-offset',
  16937. type: t.number
  16938. }, {
  16939. name: 'line-outline-width',
  16940. type: t.size
  16941. }, {
  16942. name: 'line-outline-color',
  16943. type: t.color
  16944. }, {
  16945. name: 'line-gradient-stop-colors',
  16946. type: t.colors
  16947. }, {
  16948. name: 'line-gradient-stop-positions',
  16949. type: t.percentages
  16950. }, {
  16951. name: 'curve-style',
  16952. type: t.curveStyle,
  16953. triggersBounds: diff.any,
  16954. triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue) {
  16955. if (fromValue === toValue) {
  16956. return false;
  16957. } // must have diff
  16958. return fromValue === 'bezier' ||
  16959. // remove from bundle
  16960. toValue === 'bezier'; // add to bundle
  16961. }
  16962. }, {
  16963. name: 'haystack-radius',
  16964. type: t.zeroOneNumber,
  16965. triggersBounds: diff.any
  16966. }, {
  16967. name: 'source-endpoint',
  16968. type: t.edgeEndpoint,
  16969. triggersBounds: diff.any
  16970. }, {
  16971. name: 'target-endpoint',
  16972. type: t.edgeEndpoint,
  16973. triggersBounds: diff.any
  16974. }, {
  16975. name: 'control-point-step-size',
  16976. type: t.size,
  16977. triggersBounds: diff.any
  16978. }, {
  16979. name: 'control-point-distances',
  16980. type: t.bidirectionalSizes,
  16981. triggersBounds: diff.any
  16982. }, {
  16983. name: 'control-point-weights',
  16984. type: t.numbers,
  16985. triggersBounds: diff.any
  16986. }, {
  16987. name: 'segment-distances',
  16988. type: t.bidirectionalSizes,
  16989. triggersBounds: diff.any
  16990. }, {
  16991. name: 'segment-weights',
  16992. type: t.numbers,
  16993. triggersBounds: diff.any
  16994. }, {
  16995. name: 'segment-radii',
  16996. type: t.numbers,
  16997. triggersBounds: diff.any
  16998. }, {
  16999. name: 'radius-type',
  17000. type: t.radiusType,
  17001. triggersBounds: diff.any
  17002. }, {
  17003. name: 'taxi-turn',
  17004. type: t.bidirectionalSizeMaybePercent,
  17005. triggersBounds: diff.any
  17006. }, {
  17007. name: 'taxi-turn-min-distance',
  17008. type: t.size,
  17009. triggersBounds: diff.any
  17010. }, {
  17011. name: 'taxi-direction',
  17012. type: t.axisDirection,
  17013. triggersBounds: diff.any
  17014. }, {
  17015. name: 'taxi-radius',
  17016. type: t.number,
  17017. triggersBounds: diff.any
  17018. }, {
  17019. name: 'edge-distances',
  17020. type: t.edgeDistances,
  17021. triggersBounds: diff.any
  17022. }, {
  17023. name: 'arrow-scale',
  17024. type: t.positiveNumber,
  17025. triggersBounds: diff.any
  17026. }, {
  17027. name: 'loop-direction',
  17028. type: t.angle,
  17029. triggersBounds: diff.any
  17030. }, {
  17031. name: 'loop-sweep',
  17032. type: t.angle,
  17033. triggersBounds: diff.any
  17034. }, {
  17035. name: 'source-distance-from-node',
  17036. type: t.size,
  17037. triggersBounds: diff.any
  17038. }, {
  17039. name: 'target-distance-from-node',
  17040. type: t.size,
  17041. triggersBounds: diff.any
  17042. }];
  17043. var ghost = [{
  17044. name: 'ghost',
  17045. type: t.bool,
  17046. triggersBounds: diff.any
  17047. }, {
  17048. name: 'ghost-offset-x',
  17049. type: t.bidirectionalSize,
  17050. triggersBounds: diff.any
  17051. }, {
  17052. name: 'ghost-offset-y',
  17053. type: t.bidirectionalSize,
  17054. triggersBounds: diff.any
  17055. }, {
  17056. name: 'ghost-opacity',
  17057. type: t.zeroOneNumber
  17058. }];
  17059. var core = [{
  17060. name: 'selection-box-color',
  17061. type: t.color
  17062. }, {
  17063. name: 'selection-box-opacity',
  17064. type: t.zeroOneNumber
  17065. }, {
  17066. name: 'selection-box-border-color',
  17067. type: t.color
  17068. }, {
  17069. name: 'selection-box-border-width',
  17070. type: t.size
  17071. }, {
  17072. name: 'active-bg-color',
  17073. type: t.color
  17074. }, {
  17075. name: 'active-bg-opacity',
  17076. type: t.zeroOneNumber
  17077. }, {
  17078. name: 'active-bg-size',
  17079. type: t.size
  17080. }, {
  17081. name: 'outside-texture-bg-color',
  17082. type: t.color
  17083. }, {
  17084. name: 'outside-texture-bg-opacity',
  17085. type: t.zeroOneNumber
  17086. }];
  17087. // pie backgrounds for nodes
  17088. var pie = [];
  17089. styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)
  17090. pie.push({
  17091. name: 'pie-size',
  17092. type: t.sizeMaybePercent
  17093. });
  17094. pie.push({
  17095. name: 'pie-hole',
  17096. type: t.sizeMaybePercent
  17097. });
  17098. pie.push({
  17099. name: 'pie-start-angle',
  17100. type: t.angle
  17101. });
  17102. for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
  17103. pie.push({
  17104. name: 'pie-' + i + '-background-color',
  17105. type: t.color
  17106. });
  17107. pie.push({
  17108. name: 'pie-' + i + '-background-size',
  17109. type: t.percent
  17110. });
  17111. pie.push({
  17112. name: 'pie-' + i + '-background-opacity',
  17113. type: t.zeroOneNumber
  17114. });
  17115. }
  17116. // stripe backgrounds for nodes
  17117. var stripe = [];
  17118. styfn$2.stripeBackgroundN = 16; // because the stripe properties are numbered, give access to a constant N (for renderer use)
  17119. stripe.push({
  17120. name: 'stripe-size',
  17121. type: t.sizeMaybePercent
  17122. });
  17123. stripe.push({
  17124. name: 'stripe-direction',
  17125. type: t.axisDirectionPrimary
  17126. });
  17127. for (var _i = 1; _i <= styfn$2.stripeBackgroundN; _i++) {
  17128. stripe.push({
  17129. name: 'stripe-' + _i + '-background-color',
  17130. type: t.color
  17131. });
  17132. stripe.push({
  17133. name: 'stripe-' + _i + '-background-size',
  17134. type: t.percent
  17135. });
  17136. stripe.push({
  17137. name: 'stripe-' + _i + '-background-opacity',
  17138. type: t.zeroOneNumber
  17139. });
  17140. }
  17141. // edge arrows
  17142. var edgeArrow = [];
  17143. var arrowPrefixes = styfn$2.arrowPrefixes = ['source', 'mid-source', 'target', 'mid-target'];
  17144. [{
  17145. name: 'arrow-shape',
  17146. type: t.arrowShape,
  17147. triggersBounds: diff.any
  17148. }, {
  17149. name: 'arrow-color',
  17150. type: t.color
  17151. }, {
  17152. name: 'arrow-fill',
  17153. type: t.arrowFill
  17154. }, {
  17155. name: 'arrow-width',
  17156. type: t.arrowWidth
  17157. }].forEach(function (prop) {
  17158. arrowPrefixes.forEach(function (prefix) {
  17159. var name = prefix + '-' + prop.name;
  17160. var type = prop.type,
  17161. triggersBounds = prop.triggersBounds;
  17162. edgeArrow.push({
  17163. name: name,
  17164. type: type,
  17165. triggersBounds: triggersBounds
  17166. });
  17167. });
  17168. }, {});
  17169. var props = styfn$2.properties = [].concat(behavior, transition, visibility, overlay, underlay, ghost, commonLabel, labelDimensions, mainLabel, sourceLabel, targetLabel, nodeBody, nodeBorder, nodeOutline, backgroundImage, pie, stripe, compound, edgeLine, edgeArrow, core);
  17170. var propGroups = styfn$2.propertyGroups = {
  17171. // common to all eles
  17172. behavior: behavior,
  17173. transition: transition,
  17174. visibility: visibility,
  17175. overlay: overlay,
  17176. underlay: underlay,
  17177. ghost: ghost,
  17178. // labels
  17179. commonLabel: commonLabel,
  17180. labelDimensions: labelDimensions,
  17181. mainLabel: mainLabel,
  17182. sourceLabel: sourceLabel,
  17183. targetLabel: targetLabel,
  17184. // node props
  17185. nodeBody: nodeBody,
  17186. nodeBorder: nodeBorder,
  17187. nodeOutline: nodeOutline,
  17188. backgroundImage: backgroundImage,
  17189. pie: pie,
  17190. stripe: stripe,
  17191. compound: compound,
  17192. // edge props
  17193. edgeLine: edgeLine,
  17194. edgeArrow: edgeArrow,
  17195. core: core
  17196. };
  17197. var propGroupNames = styfn$2.propertyGroupNames = {};
  17198. var propGroupKeys = styfn$2.propertyGroupKeys = Object.keys(propGroups);
  17199. propGroupKeys.forEach(function (key) {
  17200. propGroupNames[key] = propGroups[key].map(function (prop) {
  17201. return prop.name;
  17202. });
  17203. propGroups[key].forEach(function (prop) {
  17204. return prop.groupKey = key;
  17205. });
  17206. });
  17207. // define aliases
  17208. var aliases = styfn$2.aliases = [{
  17209. name: 'content',
  17210. pointsTo: 'label'
  17211. }, {
  17212. name: 'control-point-distance',
  17213. pointsTo: 'control-point-distances'
  17214. }, {
  17215. name: 'control-point-weight',
  17216. pointsTo: 'control-point-weights'
  17217. }, {
  17218. name: 'segment-distance',
  17219. pointsTo: 'segment-distances'
  17220. }, {
  17221. name: 'segment-weight',
  17222. pointsTo: 'segment-weights'
  17223. }, {
  17224. name: 'segment-radius',
  17225. pointsTo: 'segment-radii'
  17226. }, {
  17227. name: 'edge-text-rotation',
  17228. pointsTo: 'text-rotation'
  17229. }, {
  17230. name: 'padding-left',
  17231. pointsTo: 'padding'
  17232. }, {
  17233. name: 'padding-right',
  17234. pointsTo: 'padding'
  17235. }, {
  17236. name: 'padding-top',
  17237. pointsTo: 'padding'
  17238. }, {
  17239. name: 'padding-bottom',
  17240. pointsTo: 'padding'
  17241. }];
  17242. // list of property names
  17243. styfn$2.propertyNames = props.map(function (p) {
  17244. return p.name;
  17245. });
  17246. // allow access of properties by name ( e.g. style.properties.height )
  17247. for (var _i2 = 0; _i2 < props.length; _i2++) {
  17248. var prop = props[_i2];
  17249. props[prop.name] = prop; // allow lookup by name
  17250. }
  17251. // map aliases
  17252. for (var _i3 = 0; _i3 < aliases.length; _i3++) {
  17253. var alias = aliases[_i3];
  17254. var pointsToProp = props[alias.pointsTo];
  17255. var aliasProp = {
  17256. name: alias.name,
  17257. alias: true,
  17258. pointsTo: pointsToProp
  17259. };
  17260. // add alias prop for parsing
  17261. props.push(aliasProp);
  17262. props[alias.name] = aliasProp; // allow lookup by name
  17263. }
  17264. })();
  17265. styfn$2.getDefaultProperty = function (name) {
  17266. return this.getDefaultProperties()[name];
  17267. };
  17268. styfn$2.getDefaultProperties = function () {
  17269. var _p = this._private;
  17270. if (_p.defaultProperties != null) {
  17271. return _p.defaultProperties;
  17272. }
  17273. var rawProps = extend({
  17274. // core props
  17275. 'selection-box-color': '#ddd',
  17276. 'selection-box-opacity': 0.65,
  17277. 'selection-box-border-color': '#aaa',
  17278. 'selection-box-border-width': 1,
  17279. 'active-bg-color': 'black',
  17280. 'active-bg-opacity': 0.15,
  17281. 'active-bg-size': 30,
  17282. 'outside-texture-bg-color': '#000',
  17283. 'outside-texture-bg-opacity': 0.125,
  17284. // common node/edge props
  17285. 'events': 'yes',
  17286. 'text-events': 'no',
  17287. 'text-valign': 'top',
  17288. 'text-halign': 'center',
  17289. 'text-justification': 'auto',
  17290. 'line-height': 1,
  17291. 'color': '#000',
  17292. 'box-selection': 'contain',
  17293. 'text-outline-color': '#000',
  17294. 'text-outline-width': 0,
  17295. 'text-outline-opacity': 1,
  17296. 'text-opacity': 1,
  17297. 'text-decoration': 'none',
  17298. 'text-transform': 'none',
  17299. 'text-wrap': 'none',
  17300. 'text-overflow-wrap': 'whitespace',
  17301. 'text-max-width': 9999,
  17302. 'text-background-color': '#000',
  17303. 'text-background-opacity': 0,
  17304. 'text-background-shape': 'rectangle',
  17305. 'text-background-padding': 0,
  17306. 'text-border-opacity': 0,
  17307. 'text-border-width': 0,
  17308. 'text-border-style': 'solid',
  17309. 'text-border-color': '#000',
  17310. 'font-family': 'Helvetica Neue, Helvetica, sans-serif',
  17311. 'font-style': 'normal',
  17312. 'font-weight': 'normal',
  17313. 'font-size': 16,
  17314. 'min-zoomed-font-size': 0,
  17315. 'text-rotation': 'none',
  17316. 'source-text-rotation': 'none',
  17317. 'target-text-rotation': 'none',
  17318. 'visibility': 'visible',
  17319. 'display': 'element',
  17320. 'opacity': 1,
  17321. 'z-compound-depth': 'auto',
  17322. 'z-index-compare': 'auto',
  17323. 'z-index': 0,
  17324. 'label': '',
  17325. 'text-margin-x': 0,
  17326. 'text-margin-y': 0,
  17327. 'source-label': '',
  17328. 'source-text-offset': 0,
  17329. 'source-text-margin-x': 0,
  17330. 'source-text-margin-y': 0,
  17331. 'target-label': '',
  17332. 'target-text-offset': 0,
  17333. 'target-text-margin-x': 0,
  17334. 'target-text-margin-y': 0,
  17335. 'overlay-opacity': 0,
  17336. 'overlay-color': '#000',
  17337. 'overlay-padding': 10,
  17338. 'overlay-shape': 'round-rectangle',
  17339. 'overlay-corner-radius': 'auto',
  17340. 'underlay-opacity': 0,
  17341. 'underlay-color': '#000',
  17342. 'underlay-padding': 10,
  17343. 'underlay-shape': 'round-rectangle',
  17344. 'underlay-corner-radius': 'auto',
  17345. 'transition-property': 'none',
  17346. 'transition-duration': 0,
  17347. 'transition-delay': 0,
  17348. 'transition-timing-function': 'linear',
  17349. 'box-select-labels': 'no',
  17350. // node props
  17351. 'background-blacken': 0,
  17352. 'background-color': '#999',
  17353. 'background-fill': 'solid',
  17354. 'background-opacity': 1,
  17355. 'background-image': 'none',
  17356. 'background-image-crossorigin': 'anonymous',
  17357. 'background-image-opacity': 1,
  17358. 'background-image-containment': 'inside',
  17359. 'background-image-smoothing': 'yes',
  17360. 'background-position-x': '50%',
  17361. 'background-position-y': '50%',
  17362. 'background-offset-x': 0,
  17363. 'background-offset-y': 0,
  17364. 'background-width-relative-to': 'include-padding',
  17365. 'background-height-relative-to': 'include-padding',
  17366. 'background-repeat': 'no-repeat',
  17367. 'background-fit': 'none',
  17368. 'background-clip': 'node',
  17369. 'background-width': 'auto',
  17370. 'background-height': 'auto',
  17371. 'border-color': '#000',
  17372. 'border-opacity': 1,
  17373. 'border-width': 0,
  17374. 'border-style': 'solid',
  17375. 'border-dash-pattern': [4, 2],
  17376. 'border-dash-offset': 0,
  17377. 'border-cap': 'butt',
  17378. 'border-join': 'miter',
  17379. 'border-position': 'center',
  17380. 'outline-color': '#999',
  17381. 'outline-opacity': 1,
  17382. 'outline-width': 0,
  17383. 'outline-offset': 0,
  17384. 'outline-style': 'solid',
  17385. 'height': 30,
  17386. 'width': 30,
  17387. 'shape': 'ellipse',
  17388. 'shape-polygon-points': '-1, -1, 1, -1, 1, 1, -1, 1',
  17389. 'corner-radius': 'auto',
  17390. 'bounds-expansion': 0,
  17391. // node gradient
  17392. 'background-gradient-direction': 'to-bottom',
  17393. 'background-gradient-stop-colors': '#999',
  17394. 'background-gradient-stop-positions': '0%',
  17395. // ghost props
  17396. 'ghost': 'no',
  17397. 'ghost-offset-y': 0,
  17398. 'ghost-offset-x': 0,
  17399. 'ghost-opacity': 0,
  17400. // compound props
  17401. 'padding': 0,
  17402. 'padding-relative-to': 'width',
  17403. 'position': 'origin',
  17404. 'compound-sizing-wrt-labels': 'include',
  17405. 'min-width': 0,
  17406. 'min-width-bias-left': 0,
  17407. 'min-width-bias-right': 0,
  17408. 'min-height': 0,
  17409. 'min-height-bias-top': 0,
  17410. 'min-height-bias-bottom': 0
  17411. }, {
  17412. // node pie bg
  17413. 'pie-size': '100%',
  17414. 'pie-hole': 0,
  17415. 'pie-start-angle': '0deg'
  17416. }, [{
  17417. name: 'pie-{{i}}-background-color',
  17418. value: 'black'
  17419. }, {
  17420. name: 'pie-{{i}}-background-size',
  17421. value: '0%'
  17422. }, {
  17423. name: 'pie-{{i}}-background-opacity',
  17424. value: 1
  17425. }].reduce(function (css, prop) {
  17426. for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
  17427. var name = prop.name.replace('{{i}}', i);
  17428. var val = prop.value;
  17429. css[name] = val;
  17430. }
  17431. return css;
  17432. }, {}), {
  17433. // node stripes bg
  17434. 'stripe-size': '100%',
  17435. 'stripe-direction': 'horizontal'
  17436. }, [{
  17437. name: 'stripe-{{i}}-background-color',
  17438. value: 'black'
  17439. }, {
  17440. name: 'stripe-{{i}}-background-size',
  17441. value: '0%'
  17442. }, {
  17443. name: 'stripe-{{i}}-background-opacity',
  17444. value: 1
  17445. }].reduce(function (css, prop) {
  17446. for (var i = 1; i <= styfn$2.stripeBackgroundN; i++) {
  17447. var name = prop.name.replace('{{i}}', i);
  17448. var val = prop.value;
  17449. css[name] = val;
  17450. }
  17451. return css;
  17452. }, {}), {
  17453. // edge props
  17454. 'line-style': 'solid',
  17455. 'line-color': '#999',
  17456. 'line-fill': 'solid',
  17457. 'line-cap': 'butt',
  17458. 'line-opacity': 1,
  17459. 'line-outline-width': 0,
  17460. 'line-outline-color': '#000',
  17461. 'line-gradient-stop-colors': '#999',
  17462. 'line-gradient-stop-positions': '0%',
  17463. 'control-point-step-size': 40,
  17464. 'control-point-weights': 0.5,
  17465. 'segment-weights': 0.5,
  17466. 'segment-distances': 20,
  17467. 'segment-radii': 15,
  17468. 'radius-type': 'arc-radius',
  17469. 'taxi-turn': '50%',
  17470. 'taxi-radius': 15,
  17471. 'taxi-turn-min-distance': 10,
  17472. 'taxi-direction': 'auto',
  17473. 'edge-distances': 'intersection',
  17474. 'curve-style': 'haystack',
  17475. 'haystack-radius': 0,
  17476. 'arrow-scale': 1,
  17477. 'loop-direction': '-45deg',
  17478. 'loop-sweep': '-90deg',
  17479. 'source-distance-from-node': 0,
  17480. 'target-distance-from-node': 0,
  17481. 'source-endpoint': 'outside-to-node',
  17482. 'target-endpoint': 'outside-to-node',
  17483. 'line-dash-pattern': [6, 3],
  17484. 'line-dash-offset': 0
  17485. }, [{
  17486. name: 'arrow-shape',
  17487. value: 'none'
  17488. }, {
  17489. name: 'arrow-color',
  17490. value: '#999'
  17491. }, {
  17492. name: 'arrow-fill',
  17493. value: 'filled'
  17494. }, {
  17495. name: 'arrow-width',
  17496. value: 1
  17497. }].reduce(function (css, prop) {
  17498. styfn$2.arrowPrefixes.forEach(function (prefix) {
  17499. var name = prefix + '-' + prop.name;
  17500. var val = prop.value;
  17501. css[name] = val;
  17502. });
  17503. return css;
  17504. }, {}));
  17505. var parsedProps = {};
  17506. for (var i = 0; i < this.properties.length; i++) {
  17507. var prop = this.properties[i];
  17508. if (prop.pointsTo) {
  17509. continue;
  17510. }
  17511. var name = prop.name;
  17512. var val = rawProps[name];
  17513. var parsedProp = this.parse(name, val);
  17514. parsedProps[name] = parsedProp;
  17515. }
  17516. _p.defaultProperties = parsedProps;
  17517. return _p.defaultProperties;
  17518. };
  17519. styfn$2.addDefaultStylesheet = function () {
  17520. this.selector(':parent').css({
  17521. 'shape': 'rectangle',
  17522. 'padding': 10,
  17523. 'background-color': '#eee',
  17524. 'border-color': '#ccc',
  17525. 'border-width': 1
  17526. }).selector('edge').css({
  17527. 'width': 3
  17528. }).selector(':loop').css({
  17529. 'curve-style': 'bezier'
  17530. }).selector('edge:compound').css({
  17531. 'curve-style': 'bezier',
  17532. 'source-endpoint': 'outside-to-line',
  17533. 'target-endpoint': 'outside-to-line'
  17534. }).selector(':selected').css({
  17535. 'background-color': '#0169D9',
  17536. 'line-color': '#0169D9',
  17537. 'source-arrow-color': '#0169D9',
  17538. 'target-arrow-color': '#0169D9',
  17539. 'mid-source-arrow-color': '#0169D9',
  17540. 'mid-target-arrow-color': '#0169D9'
  17541. }).selector(':parent:selected').css({
  17542. 'background-color': '#CCE1F9',
  17543. 'border-color': '#aec8e5'
  17544. }).selector(':active').css({
  17545. 'overlay-color': 'black',
  17546. 'overlay-padding': 10,
  17547. 'overlay-opacity': 0.25
  17548. });
  17549. this.defaultLength = this.length;
  17550. };
  17551. var styfn$1 = {};
  17552. // a caching layer for property parsing
  17553. styfn$1.parse = function (name, value, propIsBypass, propIsFlat) {
  17554. var self = this;
  17555. // function values can't be cached in all cases, and there isn't much benefit of caching them anyway
  17556. if (fn$6(value)) {
  17557. return self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  17558. }
  17559. var flatKey = propIsFlat === 'mapping' || propIsFlat === true || propIsFlat === false || propIsFlat == null ? 'dontcare' : propIsFlat;
  17560. var bypassKey = propIsBypass ? 't' : 'f';
  17561. var valueKey = '' + value;
  17562. var argHash = hashStrings(name, valueKey, bypassKey, flatKey);
  17563. var propCache = self.propCache = self.propCache || [];
  17564. var ret;
  17565. if (!(ret = propCache[argHash])) {
  17566. ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  17567. }
  17568. // - bypasses can't be shared b/c the value can be changed by animations or otherwise overridden
  17569. // - mappings can't be shared b/c mappings are per-element
  17570. if (propIsBypass || propIsFlat === 'mapping') {
  17571. // need a copy since props are mutated later in their lifecycles
  17572. ret = copy(ret);
  17573. if (ret) {
  17574. ret.value = copy(ret.value); // because it could be an array, e.g. colour
  17575. }
  17576. }
  17577. return ret;
  17578. };
  17579. styfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {
  17580. var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);
  17581. if (!prop && value != null) {
  17582. warn("The style property `".concat(name, ": ").concat(value, "` is invalid"));
  17583. }
  17584. if (prop && (prop.name === 'width' || prop.name === 'height') && value === 'label') {
  17585. warn('The style value of `label` is deprecated for `' + prop.name + '`');
  17586. }
  17587. return prop;
  17588. };
  17589. // parse a property; return null on invalid; return parsed property otherwise
  17590. // fields :
  17591. // - name : the name of the property
  17592. // - value : the parsed, native-typed value of the property
  17593. // - strValue : a string value that represents the property value in valid css
  17594. // - bypass : true iff the property is a bypass property
  17595. styfn$1.parseImpl = function (name, value, propIsBypass, propIsFlat) {
  17596. var self = this;
  17597. name = camel2dash(name); // make sure the property name is in dash form (e.g. 'property-name' not 'propertyName')
  17598. var property = self.properties[name];
  17599. var passedValue = value;
  17600. var types = self.types;
  17601. if (!property) {
  17602. return null;
  17603. } // return null on property of unknown name
  17604. if (value === undefined) {
  17605. return null;
  17606. } // can't assign undefined
  17607. // the property may be an alias
  17608. if (property.alias) {
  17609. property = property.pointsTo;
  17610. name = property.name;
  17611. }
  17612. var valueIsString = string(value);
  17613. if (valueIsString) {
  17614. // trim the value to make parsing easier
  17615. value = value.trim();
  17616. }
  17617. var type = property.type;
  17618. if (!type) {
  17619. return null;
  17620. } // no type, no luck
  17621. // check if bypass is null or empty string (i.e. indication to delete bypass property)
  17622. if (propIsBypass && (value === '' || value === null)) {
  17623. return {
  17624. name: name,
  17625. value: value,
  17626. bypass: true,
  17627. deleteBypass: true
  17628. };
  17629. }
  17630. // check if value is a function used as a mapper
  17631. if (fn$6(value)) {
  17632. return {
  17633. name: name,
  17634. value: value,
  17635. strValue: 'fn',
  17636. mapped: types.fn,
  17637. bypass: propIsBypass
  17638. };
  17639. }
  17640. // check if value is mapped
  17641. var data, mapData;
  17642. if (!valueIsString || propIsFlat || value.length < 7 || value[1] !== 'a') ; else if (value.length >= 7 && value[0] === 'd' && (data = new RegExp(types.data.regex).exec(value))) {
  17643. if (propIsBypass) {
  17644. return false;
  17645. } // mappers not allowed in bypass
  17646. var mapped = types.data;
  17647. return {
  17648. name: name,
  17649. value: data,
  17650. strValue: '' + value,
  17651. mapped: mapped,
  17652. field: data[1],
  17653. bypass: propIsBypass
  17654. };
  17655. } else if (value.length >= 10 && value[0] === 'm' && (mapData = new RegExp(types.mapData.regex).exec(value))) {
  17656. if (propIsBypass) {
  17657. return false;
  17658. } // mappers not allowed in bypass
  17659. if (type.multiple) {
  17660. return false;
  17661. } // impossible to map to num
  17662. var _mapped = types.mapData;
  17663. // we can map only if the type is a colour or a number
  17664. if (!(type.color || type.number)) {
  17665. return false;
  17666. }
  17667. var valueMin = this.parse(name, mapData[4]); // parse to validate
  17668. if (!valueMin || valueMin.mapped) {
  17669. return false;
  17670. } // can't be invalid or mapped
  17671. var valueMax = this.parse(name, mapData[5]); // parse to validate
  17672. if (!valueMax || valueMax.mapped) {
  17673. return false;
  17674. } // can't be invalid or mapped
  17675. // check if valueMin and valueMax are the same
  17676. if (valueMin.pfValue === valueMax.pfValue || valueMin.strValue === valueMax.strValue) {
  17677. warn('`' + name + ': ' + value + '` is not a valid mapper because the output range is zero; converting to `' + name + ': ' + valueMin.strValue + '`');
  17678. return this.parse(name, valueMin.strValue); // can't make much of a mapper without a range
  17679. } else if (type.color) {
  17680. var c1 = valueMin.value;
  17681. var c2 = valueMax.value;
  17682. var same = c1[0] === c2[0] // red
  17683. && c1[1] === c2[1] // green
  17684. && c1[2] === c2[2] // blue
  17685. && (
  17686. // optional alpha
  17687. c1[3] === c2[3] // same alpha outright
  17688. || (c1[3] == null || c1[3] === 1 // full opacity for colour 1?
  17689. ) && (c2[3] == null || c2[3] === 1) // full opacity for colour 2?
  17690. );
  17691. if (same) {
  17692. return false;
  17693. } // can't make a mapper without a range
  17694. }
  17695. return {
  17696. name: name,
  17697. value: mapData,
  17698. strValue: '' + value,
  17699. mapped: _mapped,
  17700. field: mapData[1],
  17701. fieldMin: parseFloat(mapData[2]),
  17702. // min & max are numeric
  17703. fieldMax: parseFloat(mapData[3]),
  17704. valueMin: valueMin.value,
  17705. valueMax: valueMax.value,
  17706. bypass: propIsBypass
  17707. };
  17708. }
  17709. if (type.multiple && propIsFlat !== 'multiple') {
  17710. var vals;
  17711. if (valueIsString) {
  17712. vals = value.split(/\s+/);
  17713. } else if (array(value)) {
  17714. vals = value;
  17715. } else {
  17716. vals = [value];
  17717. }
  17718. if (type.evenMultiple && vals.length % 2 !== 0) {
  17719. return null;
  17720. }
  17721. var valArr = [];
  17722. var unitsArr = [];
  17723. var pfValArr = [];
  17724. var strVal = '';
  17725. var hasEnum = false;
  17726. for (var i = 0; i < vals.length; i++) {
  17727. var p = self.parse(name, vals[i], propIsBypass, 'multiple');
  17728. hasEnum = hasEnum || string(p.value);
  17729. valArr.push(p.value);
  17730. pfValArr.push(p.pfValue != null ? p.pfValue : p.value);
  17731. unitsArr.push(p.units);
  17732. strVal += (i > 0 ? ' ' : '') + p.strValue;
  17733. }
  17734. if (type.validate && !type.validate(valArr, unitsArr)) {
  17735. return null;
  17736. }
  17737. if (type.singleEnum && hasEnum) {
  17738. if (valArr.length === 1 && string(valArr[0])) {
  17739. return {
  17740. name: name,
  17741. value: valArr[0],
  17742. strValue: valArr[0],
  17743. bypass: propIsBypass
  17744. };
  17745. } else {
  17746. return null;
  17747. }
  17748. }
  17749. return {
  17750. name: name,
  17751. value: valArr,
  17752. pfValue: pfValArr,
  17753. strValue: strVal,
  17754. bypass: propIsBypass,
  17755. units: unitsArr
  17756. };
  17757. }
  17758. // several types also allow enums
  17759. var checkEnums = function checkEnums() {
  17760. for (var _i = 0; _i < type.enums.length; _i++) {
  17761. var en = type.enums[_i];
  17762. if (en === value) {
  17763. return {
  17764. name: name,
  17765. value: value,
  17766. strValue: '' + value,
  17767. bypass: propIsBypass
  17768. };
  17769. }
  17770. }
  17771. return null;
  17772. };
  17773. // check the type and return the appropriate object
  17774. if (type.number) {
  17775. var units;
  17776. var implicitUnits = 'px'; // not set => px
  17777. if (type.units) {
  17778. // use specified units if set
  17779. units = type.units;
  17780. }
  17781. if (type.implicitUnits) {
  17782. implicitUnits = type.implicitUnits;
  17783. }
  17784. if (!type.unitless) {
  17785. if (valueIsString) {
  17786. var unitsRegex = 'px|em' + (type.allowPercent ? '|\\%' : '');
  17787. if (units) {
  17788. unitsRegex = units;
  17789. } // only allow explicit units if so set
  17790. var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');
  17791. if (match) {
  17792. value = match[1];
  17793. units = match[2] || implicitUnits;
  17794. }
  17795. } else if (!units || type.implicitUnits) {
  17796. units = implicitUnits; // implicitly px if unspecified
  17797. }
  17798. }
  17799. value = parseFloat(value);
  17800. // if not a number and enums not allowed, then the value is invalid
  17801. if (isNaN(value) && type.enums === undefined) {
  17802. return null;
  17803. }
  17804. // check if this number type also accepts special keywords in place of numbers
  17805. // (i.e. `left`, `auto`, etc)
  17806. if (isNaN(value) && type.enums !== undefined) {
  17807. value = passedValue;
  17808. return checkEnums();
  17809. }
  17810. // check if value must be an integer
  17811. if (type.integer && !integer(value)) {
  17812. return null;
  17813. }
  17814. // check value is within range
  17815. if (type.min !== undefined && (value < type.min || type.strictMin && value === type.min) || type.max !== undefined && (value > type.max || type.strictMax && value === type.max)) {
  17816. return null;
  17817. }
  17818. var ret = {
  17819. name: name,
  17820. value: value,
  17821. strValue: '' + value + (units ? units : ''),
  17822. units: units,
  17823. bypass: propIsBypass
  17824. };
  17825. // normalise value in pixels
  17826. if (type.unitless || units !== 'px' && units !== 'em') {
  17827. ret.pfValue = value;
  17828. } else {
  17829. ret.pfValue = units === 'px' || !units ? value : this.getEmSizeInPixels() * value;
  17830. }
  17831. // normalise value in ms
  17832. if (units === 'ms' || units === 's') {
  17833. ret.pfValue = units === 'ms' ? value : 1000 * value;
  17834. }
  17835. // normalise value in rad
  17836. if (units === 'deg' || units === 'rad') {
  17837. ret.pfValue = units === 'rad' ? value : deg2rad(value);
  17838. }
  17839. // normalize value in %
  17840. if (units === '%') {
  17841. ret.pfValue = value / 100;
  17842. }
  17843. return ret;
  17844. } else if (type.propList) {
  17845. var props = [];
  17846. var propsStr = '' + value;
  17847. if (propsStr === 'none') ; else {
  17848. // go over each prop
  17849. var propsSplit = propsStr.split(/\s*,\s*|\s+/);
  17850. for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {
  17851. var propName = propsSplit[_i2].trim();
  17852. if (self.properties[propName]) {
  17853. props.push(propName);
  17854. } else {
  17855. warn('`' + propName + '` is not a valid property name');
  17856. }
  17857. }
  17858. if (props.length === 0) {
  17859. return null;
  17860. }
  17861. }
  17862. return {
  17863. name: name,
  17864. value: props,
  17865. strValue: props.length === 0 ? 'none' : props.join(' '),
  17866. bypass: propIsBypass
  17867. };
  17868. } else if (type.color) {
  17869. var tuple = color2tuple(value);
  17870. if (!tuple) {
  17871. return null;
  17872. }
  17873. return {
  17874. name: name,
  17875. value: tuple,
  17876. pfValue: tuple,
  17877. strValue: 'rgb(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')',
  17878. // n.b. no spaces b/c of multiple support
  17879. bypass: propIsBypass
  17880. };
  17881. } else if (type.regex || type.regexes) {
  17882. // first check enums
  17883. if (type.enums) {
  17884. var enumProp = checkEnums();
  17885. if (enumProp) {
  17886. return enumProp;
  17887. }
  17888. }
  17889. var regexes = type.regexes ? type.regexes : [type.regex];
  17890. for (var _i3 = 0; _i3 < regexes.length; _i3++) {
  17891. var regex = new RegExp(regexes[_i3]); // make a regex from the type string
  17892. var m = regex.exec(value);
  17893. if (m) {
  17894. // regex matches
  17895. return {
  17896. name: name,
  17897. value: type.singleRegexMatchValue ? m[1] : m,
  17898. strValue: '' + value,
  17899. bypass: propIsBypass
  17900. };
  17901. }
  17902. }
  17903. return null; // didn't match any
  17904. } else if (type.string) {
  17905. // just return
  17906. return {
  17907. name: name,
  17908. value: '' + value,
  17909. strValue: '' + value,
  17910. bypass: propIsBypass
  17911. };
  17912. } else if (type.enums) {
  17913. // check enums last because it's a combo type in others
  17914. return checkEnums();
  17915. } else {
  17916. return null; // not a type we can handle
  17917. }
  17918. };
  17919. var _Style = function Style(cy) {
  17920. if (!(this instanceof _Style)) {
  17921. return new _Style(cy);
  17922. }
  17923. if (!core(cy)) {
  17924. error('A style must have a core reference');
  17925. return;
  17926. }
  17927. this._private = {
  17928. cy: cy,
  17929. coreStyle: {}
  17930. };
  17931. this.length = 0;
  17932. this.resetToDefault();
  17933. };
  17934. var styfn = _Style.prototype;
  17935. styfn.instanceString = function () {
  17936. return 'style';
  17937. };
  17938. // remove all contexts
  17939. styfn.clear = function () {
  17940. var _p = this._private;
  17941. var cy = _p.cy;
  17942. var eles = cy.elements();
  17943. for (var i = 0; i < this.length; i++) {
  17944. this[i] = undefined;
  17945. }
  17946. this.length = 0;
  17947. _p.contextStyles = {};
  17948. _p.propDiffs = {};
  17949. this.cleanElements(eles, true);
  17950. eles.forEach(function (ele) {
  17951. var ele_p = ele[0]._private;
  17952. ele_p.styleDirty = true;
  17953. ele_p.appliedInitStyle = false;
  17954. });
  17955. return this; // chaining
  17956. };
  17957. styfn.resetToDefault = function () {
  17958. this.clear();
  17959. this.addDefaultStylesheet();
  17960. return this;
  17961. };
  17962. // builds a style object for the 'core' selector
  17963. styfn.core = function (propName) {
  17964. return this._private.coreStyle[propName] || this.getDefaultProperty(propName);
  17965. };
  17966. // create a new context from the specified selector string and switch to that context
  17967. styfn.selector = function (selectorStr) {
  17968. // 'core' is a special case and does not need a selector
  17969. var selector = selectorStr === 'core' ? null : new Selector(selectorStr);
  17970. var i = this.length++; // new context means new index
  17971. this[i] = {
  17972. selector: selector,
  17973. properties: [],
  17974. mappedProperties: [],
  17975. index: i
  17976. };
  17977. return this; // chaining
  17978. };
  17979. // add one or many css rules to the current context
  17980. styfn.css = function () {
  17981. var self = this;
  17982. var args = arguments;
  17983. if (args.length === 1) {
  17984. var map = args[0];
  17985. for (var i = 0; i < self.properties.length; i++) {
  17986. var prop = self.properties[i];
  17987. var mapVal = map[prop.name];
  17988. if (mapVal === undefined) {
  17989. mapVal = map[dash2camel(prop.name)];
  17990. }
  17991. if (mapVal !== undefined) {
  17992. this.cssRule(prop.name, mapVal);
  17993. }
  17994. }
  17995. } else if (args.length === 2) {
  17996. this.cssRule(args[0], args[1]);
  17997. }
  17998. // do nothing if args are invalid
  17999. return this; // chaining
  18000. };
  18001. styfn.style = styfn.css;
  18002. // add a single css rule to the current context
  18003. styfn.cssRule = function (name, value) {
  18004. // name-value pair
  18005. var property = this.parse(name, value);
  18006. // add property to current context if valid
  18007. if (property) {
  18008. var i = this.length - 1;
  18009. this[i].properties.push(property);
  18010. this[i].properties[property.name] = property; // allow access by name as well
  18011. if (property.name.match(/pie-(\d+)-background-size/) && property.value) {
  18012. this._private.hasPie = true;
  18013. }
  18014. if (property.name.match(/stripe-(\d+)-background-size/) && property.value) {
  18015. this._private.hasStripe = true;
  18016. }
  18017. if (property.mapped) {
  18018. this[i].mappedProperties.push(property);
  18019. }
  18020. // add to core style if necessary
  18021. var currentSelectorIsCore = !this[i].selector;
  18022. if (currentSelectorIsCore) {
  18023. this._private.coreStyle[property.name] = property;
  18024. }
  18025. }
  18026. return this; // chaining
  18027. };
  18028. styfn.append = function (style) {
  18029. if (stylesheet(style)) {
  18030. style.appendToStyle(this);
  18031. } else if (array(style)) {
  18032. this.appendFromJson(style);
  18033. } else if (string(style)) {
  18034. this.appendFromString(style);
  18035. } // you probably wouldn't want to append a Style, since you'd duplicate the default parts
  18036. return this;
  18037. };
  18038. // static function
  18039. _Style.fromJson = function (cy, json) {
  18040. var style = new _Style(cy);
  18041. style.fromJson(json);
  18042. return style;
  18043. };
  18044. _Style.fromString = function (cy, string) {
  18045. return new _Style(cy).fromString(string);
  18046. };
  18047. [styfn$8, styfn$7, styfn$6, styfn$5, styfn$4, styfn$3, styfn$2, styfn$1].forEach(function (props) {
  18048. extend(styfn, props);
  18049. });
  18050. _Style.types = styfn.types;
  18051. _Style.properties = styfn.properties;
  18052. _Style.propertyGroups = styfn.propertyGroups;
  18053. _Style.propertyGroupNames = styfn.propertyGroupNames;
  18054. _Style.propertyGroupKeys = styfn.propertyGroupKeys;
  18055. var corefn$2 = {
  18056. style: function style(newStyle) {
  18057. if (newStyle) {
  18058. var s = this.setStyle(newStyle);
  18059. s.update();
  18060. }
  18061. return this._private.style;
  18062. },
  18063. setStyle: function setStyle(style) {
  18064. var _p = this._private;
  18065. if (stylesheet(style)) {
  18066. _p.style = style.generateStyle(this);
  18067. } else if (array(style)) {
  18068. _p.style = _Style.fromJson(this, style);
  18069. } else if (string(style)) {
  18070. _p.style = _Style.fromString(this, style);
  18071. } else {
  18072. _p.style = _Style(this);
  18073. }
  18074. return _p.style;
  18075. },
  18076. // e.g. cy.data() changed => recalc ele mappers
  18077. updateStyle: function updateStyle() {
  18078. this.mutableElements().updateStyle(); // just send to all eles
  18079. }
  18080. };
  18081. var defaultSelectionType = 'single';
  18082. var corefn$1 = {
  18083. autolock: function autolock(bool) {
  18084. if (bool !== undefined) {
  18085. this._private.autolock = bool ? true : false;
  18086. } else {
  18087. return this._private.autolock;
  18088. }
  18089. return this; // chaining
  18090. },
  18091. autoungrabify: function autoungrabify(bool) {
  18092. if (bool !== undefined) {
  18093. this._private.autoungrabify = bool ? true : false;
  18094. } else {
  18095. return this._private.autoungrabify;
  18096. }
  18097. return this; // chaining
  18098. },
  18099. autounselectify: function autounselectify(bool) {
  18100. if (bool !== undefined) {
  18101. this._private.autounselectify = bool ? true : false;
  18102. } else {
  18103. return this._private.autounselectify;
  18104. }
  18105. return this; // chaining
  18106. },
  18107. selectionType: function selectionType(selType) {
  18108. var _p = this._private;
  18109. if (_p.selectionType == null) {
  18110. _p.selectionType = defaultSelectionType;
  18111. }
  18112. if (selType !== undefined) {
  18113. if (selType === 'additive' || selType === 'single') {
  18114. _p.selectionType = selType;
  18115. }
  18116. } else {
  18117. return _p.selectionType;
  18118. }
  18119. return this;
  18120. },
  18121. panningEnabled: function panningEnabled(bool) {
  18122. if (bool !== undefined) {
  18123. this._private.panningEnabled = bool ? true : false;
  18124. } else {
  18125. return this._private.panningEnabled;
  18126. }
  18127. return this; // chaining
  18128. },
  18129. userPanningEnabled: function userPanningEnabled(bool) {
  18130. if (bool !== undefined) {
  18131. this._private.userPanningEnabled = bool ? true : false;
  18132. } else {
  18133. return this._private.userPanningEnabled;
  18134. }
  18135. return this; // chaining
  18136. },
  18137. zoomingEnabled: function zoomingEnabled(bool) {
  18138. if (bool !== undefined) {
  18139. this._private.zoomingEnabled = bool ? true : false;
  18140. } else {
  18141. return this._private.zoomingEnabled;
  18142. }
  18143. return this; // chaining
  18144. },
  18145. userZoomingEnabled: function userZoomingEnabled(bool) {
  18146. if (bool !== undefined) {
  18147. this._private.userZoomingEnabled = bool ? true : false;
  18148. } else {
  18149. return this._private.userZoomingEnabled;
  18150. }
  18151. return this; // chaining
  18152. },
  18153. boxSelectionEnabled: function boxSelectionEnabled(bool) {
  18154. if (bool !== undefined) {
  18155. this._private.boxSelectionEnabled = bool ? true : false;
  18156. } else {
  18157. return this._private.boxSelectionEnabled;
  18158. }
  18159. return this; // chaining
  18160. },
  18161. pan: function pan() {
  18162. var args = arguments;
  18163. var pan = this._private.pan;
  18164. var dim, val, dims, x, y;
  18165. switch (args.length) {
  18166. case 0:
  18167. // .pan()
  18168. return pan;
  18169. case 1:
  18170. if (string(args[0])) {
  18171. // .pan('x')
  18172. dim = args[0];
  18173. return pan[dim];
  18174. } else if (plainObject(args[0])) {
  18175. // .pan({ x: 0, y: 100 })
  18176. if (!this._private.panningEnabled) {
  18177. return this;
  18178. }
  18179. dims = args[0];
  18180. x = dims.x;
  18181. y = dims.y;
  18182. if (number$1(x)) {
  18183. pan.x = x;
  18184. }
  18185. if (number$1(y)) {
  18186. pan.y = y;
  18187. }
  18188. this.emit('pan viewport');
  18189. }
  18190. break;
  18191. case 2:
  18192. // .pan('x', 100)
  18193. if (!this._private.panningEnabled) {
  18194. return this;
  18195. }
  18196. dim = args[0];
  18197. val = args[1];
  18198. if ((dim === 'x' || dim === 'y') && number$1(val)) {
  18199. pan[dim] = val;
  18200. }
  18201. this.emit('pan viewport');
  18202. break;
  18203. // invalid
  18204. }
  18205. this.notify('viewport');
  18206. return this; // chaining
  18207. },
  18208. panBy: function panBy(arg0, arg1) {
  18209. var args = arguments;
  18210. var pan = this._private.pan;
  18211. var dim, val, dims, x, y;
  18212. if (!this._private.panningEnabled) {
  18213. return this;
  18214. }
  18215. switch (args.length) {
  18216. case 1:
  18217. if (plainObject(arg0)) {
  18218. // .panBy({ x: 0, y: 100 })
  18219. dims = args[0];
  18220. x = dims.x;
  18221. y = dims.y;
  18222. if (number$1(x)) {
  18223. pan.x += x;
  18224. }
  18225. if (number$1(y)) {
  18226. pan.y += y;
  18227. }
  18228. this.emit('pan viewport');
  18229. }
  18230. break;
  18231. case 2:
  18232. // .panBy('x', 100)
  18233. dim = arg0;
  18234. val = arg1;
  18235. if ((dim === 'x' || dim === 'y') && number$1(val)) {
  18236. pan[dim] += val;
  18237. }
  18238. this.emit('pan viewport');
  18239. break;
  18240. // invalid
  18241. }
  18242. this.notify('viewport');
  18243. return this; // chaining
  18244. },
  18245. gc: function gc() {
  18246. this.notify('gc');
  18247. },
  18248. fit: function fit(elements, padding) {
  18249. var viewportState = this.getFitViewport(elements, padding);
  18250. if (viewportState) {
  18251. var _p = this._private;
  18252. _p.zoom = viewportState.zoom;
  18253. _p.pan = viewportState.pan;
  18254. this.emit('pan zoom viewport');
  18255. this.notify('viewport');
  18256. }
  18257. return this; // chaining
  18258. },
  18259. getFitViewport: function getFitViewport(elements, padding) {
  18260. if (number$1(elements) && padding === undefined) {
  18261. // elements is optional
  18262. padding = elements;
  18263. elements = undefined;
  18264. }
  18265. if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
  18266. return;
  18267. }
  18268. var bb;
  18269. if (string(elements)) {
  18270. var sel = elements;
  18271. elements = this.$(sel);
  18272. } else if (boundingBox(elements)) {
  18273. // assume bb
  18274. var bbe = elements;
  18275. bb = {
  18276. x1: bbe.x1,
  18277. y1: bbe.y1,
  18278. x2: bbe.x2,
  18279. y2: bbe.y2
  18280. };
  18281. bb.w = bb.x2 - bb.x1;
  18282. bb.h = bb.y2 - bb.y1;
  18283. } else if (!elementOrCollection(elements)) {
  18284. elements = this.mutableElements();
  18285. }
  18286. if (elementOrCollection(elements) && elements.empty()) {
  18287. return;
  18288. } // can't fit to nothing
  18289. bb = bb || elements.boundingBox();
  18290. var w = this.width();
  18291. var h = this.height();
  18292. var zoom;
  18293. padding = number$1(padding) ? padding : 0;
  18294. if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0 && !isNaN(bb.w) && !isNaN(bb.h) && bb.w > 0 && bb.h > 0) {
  18295. zoom = Math.min((w - 2 * padding) / bb.w, (h - 2 * padding) / bb.h);
  18296. // crop zoom
  18297. zoom = zoom > this._private.maxZoom ? this._private.maxZoom : zoom;
  18298. zoom = zoom < this._private.minZoom ? this._private.minZoom : zoom;
  18299. var pan = {
  18300. // now pan to middle
  18301. x: (w - zoom * (bb.x1 + bb.x2)) / 2,
  18302. y: (h - zoom * (bb.y1 + bb.y2)) / 2
  18303. };
  18304. return {
  18305. zoom: zoom,
  18306. pan: pan
  18307. };
  18308. }
  18309. return;
  18310. },
  18311. zoomRange: function zoomRange(min, max) {
  18312. var _p = this._private;
  18313. if (max == null) {
  18314. var opts = min;
  18315. min = opts.min;
  18316. max = opts.max;
  18317. }
  18318. if (number$1(min) && number$1(max) && min <= max) {
  18319. _p.minZoom = min;
  18320. _p.maxZoom = max;
  18321. } else if (number$1(min) && max === undefined && min <= _p.maxZoom) {
  18322. _p.minZoom = min;
  18323. } else if (number$1(max) && min === undefined && max >= _p.minZoom) {
  18324. _p.maxZoom = max;
  18325. }
  18326. return this;
  18327. },
  18328. minZoom: function minZoom(zoom) {
  18329. if (zoom === undefined) {
  18330. return this._private.minZoom;
  18331. } else {
  18332. return this.zoomRange({
  18333. min: zoom
  18334. });
  18335. }
  18336. },
  18337. maxZoom: function maxZoom(zoom) {
  18338. if (zoom === undefined) {
  18339. return this._private.maxZoom;
  18340. } else {
  18341. return this.zoomRange({
  18342. max: zoom
  18343. });
  18344. }
  18345. },
  18346. getZoomedViewport: function getZoomedViewport(params) {
  18347. var _p = this._private;
  18348. var currentPan = _p.pan;
  18349. var currentZoom = _p.zoom;
  18350. var pos; // in rendered px
  18351. var zoom;
  18352. var bail = false;
  18353. if (!_p.zoomingEnabled) {
  18354. // zooming disabled
  18355. bail = true;
  18356. }
  18357. if (number$1(params)) {
  18358. // then set the zoom
  18359. zoom = params;
  18360. } else if (plainObject(params)) {
  18361. // then zoom about a point
  18362. zoom = params.level;
  18363. if (params.position != null) {
  18364. pos = modelToRenderedPosition$1(params.position, currentZoom, currentPan);
  18365. } else if (params.renderedPosition != null) {
  18366. pos = params.renderedPosition;
  18367. }
  18368. if (pos != null && !_p.panningEnabled) {
  18369. // panning disabled
  18370. bail = true;
  18371. }
  18372. }
  18373. // crop zoom
  18374. zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;
  18375. zoom = zoom < _p.minZoom ? _p.minZoom : zoom;
  18376. // can't zoom with invalid params
  18377. if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {
  18378. return null;
  18379. }
  18380. if (pos != null) {
  18381. // set zoom about position
  18382. var pan1 = currentPan;
  18383. var zoom1 = currentZoom;
  18384. var zoom2 = zoom;
  18385. var pan2 = {
  18386. x: -zoom2 / zoom1 * (pos.x - pan1.x) + pos.x,
  18387. y: -zoom2 / zoom1 * (pos.y - pan1.y) + pos.y
  18388. };
  18389. return {
  18390. zoomed: true,
  18391. panned: true,
  18392. zoom: zoom2,
  18393. pan: pan2
  18394. };
  18395. } else {
  18396. // just set the zoom
  18397. return {
  18398. zoomed: true,
  18399. panned: false,
  18400. zoom: zoom,
  18401. pan: currentPan
  18402. };
  18403. }
  18404. },
  18405. zoom: function zoom(params) {
  18406. if (params === undefined) {
  18407. // get
  18408. return this._private.zoom;
  18409. } else {
  18410. // set
  18411. var vp = this.getZoomedViewport(params);
  18412. var _p = this._private;
  18413. if (vp == null || !vp.zoomed) {
  18414. return this;
  18415. }
  18416. _p.zoom = vp.zoom;
  18417. if (vp.panned) {
  18418. _p.pan.x = vp.pan.x;
  18419. _p.pan.y = vp.pan.y;
  18420. }
  18421. this.emit('zoom' + (vp.panned ? ' pan' : '') + ' viewport');
  18422. this.notify('viewport');
  18423. return this; // chaining
  18424. }
  18425. },
  18426. viewport: function viewport(opts) {
  18427. var _p = this._private;
  18428. var zoomDefd = true;
  18429. var panDefd = true;
  18430. var events = []; // to trigger
  18431. var zoomFailed = false;
  18432. var panFailed = false;
  18433. if (!opts) {
  18434. return this;
  18435. }
  18436. if (!number$1(opts.zoom)) {
  18437. zoomDefd = false;
  18438. }
  18439. if (!plainObject(opts.pan)) {
  18440. panDefd = false;
  18441. }
  18442. if (!zoomDefd && !panDefd) {
  18443. return this;
  18444. }
  18445. if (zoomDefd) {
  18446. var z = opts.zoom;
  18447. if (z < _p.minZoom || z > _p.maxZoom || !_p.zoomingEnabled) {
  18448. zoomFailed = true;
  18449. } else {
  18450. _p.zoom = z;
  18451. events.push('zoom');
  18452. }
  18453. }
  18454. if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {
  18455. var p = opts.pan;
  18456. if (number$1(p.x)) {
  18457. _p.pan.x = p.x;
  18458. panFailed = false;
  18459. }
  18460. if (number$1(p.y)) {
  18461. _p.pan.y = p.y;
  18462. panFailed = false;
  18463. }
  18464. if (!panFailed) {
  18465. events.push('pan');
  18466. }
  18467. }
  18468. if (events.length > 0) {
  18469. events.push('viewport');
  18470. this.emit(events.join(' '));
  18471. this.notify('viewport');
  18472. }
  18473. return this; // chaining
  18474. },
  18475. center: function center(elements) {
  18476. var pan = this.getCenterPan(elements);
  18477. if (pan) {
  18478. this._private.pan = pan;
  18479. this.emit('pan viewport');
  18480. this.notify('viewport');
  18481. }
  18482. return this; // chaining
  18483. },
  18484. getCenterPan: function getCenterPan(elements, zoom) {
  18485. if (!this._private.panningEnabled) {
  18486. return;
  18487. }
  18488. if (string(elements)) {
  18489. var selector = elements;
  18490. elements = this.mutableElements().filter(selector);
  18491. } else if (!elementOrCollection(elements)) {
  18492. elements = this.mutableElements();
  18493. }
  18494. if (elements.length === 0) {
  18495. return;
  18496. } // can't centre pan to nothing
  18497. var bb = elements.boundingBox();
  18498. var w = this.width();
  18499. var h = this.height();
  18500. zoom = zoom === undefined ? this._private.zoom : zoom;
  18501. var pan = {
  18502. // middle
  18503. x: (w - zoom * (bb.x1 + bb.x2)) / 2,
  18504. y: (h - zoom * (bb.y1 + bb.y2)) / 2
  18505. };
  18506. return pan;
  18507. },
  18508. reset: function reset() {
  18509. if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
  18510. return this;
  18511. }
  18512. this.viewport({
  18513. pan: {
  18514. x: 0,
  18515. y: 0
  18516. },
  18517. zoom: 1
  18518. });
  18519. return this; // chaining
  18520. },
  18521. invalidateSize: function invalidateSize() {
  18522. this._private.sizeCache = null;
  18523. },
  18524. size: function size() {
  18525. var _p = this._private;
  18526. var container = _p.container;
  18527. var cy = this;
  18528. return _p.sizeCache = _p.sizeCache || (container ? function () {
  18529. var style = cy.window().getComputedStyle(container);
  18530. var val = function val(name) {
  18531. return parseFloat(style.getPropertyValue(name));
  18532. };
  18533. return {
  18534. width: container.clientWidth - val('padding-left') - val('padding-right'),
  18535. height: container.clientHeight - val('padding-top') - val('padding-bottom')
  18536. };
  18537. }() : {
  18538. // fallback if no container (not 0 b/c can be used for dividing etc)
  18539. width: 1,
  18540. height: 1
  18541. });
  18542. },
  18543. width: function width() {
  18544. return this.size().width;
  18545. },
  18546. height: function height() {
  18547. return this.size().height;
  18548. },
  18549. extent: function extent() {
  18550. var pan = this._private.pan;
  18551. var zoom = this._private.zoom;
  18552. var rb = this.renderedExtent();
  18553. var b = {
  18554. x1: (rb.x1 - pan.x) / zoom,
  18555. x2: (rb.x2 - pan.x) / zoom,
  18556. y1: (rb.y1 - pan.y) / zoom,
  18557. y2: (rb.y2 - pan.y) / zoom
  18558. };
  18559. b.w = b.x2 - b.x1;
  18560. b.h = b.y2 - b.y1;
  18561. return b;
  18562. },
  18563. renderedExtent: function renderedExtent() {
  18564. var width = this.width();
  18565. var height = this.height();
  18566. return {
  18567. x1: 0,
  18568. y1: 0,
  18569. x2: width,
  18570. y2: height,
  18571. w: width,
  18572. h: height
  18573. };
  18574. },
  18575. multiClickDebounceTime: function multiClickDebounceTime(_int) {
  18576. if (_int) this._private.multiClickDebounceTime = _int;else return this._private.multiClickDebounceTime;
  18577. return this; // chaining
  18578. }
  18579. };
  18580. // aliases
  18581. corefn$1.centre = corefn$1.center;
  18582. // backwards compatibility
  18583. corefn$1.autolockNodes = corefn$1.autolock;
  18584. corefn$1.autoungrabifyNodes = corefn$1.autoungrabify;
  18585. var fn = {
  18586. data: define.data({
  18587. field: 'data',
  18588. bindingEvent: 'data',
  18589. allowBinding: true,
  18590. allowSetting: true,
  18591. settingEvent: 'data',
  18592. settingTriggersEvent: true,
  18593. triggerFnName: 'trigger',
  18594. allowGetting: true,
  18595. updateStyle: true
  18596. }),
  18597. removeData: define.removeData({
  18598. field: 'data',
  18599. event: 'data',
  18600. triggerFnName: 'trigger',
  18601. triggerEvent: true,
  18602. updateStyle: true
  18603. }),
  18604. scratch: define.data({
  18605. field: 'scratch',
  18606. bindingEvent: 'scratch',
  18607. allowBinding: true,
  18608. allowSetting: true,
  18609. settingEvent: 'scratch',
  18610. settingTriggersEvent: true,
  18611. triggerFnName: 'trigger',
  18612. allowGetting: true,
  18613. updateStyle: true
  18614. }),
  18615. removeScratch: define.removeData({
  18616. field: 'scratch',
  18617. event: 'scratch',
  18618. triggerFnName: 'trigger',
  18619. triggerEvent: true,
  18620. updateStyle: true
  18621. })
  18622. };
  18623. // aliases
  18624. fn.attr = fn.data;
  18625. fn.removeAttr = fn.removeData;
  18626. var Core = function Core(opts) {
  18627. var cy = this;
  18628. opts = extend({}, opts);
  18629. var container = opts.container;
  18630. // allow for passing a wrapped jquery object
  18631. // e.g. cytoscape({ container: $('#cy') })
  18632. if (container && !htmlElement(container) && htmlElement(container[0])) {
  18633. container = container[0];
  18634. }
  18635. var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery
  18636. reg = reg || {};
  18637. if (reg && reg.cy) {
  18638. reg.cy.destroy();
  18639. reg = {}; // old instance => replace reg completely
  18640. }
  18641. var readies = reg.readies = reg.readies || [];
  18642. if (container) {
  18643. container._cyreg = reg;
  18644. } // make sure container assoc'd reg points to this cy
  18645. reg.cy = cy;
  18646. var head = _window !== undefined && container !== undefined && !opts.headless;
  18647. var options = opts;
  18648. options.layout = extend({
  18649. name: head ? 'grid' : 'null'
  18650. }, options.layout);
  18651. options.renderer = extend({
  18652. name: head ? 'canvas' : 'null'
  18653. }, options.renderer);
  18654. var defVal = function defVal(def, val, altVal) {
  18655. if (val !== undefined) {
  18656. return val;
  18657. } else if (altVal !== undefined) {
  18658. return altVal;
  18659. } else {
  18660. return def;
  18661. }
  18662. };
  18663. var _p = this._private = {
  18664. container: container,
  18665. // html dom ele container
  18666. ready: false,
  18667. // whether ready has been triggered
  18668. options: options,
  18669. // cached options
  18670. elements: new Collection(this),
  18671. // elements in the graph
  18672. listeners: [],
  18673. // list of listeners
  18674. aniEles: new Collection(this),
  18675. // elements being animated
  18676. data: options.data || {},
  18677. // data for the core
  18678. scratch: {},
  18679. // scratch object for core
  18680. layout: null,
  18681. renderer: null,
  18682. destroyed: false,
  18683. // whether destroy was called
  18684. notificationsEnabled: true,
  18685. // whether notifications are sent to the renderer
  18686. minZoom: 1e-50,
  18687. maxZoom: 1e50,
  18688. zoomingEnabled: defVal(true, options.zoomingEnabled),
  18689. userZoomingEnabled: defVal(true, options.userZoomingEnabled),
  18690. panningEnabled: defVal(true, options.panningEnabled),
  18691. userPanningEnabled: defVal(true, options.userPanningEnabled),
  18692. boxSelectionEnabled: defVal(true, options.boxSelectionEnabled),
  18693. autolock: defVal(false, options.autolock, options.autolockNodes),
  18694. autoungrabify: defVal(false, options.autoungrabify, options.autoungrabifyNodes),
  18695. autounselectify: defVal(false, options.autounselectify),
  18696. styleEnabled: options.styleEnabled === undefined ? head : options.styleEnabled,
  18697. zoom: number$1(options.zoom) ? options.zoom : 1,
  18698. pan: {
  18699. x: plainObject(options.pan) && number$1(options.pan.x) ? options.pan.x : 0,
  18700. y: plainObject(options.pan) && number$1(options.pan.y) ? options.pan.y : 0
  18701. },
  18702. animation: {
  18703. // object for currently-running animations
  18704. current: [],
  18705. queue: []
  18706. },
  18707. hasCompoundNodes: false,
  18708. multiClickDebounceTime: defVal(250, options.multiClickDebounceTime)
  18709. };
  18710. this.createEmitter();
  18711. // set selection type
  18712. this.selectionType(options.selectionType);
  18713. // init zoom bounds
  18714. this.zoomRange({
  18715. min: options.minZoom,
  18716. max: options.maxZoom
  18717. });
  18718. var loadExtData = function loadExtData(extData, next) {
  18719. var anyIsPromise = extData.some(promise);
  18720. if (anyIsPromise) {
  18721. return Promise$1.all(extData).then(next); // load all data asynchronously, then exec rest of init
  18722. } else {
  18723. next(extData); // exec synchronously for convenience
  18724. }
  18725. };
  18726. // start with the default stylesheet so we have something before loading an external stylesheet
  18727. if (_p.styleEnabled) {
  18728. cy.setStyle([]);
  18729. }
  18730. // create the renderer
  18731. var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options
  18732. cy.initRenderer(rendererOptions);
  18733. var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {
  18734. cy.notifications(false);
  18735. // remove old elements
  18736. var oldEles = cy.mutableElements();
  18737. if (oldEles.length > 0) {
  18738. oldEles.remove();
  18739. }
  18740. if (elements != null) {
  18741. if (plainObject(elements) || array(elements)) {
  18742. cy.add(elements);
  18743. }
  18744. }
  18745. cy.one('layoutready', function (e) {
  18746. cy.notifications(true);
  18747. cy.emit(e); // we missed this event by turning notifications off, so pass it on
  18748. cy.one('load', onload);
  18749. cy.emitAndNotify('load');
  18750. }).one('layoutstop', function () {
  18751. cy.one('done', ondone);
  18752. cy.emit('done');
  18753. });
  18754. var layoutOpts = extend({}, cy._private.options.layout);
  18755. layoutOpts.eles = cy.elements();
  18756. cy.layout(layoutOpts).run();
  18757. };
  18758. loadExtData([options.style, options.elements], function (thens) {
  18759. var initStyle = thens[0];
  18760. var initEles = thens[1];
  18761. // init style
  18762. if (_p.styleEnabled) {
  18763. cy.style().append(initStyle);
  18764. }
  18765. // initial load
  18766. setElesAndLayout(initEles, function () {
  18767. // onready
  18768. cy.startAnimationLoop();
  18769. _p.ready = true;
  18770. // if a ready callback is specified as an option, the bind it
  18771. if (fn$6(options.ready)) {
  18772. cy.on('ready', options.ready);
  18773. }
  18774. // bind all the ready handlers registered before creating this instance
  18775. for (var i = 0; i < readies.length; i++) {
  18776. var fn = readies[i];
  18777. cy.on('ready', fn);
  18778. }
  18779. if (reg) {
  18780. reg.readies = [];
  18781. } // clear b/c we've bound them all and don't want to keep it around in case a new core uses the same div etc
  18782. cy.emit('ready');
  18783. }, options.done);
  18784. });
  18785. };
  18786. var corefn = Core.prototype; // short alias
  18787. extend(corefn, {
  18788. instanceString: function instanceString() {
  18789. return 'core';
  18790. },
  18791. isReady: function isReady() {
  18792. return this._private.ready;
  18793. },
  18794. destroyed: function destroyed() {
  18795. return this._private.destroyed;
  18796. },
  18797. ready: function ready(fn) {
  18798. if (this.isReady()) {
  18799. this.emitter().emit('ready', [], fn); // just calls fn as though triggered via ready event
  18800. } else {
  18801. this.on('ready', fn);
  18802. }
  18803. return this;
  18804. },
  18805. destroy: function destroy() {
  18806. var cy = this;
  18807. if (cy.destroyed()) return;
  18808. cy.stopAnimationLoop();
  18809. cy.destroyRenderer();
  18810. this.emit('destroy');
  18811. cy._private.destroyed = true;
  18812. return cy;
  18813. },
  18814. hasElementWithId: function hasElementWithId(id) {
  18815. return this._private.elements.hasElementWithId(id);
  18816. },
  18817. getElementById: function getElementById(id) {
  18818. return this._private.elements.getElementById(id);
  18819. },
  18820. hasCompoundNodes: function hasCompoundNodes() {
  18821. return this._private.hasCompoundNodes;
  18822. },
  18823. headless: function headless() {
  18824. return this._private.renderer.isHeadless();
  18825. },
  18826. styleEnabled: function styleEnabled() {
  18827. return this._private.styleEnabled;
  18828. },
  18829. addToPool: function addToPool(eles) {
  18830. this._private.elements.merge(eles);
  18831. return this; // chaining
  18832. },
  18833. removeFromPool: function removeFromPool(eles) {
  18834. this._private.elements.unmerge(eles);
  18835. return this;
  18836. },
  18837. container: function container() {
  18838. return this._private.container || null;
  18839. },
  18840. window: function window() {
  18841. var container = this._private.container;
  18842. if (container == null) return _window;
  18843. var ownerDocument = this._private.container.ownerDocument;
  18844. if (ownerDocument === undefined || ownerDocument == null) {
  18845. return _window;
  18846. }
  18847. return ownerDocument.defaultView || _window;
  18848. },
  18849. mount: function mount(container) {
  18850. if (container == null) {
  18851. return;
  18852. }
  18853. var cy = this;
  18854. var _p = cy._private;
  18855. var options = _p.options;
  18856. if (!htmlElement(container) && htmlElement(container[0])) {
  18857. container = container[0];
  18858. }
  18859. cy.stopAnimationLoop();
  18860. cy.destroyRenderer();
  18861. _p.container = container;
  18862. _p.styleEnabled = true;
  18863. cy.invalidateSize();
  18864. cy.initRenderer(extend({}, options, options.renderer, {
  18865. // allow custom renderer name to be re-used, otherwise use canvas
  18866. name: options.renderer.name === 'null' ? 'canvas' : options.renderer.name
  18867. }));
  18868. cy.startAnimationLoop();
  18869. cy.style(options.style);
  18870. cy.emit('mount');
  18871. return cy;
  18872. },
  18873. unmount: function unmount() {
  18874. var cy = this;
  18875. cy.stopAnimationLoop();
  18876. cy.destroyRenderer();
  18877. cy.initRenderer({
  18878. name: 'null'
  18879. });
  18880. cy.emit('unmount');
  18881. return cy;
  18882. },
  18883. options: function options() {
  18884. return copy(this._private.options);
  18885. },
  18886. json: function json(obj) {
  18887. var cy = this;
  18888. var _p = cy._private;
  18889. var eles = cy.mutableElements();
  18890. var getFreshRef = function getFreshRef(ele) {
  18891. return cy.getElementById(ele.id());
  18892. };
  18893. if (plainObject(obj)) {
  18894. // set
  18895. cy.startBatch();
  18896. if (obj.elements) {
  18897. var idInJson = {};
  18898. var updateEles = function updateEles(jsons, gr) {
  18899. var toAdd = [];
  18900. var toMod = [];
  18901. for (var i = 0; i < jsons.length; i++) {
  18902. var json = jsons[i];
  18903. if (!json.data.id) {
  18904. warn('cy.json() cannot handle elements without an ID attribute');
  18905. continue;
  18906. }
  18907. var id = '' + json.data.id; // id must be string
  18908. var ele = cy.getElementById(id);
  18909. idInJson[id] = true;
  18910. if (ele.length !== 0) {
  18911. // existing element should be updated
  18912. toMod.push({
  18913. ele: ele,
  18914. json: json
  18915. });
  18916. } else {
  18917. // otherwise should be added
  18918. if (gr) {
  18919. json.group = gr;
  18920. toAdd.push(json);
  18921. } else {
  18922. toAdd.push(json);
  18923. }
  18924. }
  18925. }
  18926. cy.add(toAdd);
  18927. for (var _i = 0; _i < toMod.length; _i++) {
  18928. var _toMod$_i = toMod[_i],
  18929. _ele = _toMod$_i.ele,
  18930. _json = _toMod$_i.json;
  18931. _ele.json(_json);
  18932. }
  18933. };
  18934. if (array(obj.elements)) {
  18935. // elements: []
  18936. updateEles(obj.elements);
  18937. } else {
  18938. // elements: { nodes: [], edges: [] }
  18939. var grs = ['nodes', 'edges'];
  18940. for (var i = 0; i < grs.length; i++) {
  18941. var gr = grs[i];
  18942. var elements = obj.elements[gr];
  18943. if (array(elements)) {
  18944. updateEles(elements, gr);
  18945. }
  18946. }
  18947. }
  18948. var parentsToRemove = cy.collection();
  18949. eles.filter(function (ele) {
  18950. return !idInJson[ele.id()];
  18951. }).forEach(function (ele) {
  18952. if (ele.isParent()) {
  18953. parentsToRemove.merge(ele);
  18954. } else {
  18955. ele.remove();
  18956. }
  18957. });
  18958. // so that children are not removed w/parent
  18959. parentsToRemove.forEach(function (ele) {
  18960. return ele.children().move({
  18961. parent: null
  18962. });
  18963. });
  18964. // intermediate parents may be moved by prior line, so make sure we remove by fresh refs
  18965. parentsToRemove.forEach(function (ele) {
  18966. return getFreshRef(ele).remove();
  18967. });
  18968. }
  18969. if (obj.style) {
  18970. cy.style(obj.style);
  18971. }
  18972. if (obj.zoom != null && obj.zoom !== _p.zoom) {
  18973. cy.zoom(obj.zoom);
  18974. }
  18975. if (obj.pan) {
  18976. if (obj.pan.x !== _p.pan.x || obj.pan.y !== _p.pan.y) {
  18977. cy.pan(obj.pan);
  18978. }
  18979. }
  18980. if (obj.data) {
  18981. cy.data(obj.data);
  18982. }
  18983. var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];
  18984. for (var _i2 = 0; _i2 < fields.length; _i2++) {
  18985. var f = fields[_i2];
  18986. if (obj[f] != null) {
  18987. cy[f](obj[f]);
  18988. }
  18989. }
  18990. cy.endBatch();
  18991. return this; // chaining
  18992. } else {
  18993. // get
  18994. var flat = !!obj;
  18995. var json = {};
  18996. if (flat) {
  18997. json.elements = this.elements().map(function (ele) {
  18998. return ele.json();
  18999. });
  19000. } else {
  19001. json.elements = {};
  19002. eles.forEach(function (ele) {
  19003. var group = ele.group();
  19004. if (!json.elements[group]) {
  19005. json.elements[group] = [];
  19006. }
  19007. json.elements[group].push(ele.json());
  19008. });
  19009. }
  19010. if (this._private.styleEnabled) {
  19011. json.style = cy.style().json();
  19012. }
  19013. json.data = copy(cy.data());
  19014. var options = _p.options;
  19015. json.zoomingEnabled = _p.zoomingEnabled;
  19016. json.userZoomingEnabled = _p.userZoomingEnabled;
  19017. json.zoom = _p.zoom;
  19018. json.minZoom = _p.minZoom;
  19019. json.maxZoom = _p.maxZoom;
  19020. json.panningEnabled = _p.panningEnabled;
  19021. json.userPanningEnabled = _p.userPanningEnabled;
  19022. json.pan = copy(_p.pan);
  19023. json.boxSelectionEnabled = _p.boxSelectionEnabled;
  19024. json.renderer = copy(options.renderer);
  19025. json.hideEdgesOnViewport = options.hideEdgesOnViewport;
  19026. json.textureOnViewport = options.textureOnViewport;
  19027. json.wheelSensitivity = options.wheelSensitivity;
  19028. json.motionBlur = options.motionBlur;
  19029. json.multiClickDebounceTime = options.multiClickDebounceTime;
  19030. return json;
  19031. }
  19032. }
  19033. });
  19034. corefn.$id = corefn.getElementById;
  19035. [corefn$9, corefn$8, elesfn, corefn$7, corefn$6, corefn$5, corefn$4, corefn$3, corefn$2, corefn$1, fn].forEach(function (props) {
  19036. extend(corefn, props);
  19037. });
  19038. /* eslint-disable no-unused-vars */
  19039. var defaults$7 = {
  19040. fit: true,
  19041. // whether to fit the viewport to the graph
  19042. directed: false,
  19043. // whether the tree is directed downwards (or edges can point in any direction if false)
  19044. direction: 'downward',
  19045. // determines the direction in which the tree structure is drawn. The possible values are 'downward', 'upward', 'rightward', or 'leftward'.
  19046. padding: 30,
  19047. // padding on fit
  19048. circle: false,
  19049. // put depths in concentric circles if true, put depths top down if false
  19050. grid: false,
  19051. // whether to create an even grid into which the DAG is placed (circle:false only)
  19052. spacingFactor: 1.75,
  19053. // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)
  19054. boundingBox: undefined,
  19055. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19056. avoidOverlap: true,
  19057. // prevents node overlap, may overflow boundingBox if not enough space
  19058. nodeDimensionsIncludeLabels: false,
  19059. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19060. roots: undefined,
  19061. // the roots of the trees
  19062. depthSort: undefined,
  19063. // a sorting function to order nodes at equal depth. e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  19064. animate: false,
  19065. // whether to transition the node positions
  19066. animationDuration: 500,
  19067. // duration of animation in ms if enabled
  19068. animationEasing: undefined,
  19069. // easing of animation if enabled,
  19070. animateFilter: function animateFilter(node, i) {
  19071. return true;
  19072. },
  19073. // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts
  19074. ready: undefined,
  19075. // callback on layoutready
  19076. stop: undefined,
  19077. // callback on layoutstop
  19078. transform: function transform(node, position) {
  19079. return position;
  19080. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19081. };
  19082. var deprecatedOptionDefaults = {
  19083. maximal: false,
  19084. // whether to shift nodes down their natural BFS depths in order to avoid upwards edges (DAGS only); setting acyclic to true sets maximal to true also
  19085. acyclic: false // whether the tree is acyclic and thus a node could be shifted (due to the maximal option) multiple times without causing an infinite loop; setting to true sets maximal to true also; if you are uncertain whether a tree is acyclic, set to false to avoid potential infinite loops
  19086. };
  19087. /* eslint-enable */
  19088. var getInfo = function getInfo(ele) {
  19089. return ele.scratch('breadthfirst');
  19090. };
  19091. var setInfo = function setInfo(ele, obj) {
  19092. return ele.scratch('breadthfirst', obj);
  19093. };
  19094. function BreadthFirstLayout(options) {
  19095. this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);
  19096. }
  19097. BreadthFirstLayout.prototype.run = function () {
  19098. var options = this.options;
  19099. var cy = options.cy;
  19100. var eles = options.eles;
  19101. var nodes = eles.nodes().filter(function (n) {
  19102. return n.isChildless();
  19103. });
  19104. var graph = eles;
  19105. var directed = options.directed;
  19106. var maximal = options.acyclic || options.maximal || options.maximalAdjustments > 0; // maximalAdjustments for compat. w/ old code; also, setting acyclic to true sets maximal to true
  19107. var hasBoundingBox = !!options.boundingBox;
  19108. var bb = makeBoundingBox(hasBoundingBox ? options.boundingBox : structuredClone(cy.extent()));
  19109. var roots;
  19110. if (elementOrCollection(options.roots)) {
  19111. roots = options.roots;
  19112. } else if (array(options.roots)) {
  19113. var rootsArray = [];
  19114. for (var i = 0; i < options.roots.length; i++) {
  19115. var id = options.roots[i];
  19116. var ele = cy.getElementById(id);
  19117. rootsArray.push(ele);
  19118. }
  19119. roots = cy.collection(rootsArray);
  19120. } else if (string(options.roots)) {
  19121. roots = cy.$(options.roots);
  19122. } else {
  19123. if (directed) {
  19124. roots = nodes.roots();
  19125. } else {
  19126. var components = eles.components();
  19127. roots = cy.collection();
  19128. var _loop = function _loop() {
  19129. var comp = components[_i];
  19130. var maxDegree = comp.maxDegree(false);
  19131. var compRoots = comp.filter(function (ele) {
  19132. return ele.degree(false) === maxDegree;
  19133. });
  19134. roots = roots.add(compRoots);
  19135. };
  19136. for (var _i = 0; _i < components.length; _i++) {
  19137. _loop();
  19138. }
  19139. }
  19140. }
  19141. var depths = [];
  19142. var foundByBfs = {};
  19143. var addToDepth = function addToDepth(ele, d) {
  19144. if (depths[d] == null) {
  19145. depths[d] = [];
  19146. }
  19147. var i = depths[d].length;
  19148. depths[d].push(ele);
  19149. setInfo(ele, {
  19150. index: i,
  19151. depth: d
  19152. });
  19153. };
  19154. var changeDepth = function changeDepth(ele, newDepth) {
  19155. var _getInfo = getInfo(ele),
  19156. depth = _getInfo.depth,
  19157. index = _getInfo.index;
  19158. depths[depth][index] = null;
  19159. // add only childless nodes
  19160. if (ele.isChildless()) addToDepth(ele, newDepth);
  19161. };
  19162. // find the depths of the nodes
  19163. graph.bfs({
  19164. roots: roots,
  19165. directed: options.directed,
  19166. visit: function visit(node, edge, pNode, i, depth) {
  19167. var ele = node[0];
  19168. var id = ele.id();
  19169. // add only childless nodes
  19170. if (ele.isChildless()) addToDepth(ele, depth);
  19171. foundByBfs[id] = true;
  19172. }
  19173. });
  19174. // check for nodes not found by bfs
  19175. var orphanNodes = [];
  19176. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  19177. var _ele = nodes[_i2];
  19178. if (foundByBfs[_ele.id()]) {
  19179. continue;
  19180. } else {
  19181. orphanNodes.push(_ele);
  19182. }
  19183. }
  19184. // assign the nodes a depth and index
  19185. var assignDepthsAt = function assignDepthsAt(i) {
  19186. var eles = depths[i];
  19187. for (var j = 0; j < eles.length; j++) {
  19188. var _ele2 = eles[j];
  19189. if (_ele2 == null) {
  19190. eles.splice(j, 1);
  19191. j--;
  19192. continue;
  19193. }
  19194. setInfo(_ele2, {
  19195. depth: i,
  19196. index: j
  19197. });
  19198. }
  19199. };
  19200. var adjustMaximally = function adjustMaximally(ele, shifted) {
  19201. var eInfo = getInfo(ele);
  19202. var incomers = ele.incomers().filter(function (el) {
  19203. return el.isNode() && eles.has(el);
  19204. });
  19205. var maxDepth = -1;
  19206. var id = ele.id();
  19207. for (var k = 0; k < incomers.length; k++) {
  19208. var incmr = incomers[k];
  19209. var iInfo = getInfo(incmr);
  19210. maxDepth = Math.max(maxDepth, iInfo.depth);
  19211. }
  19212. if (eInfo.depth <= maxDepth) {
  19213. if (!options.acyclic && shifted[id]) {
  19214. return null;
  19215. }
  19216. var newDepth = maxDepth + 1;
  19217. changeDepth(ele, newDepth);
  19218. shifted[id] = newDepth;
  19219. return true;
  19220. }
  19221. return false;
  19222. };
  19223. // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)
  19224. if (directed && maximal) {
  19225. var Q = [];
  19226. var shifted = {};
  19227. var enqueue = function enqueue(n) {
  19228. return Q.push(n);
  19229. };
  19230. var dequeue = function dequeue() {
  19231. return Q.shift();
  19232. };
  19233. nodes.forEach(function (n) {
  19234. return Q.push(n);
  19235. });
  19236. while (Q.length > 0) {
  19237. var _ele3 = dequeue();
  19238. var didShift = adjustMaximally(_ele3, shifted);
  19239. if (didShift) {
  19240. _ele3.outgoers().filter(function (el) {
  19241. return el.isNode() && eles.has(el);
  19242. }).forEach(enqueue);
  19243. } else if (didShift === null) {
  19244. warn('Detected double maximal shift for node `' + _ele3.id() + '`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.');
  19245. break; // exit on failure
  19246. }
  19247. }
  19248. }
  19249. // find min distance we need to leave between nodes
  19250. var minDistance = 0;
  19251. if (options.avoidOverlap) {
  19252. for (var _i3 = 0; _i3 < nodes.length; _i3++) {
  19253. var n = nodes[_i3];
  19254. var nbb = n.layoutDimensions(options);
  19255. var w = nbb.w;
  19256. var h = nbb.h;
  19257. minDistance = Math.max(minDistance, w, h);
  19258. }
  19259. }
  19260. // get the weighted percent for an element based on its connectivity to other levels
  19261. var cachedWeightedPercent = {};
  19262. var getWeightedPercent = function getWeightedPercent(ele) {
  19263. if (cachedWeightedPercent[ele.id()]) {
  19264. return cachedWeightedPercent[ele.id()];
  19265. }
  19266. var eleDepth = getInfo(ele).depth;
  19267. var neighbors = ele.neighborhood();
  19268. var percent = 0;
  19269. var samples = 0;
  19270. for (var _i4 = 0; _i4 < neighbors.length; _i4++) {
  19271. var neighbor = neighbors[_i4];
  19272. if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {
  19273. continue;
  19274. }
  19275. var bf = getInfo(neighbor);
  19276. if (bf == null) {
  19277. continue;
  19278. }
  19279. var index = bf.index;
  19280. var depth = bf.depth;
  19281. // unassigned neighbours shouldn't affect the ordering
  19282. if (index == null || depth == null) {
  19283. continue;
  19284. }
  19285. var nDepth = depths[depth].length;
  19286. if (depth < eleDepth) {
  19287. // only get influenced by elements above
  19288. percent += index / nDepth;
  19289. samples++;
  19290. }
  19291. }
  19292. samples = Math.max(1, samples);
  19293. percent = percent / samples;
  19294. if (samples === 0) {
  19295. // put lone nodes at the start
  19296. percent = 0;
  19297. }
  19298. cachedWeightedPercent[ele.id()] = percent;
  19299. return percent;
  19300. };
  19301. // rearrange the indices in each depth level based on connectivity
  19302. var sortFn = function sortFn(a, b) {
  19303. var apct = getWeightedPercent(a);
  19304. var bpct = getWeightedPercent(b);
  19305. var diff = apct - bpct;
  19306. if (diff === 0) {
  19307. return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons
  19308. } else {
  19309. return diff;
  19310. }
  19311. };
  19312. if (options.depthSort !== undefined) {
  19313. sortFn = options.depthSort;
  19314. }
  19315. var depthsLen = depths.length;
  19316. // sort each level to make connected nodes closer
  19317. for (var _i5 = 0; _i5 < depthsLen; _i5++) {
  19318. depths[_i5].sort(sortFn);
  19319. assignDepthsAt(_i5);
  19320. }
  19321. // assign orphan nodes to a new top-level depth
  19322. var orphanDepth = [];
  19323. for (var _i6 = 0; _i6 < orphanNodes.length; _i6++) {
  19324. orphanDepth.push(orphanNodes[_i6]);
  19325. }
  19326. var assignDepths = function assignDepths() {
  19327. for (var _i7 = 0; _i7 < depthsLen; _i7++) {
  19328. assignDepthsAt(_i7);
  19329. }
  19330. };
  19331. // add a new top-level depth only when there are orphan nodes
  19332. if (orphanDepth.length) {
  19333. depths.unshift(orphanDepth);
  19334. depthsLen = depths.length;
  19335. assignDepths();
  19336. }
  19337. var biggestDepthSize = 0;
  19338. for (var _i8 = 0; _i8 < depthsLen; _i8++) {
  19339. biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);
  19340. }
  19341. var center = {
  19342. x: bb.x1 + bb.w / 2,
  19343. y: bb.y1 + bb.h / 2
  19344. };
  19345. // average node size
  19346. var aveNodeSize = nodes.reduce(function (acc, node) {
  19347. return function (box) {
  19348. return {
  19349. w: acc.w === -1 ? box.w : (acc.w + box.w) / 2,
  19350. h: acc.h === -1 ? box.h : (acc.h + box.h) / 2
  19351. };
  19352. }(node.boundingBox({
  19353. includeLabels: options.nodeDimensionsIncludeLabels
  19354. }));
  19355. }, {
  19356. w: -1,
  19357. h: -1
  19358. });
  19359. var distanceY = Math.max(
  19360. // only one depth
  19361. depthsLen === 1 ? 0 :
  19362. // inside a bounding box, no need for top & bottom padding
  19363. hasBoundingBox ? (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen - 1) : (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen + 1), minDistance);
  19364. var maxDepthSize = depths.reduce(function (max, eles) {
  19365. return Math.max(max, eles.length);
  19366. }, 0);
  19367. var getPositionTopBottom = function getPositionTopBottom(ele) {
  19368. var _getInfo2 = getInfo(ele),
  19369. depth = _getInfo2.depth,
  19370. index = _getInfo2.index;
  19371. if (options.circle) {
  19372. var radiusStepSize = Math.min(bb.w / 2 / depthsLen, bb.h / 2 / depthsLen);
  19373. radiusStepSize = Math.max(radiusStepSize, minDistance);
  19374. var radius = radiusStepSize * depth + radiusStepSize - (depthsLen > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);
  19375. var theta = 2 * Math.PI / depths[depth].length * index;
  19376. if (depth === 0 && depths[0].length === 1) {
  19377. radius = 1;
  19378. }
  19379. return {
  19380. x: center.x + radius * Math.cos(theta),
  19381. y: center.y + radius * Math.sin(theta)
  19382. };
  19383. } else {
  19384. var depthSize = depths[depth].length;
  19385. var distanceX = Math.max(
  19386. // only one depth
  19387. depthSize === 1 ? 0 :
  19388. // inside a bounding box, no need for left & right padding
  19389. hasBoundingBox ? (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) - 1) : (bb.w - options.padding * 2 - aveNodeSize.w) / ((options.grid ? maxDepthSize : depthSize) + 1), minDistance);
  19390. var epos = {
  19391. x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,
  19392. y: center.y + (depth + 1 - (depthsLen + 1) / 2) * distanceY
  19393. };
  19394. return epos;
  19395. }
  19396. };
  19397. var rotateDegrees = {
  19398. 'downward': 0,
  19399. 'leftward': 90,
  19400. 'upward': 180,
  19401. 'rightward': -90
  19402. };
  19403. if (Object.keys(rotateDegrees).indexOf(options.direction) === -1) {
  19404. error("Invalid direction '".concat(options.direction, "' specified for breadthfirst layout. Valid values are: ").concat(Object.keys(rotateDegrees).join(', ')));
  19405. }
  19406. var getPosition = function getPosition(ele) {
  19407. return rotatePosAndSkewByBox(getPositionTopBottom(ele), bb, rotateDegrees[options.direction]);
  19408. };
  19409. eles.nodes().layoutPositions(this, options, getPosition);
  19410. return this; // chaining
  19411. };
  19412. var defaults$6 = {
  19413. fit: true,
  19414. // whether to fit the viewport to the graph
  19415. padding: 30,
  19416. // the padding on fit
  19417. boundingBox: undefined,
  19418. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19419. avoidOverlap: true,
  19420. // prevents node overlap, may overflow boundingBox and radius if not enough space
  19421. nodeDimensionsIncludeLabels: false,
  19422. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19423. spacingFactor: undefined,
  19424. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  19425. radius: undefined,
  19426. // the radius of the circle
  19427. startAngle: 3 / 2 * Math.PI,
  19428. // where nodes start in radians
  19429. sweep: undefined,
  19430. // how many radians should be between the first and last node (defaults to full circle)
  19431. clockwise: true,
  19432. // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  19433. sort: undefined,
  19434. // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  19435. animate: false,
  19436. // whether to transition the node positions
  19437. animationDuration: 500,
  19438. // duration of animation in ms if enabled
  19439. animationEasing: undefined,
  19440. // easing of animation if enabled
  19441. animateFilter: function animateFilter(node, i) {
  19442. return true;
  19443. },
  19444. // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts
  19445. ready: undefined,
  19446. // callback on layoutready
  19447. stop: undefined,
  19448. // callback on layoutstop
  19449. transform: function transform(node, position) {
  19450. return position;
  19451. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19452. };
  19453. function CircleLayout(options) {
  19454. this.options = extend({}, defaults$6, options);
  19455. }
  19456. CircleLayout.prototype.run = function () {
  19457. var params = this.options;
  19458. var options = params;
  19459. var cy = params.cy;
  19460. var eles = options.eles;
  19461. var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  19462. var nodes = eles.nodes().not(':parent');
  19463. if (options.sort) {
  19464. nodes = nodes.sort(options.sort);
  19465. }
  19466. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19467. x1: 0,
  19468. y1: 0,
  19469. w: cy.width(),
  19470. h: cy.height()
  19471. });
  19472. var center = {
  19473. x: bb.x1 + bb.w / 2,
  19474. y: bb.y1 + bb.h / 2
  19475. };
  19476. var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / nodes.length : options.sweep;
  19477. var dTheta = sweep / Math.max(1, nodes.length - 1);
  19478. var r;
  19479. var minDistance = 0;
  19480. for (var i = 0; i < nodes.length; i++) {
  19481. var n = nodes[i];
  19482. var nbb = n.layoutDimensions(options);
  19483. var w = nbb.w;
  19484. var h = nbb.h;
  19485. minDistance = Math.max(minDistance, w, h);
  19486. }
  19487. if (number$1(options.radius)) {
  19488. r = options.radius;
  19489. } else if (nodes.length <= 1) {
  19490. r = 0;
  19491. } else {
  19492. r = Math.min(bb.h, bb.w) / 2 - minDistance;
  19493. }
  19494. // calculate the radius
  19495. if (nodes.length > 1 && options.avoidOverlap) {
  19496. // but only if more than one node (can't overlap)
  19497. minDistance *= 1.75; // just to have some nice spacing
  19498. var dcos = Math.cos(dTheta) - Math.cos(0);
  19499. var dsin = Math.sin(dTheta) - Math.sin(0);
  19500. var rMin = Math.sqrt(minDistance * minDistance / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
  19501. r = Math.max(rMin, r);
  19502. }
  19503. var getPos = function getPos(ele, i) {
  19504. var theta = options.startAngle + i * dTheta * (clockwise ? 1 : -1);
  19505. var rx = r * Math.cos(theta);
  19506. var ry = r * Math.sin(theta);
  19507. var pos = {
  19508. x: center.x + rx,
  19509. y: center.y + ry
  19510. };
  19511. return pos;
  19512. };
  19513. eles.nodes().layoutPositions(this, options, getPos);
  19514. return this; // chaining
  19515. };
  19516. var defaults$5 = {
  19517. fit: true,
  19518. // whether to fit the viewport to the graph
  19519. padding: 30,
  19520. // the padding on fit
  19521. startAngle: 3 / 2 * Math.PI,
  19522. // where nodes start in radians
  19523. sweep: undefined,
  19524. // how many radians should be between the first and last node (defaults to full circle)
  19525. clockwise: true,
  19526. // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  19527. equidistant: false,
  19528. // whether levels have an equal radial distance betwen them, may cause bounding box overflow
  19529. minNodeSpacing: 10,
  19530. // min spacing between outside of nodes (used for radius adjustment)
  19531. boundingBox: undefined,
  19532. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19533. avoidOverlap: true,
  19534. // prevents node overlap, may overflow boundingBox if not enough space
  19535. nodeDimensionsIncludeLabels: false,
  19536. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19537. height: undefined,
  19538. // height of layout area (overrides container height)
  19539. width: undefined,
  19540. // width of layout area (overrides container width)
  19541. spacingFactor: undefined,
  19542. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  19543. concentric: function concentric(node) {
  19544. // returns numeric value for each node, placing higher nodes in levels towards the centre
  19545. return node.degree();
  19546. },
  19547. levelWidth: function levelWidth(nodes) {
  19548. // the variation of concentric values in each level
  19549. return nodes.maxDegree() / 4;
  19550. },
  19551. animate: false,
  19552. // whether to transition the node positions
  19553. animationDuration: 500,
  19554. // duration of animation in ms if enabled
  19555. animationEasing: undefined,
  19556. // easing of animation if enabled
  19557. animateFilter: function animateFilter(node, i) {
  19558. return true;
  19559. },
  19560. // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts
  19561. ready: undefined,
  19562. // callback on layoutready
  19563. stop: undefined,
  19564. // callback on layoutstop
  19565. transform: function transform(node, position) {
  19566. return position;
  19567. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19568. };
  19569. function ConcentricLayout(options) {
  19570. this.options = extend({}, defaults$5, options);
  19571. }
  19572. ConcentricLayout.prototype.run = function () {
  19573. var params = this.options;
  19574. var options = params;
  19575. var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  19576. var cy = params.cy;
  19577. var eles = options.eles;
  19578. var nodes = eles.nodes().not(':parent');
  19579. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19580. x1: 0,
  19581. y1: 0,
  19582. w: cy.width(),
  19583. h: cy.height()
  19584. });
  19585. var center = {
  19586. x: bb.x1 + bb.w / 2,
  19587. y: bb.y1 + bb.h / 2
  19588. };
  19589. var nodeValues = []; // { node, value }
  19590. var maxNodeSize = 0;
  19591. for (var i = 0; i < nodes.length; i++) {
  19592. var node = nodes[i];
  19593. var value = undefined;
  19594. // calculate the node value
  19595. value = options.concentric(node);
  19596. nodeValues.push({
  19597. value: value,
  19598. node: node
  19599. });
  19600. // for style mapping
  19601. node._private.scratch.concentric = value;
  19602. }
  19603. // in case we used the `concentric` in style
  19604. nodes.updateStyle();
  19605. // calculate max size now based on potentially updated mappers
  19606. for (var _i = 0; _i < nodes.length; _i++) {
  19607. var _node = nodes[_i];
  19608. var nbb = _node.layoutDimensions(options);
  19609. maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);
  19610. }
  19611. // sort node values in descreasing order
  19612. nodeValues.sort(function (a, b) {
  19613. return b.value - a.value;
  19614. });
  19615. var levelWidth = options.levelWidth(nodes);
  19616. // put the values into levels
  19617. var levels = [[]];
  19618. var currentLevel = levels[0];
  19619. for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {
  19620. var val = nodeValues[_i2];
  19621. if (currentLevel.length > 0) {
  19622. var diff = Math.abs(currentLevel[0].value - val.value);
  19623. if (diff >= levelWidth) {
  19624. currentLevel = [];
  19625. levels.push(currentLevel);
  19626. }
  19627. }
  19628. currentLevel.push(val);
  19629. }
  19630. // create positions from levels
  19631. var minDist = maxNodeSize + options.minNodeSpacing; // min dist between nodes
  19632. if (!options.avoidOverlap) {
  19633. // then strictly constrain to bb
  19634. var firstLvlHasMulti = levels.length > 0 && levels[0].length > 1;
  19635. var maxR = Math.min(bb.w, bb.h) / 2 - minDist;
  19636. var rStep = maxR / (levels.length + firstLvlHasMulti ? 1 : 0);
  19637. minDist = Math.min(minDist, rStep);
  19638. }
  19639. // find the metrics for each level
  19640. var r = 0;
  19641. for (var _i3 = 0; _i3 < levels.length; _i3++) {
  19642. var level = levels[_i3];
  19643. var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / level.length : options.sweep;
  19644. var dTheta = level.dTheta = sweep / Math.max(1, level.length - 1);
  19645. // calculate the radius
  19646. if (level.length > 1 && options.avoidOverlap) {
  19647. // but only if more than one node (can't overlap)
  19648. var dcos = Math.cos(dTheta) - Math.cos(0);
  19649. var dsin = Math.sin(dTheta) - Math.sin(0);
  19650. var rMin = Math.sqrt(minDist * minDist / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
  19651. r = Math.max(rMin, r);
  19652. }
  19653. level.r = r;
  19654. r += minDist;
  19655. }
  19656. if (options.equidistant) {
  19657. var rDeltaMax = 0;
  19658. var _r = 0;
  19659. for (var _i4 = 0; _i4 < levels.length; _i4++) {
  19660. var _level = levels[_i4];
  19661. var rDelta = _level.r - _r;
  19662. rDeltaMax = Math.max(rDeltaMax, rDelta);
  19663. }
  19664. _r = 0;
  19665. for (var _i5 = 0; _i5 < levels.length; _i5++) {
  19666. var _level2 = levels[_i5];
  19667. if (_i5 === 0) {
  19668. _r = _level2.r;
  19669. }
  19670. _level2.r = _r;
  19671. _r += rDeltaMax;
  19672. }
  19673. }
  19674. // calculate the node positions
  19675. var pos = {}; // id => position
  19676. for (var _i6 = 0; _i6 < levels.length; _i6++) {
  19677. var _level3 = levels[_i6];
  19678. var _dTheta = _level3.dTheta;
  19679. var _r2 = _level3.r;
  19680. for (var j = 0; j < _level3.length; j++) {
  19681. var _val = _level3[j];
  19682. var theta = options.startAngle + (clockwise ? 1 : -1) * _dTheta * j;
  19683. var p = {
  19684. x: center.x + _r2 * Math.cos(theta),
  19685. y: center.y + _r2 * Math.sin(theta)
  19686. };
  19687. pos[_val.node.id()] = p;
  19688. }
  19689. }
  19690. // position the nodes
  19691. eles.nodes().layoutPositions(this, options, function (ele) {
  19692. var id = ele.id();
  19693. return pos[id];
  19694. });
  19695. return this; // chaining
  19696. };
  19697. /*
  19698. The CoSE layout was written by Gerardo Huck.
  19699. https://www.linkedin.com/in/gerardohuck/
  19700. Based on the following article:
  19701. http://dl.acm.org/citation.cfm?id=1498047
  19702. Modifications tracked on Github.
  19703. */
  19704. var DEBUG;
  19705. /**
  19706. * @brief : default layout options
  19707. */
  19708. var defaults$4 = {
  19709. // Called on `layoutready`
  19710. ready: function ready() {},
  19711. // Called on `layoutstop`
  19712. stop: function stop() {},
  19713. // Whether to animate while running the layout
  19714. // true : Animate continuously as the layout is running
  19715. // false : Just show the end result
  19716. // 'end' : Animate with the end result, from the initial positions to the end positions
  19717. animate: true,
  19718. // Easing of the animation for animate:'end'
  19719. animationEasing: undefined,
  19720. // The duration of the animation for animate:'end'
  19721. animationDuration: undefined,
  19722. // A function that determines whether the node should be animated
  19723. // All nodes animated by default on animate enabled
  19724. // Non-animated nodes are positioned immediately when the layout starts
  19725. animateFilter: function animateFilter(node, i) {
  19726. return true;
  19727. },
  19728. // The layout animates only after this many milliseconds for animate:true
  19729. // (prevents flashing on fast runs)
  19730. animationThreshold: 250,
  19731. // Number of iterations between consecutive screen positions update
  19732. refresh: 20,
  19733. // Whether to fit the network view after when done
  19734. fit: true,
  19735. // Padding on fit
  19736. padding: 30,
  19737. // Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19738. boundingBox: undefined,
  19739. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19740. nodeDimensionsIncludeLabels: false,
  19741. // Randomize the initial positions of the nodes (true) or use existing positions (false)
  19742. randomize: false,
  19743. // Extra spacing between components in non-compound graphs
  19744. componentSpacing: 40,
  19745. // Node repulsion (non overlapping) multiplier
  19746. nodeRepulsion: function nodeRepulsion(node) {
  19747. return 2048;
  19748. },
  19749. // Node repulsion (overlapping) multiplier
  19750. nodeOverlap: 4,
  19751. // Ideal edge (non nested) length
  19752. idealEdgeLength: function idealEdgeLength(edge) {
  19753. return 32;
  19754. },
  19755. // Divisor to compute edge forces
  19756. edgeElasticity: function edgeElasticity(edge) {
  19757. return 32;
  19758. },
  19759. // Nesting factor (multiplier) to compute ideal edge length for nested edges
  19760. nestingFactor: 1.2,
  19761. // Gravity force (constant)
  19762. gravity: 1,
  19763. // Maximum number of iterations to perform
  19764. numIter: 1000,
  19765. // Initial temperature (maximum node displacement)
  19766. initialTemp: 1000,
  19767. // Cooling factor (how the temperature is reduced between consecutive iterations
  19768. coolingFactor: 0.99,
  19769. // Lower temperature threshold (below this point the layout will end)
  19770. minTemp: 1.0
  19771. };
  19772. /**
  19773. * @brief : constructor
  19774. * @arg options : object containing layout options
  19775. */
  19776. function CoseLayout(options) {
  19777. this.options = extend({}, defaults$4, options);
  19778. this.options.layout = this;
  19779. // Exclude any edge that has a source or target node that is not in the set of passed-in nodes
  19780. var nodes = this.options.eles.nodes();
  19781. var edges = this.options.eles.edges();
  19782. var notEdges = edges.filter(function (e) {
  19783. var sourceId = e.source().data('id');
  19784. var targetId = e.target().data('id');
  19785. var hasSource = nodes.some(function (n) {
  19786. return n.data('id') === sourceId;
  19787. });
  19788. var hasTarget = nodes.some(function (n) {
  19789. return n.data('id') === targetId;
  19790. });
  19791. return !hasSource || !hasTarget;
  19792. });
  19793. this.options.eles = this.options.eles.not(notEdges);
  19794. }
  19795. /**
  19796. * @brief : runs the layout
  19797. */
  19798. CoseLayout.prototype.run = function () {
  19799. var options = this.options;
  19800. var cy = options.cy;
  19801. var layout = this;
  19802. layout.stopped = false;
  19803. if (options.animate === true || options.animate === false) {
  19804. layout.emit({
  19805. type: 'layoutstart',
  19806. layout: layout
  19807. });
  19808. }
  19809. // Set DEBUG - Global variable
  19810. if (true === options.debug) {
  19811. DEBUG = true;
  19812. } else {
  19813. DEBUG = false;
  19814. }
  19815. // Initialize layout info
  19816. var layoutInfo = createLayoutInfo(cy, layout, options);
  19817. // Show LayoutInfo contents if debugging
  19818. if (DEBUG) {
  19819. printLayoutInfo(layoutInfo);
  19820. }
  19821. // If required, randomize node positions
  19822. if (options.randomize) {
  19823. randomizePositions(layoutInfo);
  19824. }
  19825. var startTime = performanceNow();
  19826. var refresh = function refresh() {
  19827. refreshPositions(layoutInfo, cy, options);
  19828. // Fit the graph if necessary
  19829. if (true === options.fit) {
  19830. cy.fit(options.padding);
  19831. }
  19832. };
  19833. var mainLoop = function mainLoop(i) {
  19834. if (layout.stopped || i >= options.numIter) {
  19835. // logDebug("Layout manually stopped. Stopping computation in step " + i);
  19836. return false;
  19837. }
  19838. // Do one step in the phisical simulation
  19839. step(layoutInfo, options);
  19840. // Update temperature
  19841. layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;
  19842. // logDebug("New temperature: " + layoutInfo.temperature);
  19843. if (layoutInfo.temperature < options.minTemp) {
  19844. // logDebug("Temperature drop below minimum threshold. Stopping computation in step " + i);
  19845. return false;
  19846. }
  19847. return true;
  19848. };
  19849. var done = function done() {
  19850. if (options.animate === true || options.animate === false) {
  19851. refresh();
  19852. // Layout has finished
  19853. layout.one('layoutstop', options.stop);
  19854. layout.emit({
  19855. type: 'layoutstop',
  19856. layout: layout
  19857. });
  19858. } else {
  19859. var nodes = options.eles.nodes();
  19860. var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  19861. nodes.layoutPositions(layout, options, getScaledPos);
  19862. }
  19863. };
  19864. var i = 0;
  19865. var loopRet = true;
  19866. if (options.animate === true) {
  19867. var _frame = function frame() {
  19868. var f = 0;
  19869. while (loopRet && f < options.refresh) {
  19870. loopRet = mainLoop(i);
  19871. i++;
  19872. f++;
  19873. }
  19874. if (!loopRet) {
  19875. // it's done
  19876. separateComponents(layoutInfo, options);
  19877. done();
  19878. } else {
  19879. var now = performanceNow();
  19880. if (now - startTime >= options.animationThreshold) {
  19881. refresh();
  19882. }
  19883. requestAnimationFrame(_frame);
  19884. }
  19885. };
  19886. _frame();
  19887. } else {
  19888. while (loopRet) {
  19889. loopRet = mainLoop(i);
  19890. i++;
  19891. }
  19892. separateComponents(layoutInfo, options);
  19893. done();
  19894. }
  19895. return this; // chaining
  19896. };
  19897. /**
  19898. * @brief : called on continuous layouts to stop them before they finish
  19899. */
  19900. CoseLayout.prototype.stop = function () {
  19901. this.stopped = true;
  19902. if (this.thread) {
  19903. this.thread.stop();
  19904. }
  19905. this.emit('layoutstop');
  19906. return this; // chaining
  19907. };
  19908. CoseLayout.prototype.destroy = function () {
  19909. if (this.thread) {
  19910. this.thread.stop();
  19911. }
  19912. return this; // chaining
  19913. };
  19914. /**
  19915. * @brief : Creates an object which is contains all the data
  19916. * used in the layout process
  19917. * @arg cy : cytoscape.js object
  19918. * @return : layoutInfo object initialized
  19919. */
  19920. var createLayoutInfo = function createLayoutInfo(cy, layout, options) {
  19921. // Shortcut
  19922. var edges = options.eles.edges();
  19923. var nodes = options.eles.nodes();
  19924. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19925. x1: 0,
  19926. y1: 0,
  19927. w: cy.width(),
  19928. h: cy.height()
  19929. });
  19930. var layoutInfo = {
  19931. isCompound: cy.hasCompoundNodes(),
  19932. layoutNodes: [],
  19933. idToIndex: {},
  19934. nodeSize: nodes.size(),
  19935. graphSet: [],
  19936. indexToGraph: [],
  19937. layoutEdges: [],
  19938. edgeSize: edges.size(),
  19939. temperature: options.initialTemp,
  19940. clientWidth: bb.w,
  19941. clientHeight: bb.h,
  19942. boundingBox: bb
  19943. };
  19944. var components = options.eles.components();
  19945. var id2cmptId = {};
  19946. for (var i = 0; i < components.length; i++) {
  19947. var component = components[i];
  19948. for (var j = 0; j < component.length; j++) {
  19949. var node = component[j];
  19950. id2cmptId[node.id()] = i;
  19951. }
  19952. }
  19953. // Iterate over all nodes, creating layout nodes
  19954. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  19955. var n = nodes[i];
  19956. var nbb = n.layoutDimensions(options);
  19957. var tempNode = {};
  19958. tempNode.isLocked = n.locked();
  19959. tempNode.id = n.data('id');
  19960. tempNode.parentId = n.data('parent');
  19961. tempNode.cmptId = id2cmptId[n.id()];
  19962. tempNode.children = [];
  19963. tempNode.positionX = n.position('x');
  19964. tempNode.positionY = n.position('y');
  19965. tempNode.offsetX = 0;
  19966. tempNode.offsetY = 0;
  19967. tempNode.height = nbb.w;
  19968. tempNode.width = nbb.h;
  19969. tempNode.maxX = tempNode.positionX + tempNode.width / 2;
  19970. tempNode.minX = tempNode.positionX - tempNode.width / 2;
  19971. tempNode.maxY = tempNode.positionY + tempNode.height / 2;
  19972. tempNode.minY = tempNode.positionY - tempNode.height / 2;
  19973. tempNode.padLeft = parseFloat(n.style('padding'));
  19974. tempNode.padRight = parseFloat(n.style('padding'));
  19975. tempNode.padTop = parseFloat(n.style('padding'));
  19976. tempNode.padBottom = parseFloat(n.style('padding'));
  19977. // forces
  19978. tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion;
  19979. // Add new node
  19980. layoutInfo.layoutNodes.push(tempNode);
  19981. // Add entry to id-index map
  19982. layoutInfo.idToIndex[tempNode.id] = i;
  19983. }
  19984. // Inline implementation of a queue, used for traversing the graph in BFS order
  19985. var queue = [];
  19986. var start = 0; // Points to the start the queue
  19987. var end = -1; // Points to the end of the queue
  19988. var tempGraph = [];
  19989. // Second pass to add child information and
  19990. // initialize queue for hierarchical traversal
  19991. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  19992. var n = layoutInfo.layoutNodes[i];
  19993. var p_id = n.parentId;
  19994. // Check if node n has a parent node
  19995. if (null != p_id) {
  19996. // Add node Id to parent's list of children
  19997. layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);
  19998. } else {
  19999. // If a node doesn't have a parent, then it's in the root graph
  20000. queue[++end] = n.id;
  20001. tempGraph.push(n.id);
  20002. }
  20003. }
  20004. // Add root graph to graphSet
  20005. layoutInfo.graphSet.push(tempGraph);
  20006. // Traverse the graph, level by level,
  20007. while (start <= end) {
  20008. // Get the node to visit and remove it from queue
  20009. var node_id = queue[start++];
  20010. var node_ix = layoutInfo.idToIndex[node_id];
  20011. var node = layoutInfo.layoutNodes[node_ix];
  20012. var children = node.children;
  20013. if (children.length > 0) {
  20014. // Add children nodes as a new graph to graph set
  20015. layoutInfo.graphSet.push(children);
  20016. // Add children to que queue to be visited
  20017. for (var i = 0; i < children.length; i++) {
  20018. queue[++end] = children[i];
  20019. }
  20020. }
  20021. }
  20022. // Create indexToGraph map
  20023. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20024. var graph = layoutInfo.graphSet[i];
  20025. for (var j = 0; j < graph.length; j++) {
  20026. var index = layoutInfo.idToIndex[graph[j]];
  20027. layoutInfo.indexToGraph[index] = i;
  20028. }
  20029. }
  20030. // Iterate over all edges, creating Layout Edges
  20031. for (var i = 0; i < layoutInfo.edgeSize; i++) {
  20032. var e = edges[i];
  20033. var tempEdge = {};
  20034. tempEdge.id = e.data('id');
  20035. tempEdge.sourceId = e.data('source');
  20036. tempEdge.targetId = e.data('target');
  20037. // Compute ideal length
  20038. var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;
  20039. var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity;
  20040. // Check if it's an inter graph edge
  20041. var sourceIx = layoutInfo.idToIndex[tempEdge.sourceId];
  20042. var targetIx = layoutInfo.idToIndex[tempEdge.targetId];
  20043. var sourceGraph = layoutInfo.indexToGraph[sourceIx];
  20044. var targetGraph = layoutInfo.indexToGraph[targetIx];
  20045. if (sourceGraph != targetGraph) {
  20046. // Find lowest common graph ancestor
  20047. var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo);
  20048. // Compute sum of node depths, relative to lca graph
  20049. var lcaGraph = layoutInfo.graphSet[lca];
  20050. var depth = 0;
  20051. // Source depth
  20052. var tempNode = layoutInfo.layoutNodes[sourceIx];
  20053. while (-1 === lcaGraph.indexOf(tempNode.id)) {
  20054. tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
  20055. depth++;
  20056. }
  20057. // Target depth
  20058. tempNode = layoutInfo.layoutNodes[targetIx];
  20059. while (-1 === lcaGraph.indexOf(tempNode.id)) {
  20060. tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
  20061. depth++;
  20062. }
  20063. // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +
  20064. // ". Index: " + lca + " Contents: " + lcaGraph.toString() +
  20065. // ". Depth: " + depth);
  20066. // Update idealLength
  20067. idealLength *= depth * options.nestingFactor;
  20068. }
  20069. tempEdge.idealLength = idealLength;
  20070. tempEdge.elasticity = elasticity;
  20071. layoutInfo.layoutEdges.push(tempEdge);
  20072. }
  20073. // Finally, return layoutInfo object
  20074. return layoutInfo;
  20075. };
  20076. /**
  20077. * @brief : This function finds the index of the lowest common
  20078. * graph ancestor between 2 nodes in the subtree
  20079. * (from the graph hierarchy induced tree) whose
  20080. * root is graphIx
  20081. *
  20082. * @arg node1: node1's ID
  20083. * @arg node2: node2's ID
  20084. * @arg layoutInfo: layoutInfo object
  20085. *
  20086. */
  20087. var findLCA = function findLCA(node1, node2, layoutInfo) {
  20088. // Find their common ancester, starting from the root graph
  20089. var res = _findLCA_aux(node1, node2, 0, layoutInfo);
  20090. if (2 > res.count) {
  20091. // If aux function couldn't find the common ancester,
  20092. // then it is the root graph
  20093. return 0;
  20094. } else {
  20095. return res.graph;
  20096. }
  20097. };
  20098. /**
  20099. * @brief : Auxiliary function used for LCA computation
  20100. *
  20101. * @arg node1 : node1's ID
  20102. * @arg node2 : node2's ID
  20103. * @arg graphIx : subgraph index
  20104. * @arg layoutInfo : layoutInfo object
  20105. *
  20106. * @return : object of the form {count: X, graph: Y}, where:
  20107. * X is the number of ancestors (max: 2) found in
  20108. * graphIx (and it's subgraphs),
  20109. * Y is the graph index of the lowest graph containing
  20110. * all X nodes
  20111. */
  20112. var _findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {
  20113. var graph = layoutInfo.graphSet[graphIx];
  20114. // If both nodes belongs to graphIx
  20115. if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {
  20116. return {
  20117. count: 2,
  20118. graph: graphIx
  20119. };
  20120. }
  20121. // Make recursive calls for all subgraphs
  20122. var c = 0;
  20123. for (var i = 0; i < graph.length; i++) {
  20124. var nodeId = graph[i];
  20125. var nodeIx = layoutInfo.idToIndex[nodeId];
  20126. var children = layoutInfo.layoutNodes[nodeIx].children;
  20127. // If the node has no child, skip it
  20128. if (0 === children.length) {
  20129. continue;
  20130. }
  20131. var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];
  20132. var result = _findLCA_aux(node1, node2, childGraphIx, layoutInfo);
  20133. if (0 === result.count) {
  20134. // Neither node1 nor node2 are present in this subgraph
  20135. continue;
  20136. } else if (1 === result.count) {
  20137. // One of (node1, node2) is present in this subgraph
  20138. c++;
  20139. if (2 === c) {
  20140. // We've already found both nodes, no need to keep searching
  20141. break;
  20142. }
  20143. } else {
  20144. // Both nodes are present in this subgraph
  20145. return result;
  20146. }
  20147. }
  20148. return {
  20149. count: c,
  20150. graph: graphIx
  20151. };
  20152. };
  20153. /**
  20154. * @brief: printsLayoutInfo into js console
  20155. * Only used for debbuging
  20156. */
  20157. var printLayoutInfo;
  20158. /**
  20159. * @brief : Randomizes the position of all nodes
  20160. */
  20161. var randomizePositions = function randomizePositions(layoutInfo, cy) {
  20162. var width = layoutInfo.clientWidth;
  20163. var height = layoutInfo.clientHeight;
  20164. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20165. var n = layoutInfo.layoutNodes[i];
  20166. // No need to randomize compound nodes or locked nodes
  20167. if (0 === n.children.length && !n.isLocked) {
  20168. n.positionX = Math.random() * width;
  20169. n.positionY = Math.random() * height;
  20170. }
  20171. }
  20172. };
  20173. var getScaleInBoundsFn = function getScaleInBoundsFn(layoutInfo, options, nodes) {
  20174. var bb = layoutInfo.boundingBox;
  20175. var coseBB = {
  20176. x1: Infinity,
  20177. x2: -Infinity,
  20178. y1: Infinity,
  20179. y2: -Infinity
  20180. };
  20181. if (options.boundingBox) {
  20182. nodes.forEach(function (node) {
  20183. var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[node.data('id')]];
  20184. coseBB.x1 = Math.min(coseBB.x1, lnode.positionX);
  20185. coseBB.x2 = Math.max(coseBB.x2, lnode.positionX);
  20186. coseBB.y1 = Math.min(coseBB.y1, lnode.positionY);
  20187. coseBB.y2 = Math.max(coseBB.y2, lnode.positionY);
  20188. });
  20189. coseBB.w = coseBB.x2 - coseBB.x1;
  20190. coseBB.h = coseBB.y2 - coseBB.y1;
  20191. }
  20192. return function (ele, i) {
  20193. var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];
  20194. if (options.boundingBox) {
  20195. // then add extra bounding box constraint
  20196. // Handle single node case where coseBB.w or coseBB.h is 0
  20197. var pctX = coseBB.w === 0 ? 0.5 : (lnode.positionX - coseBB.x1) / coseBB.w;
  20198. var pctY = coseBB.h === 0 ? 0.5 : (lnode.positionY - coseBB.y1) / coseBB.h;
  20199. return {
  20200. x: bb.x1 + pctX * bb.w,
  20201. y: bb.y1 + pctY * bb.h
  20202. };
  20203. } else {
  20204. return {
  20205. x: lnode.positionX,
  20206. y: lnode.positionY
  20207. };
  20208. }
  20209. };
  20210. };
  20211. /**
  20212. * @brief : Updates the positions of nodes in the network
  20213. * @arg layoutInfo : LayoutInfo object
  20214. * @arg cy : Cytoscape object
  20215. * @arg options : Layout options
  20216. */
  20217. var refreshPositions = function refreshPositions(layoutInfo, cy, options) {
  20218. // var s = 'Refreshing positions';
  20219. // logDebug(s);
  20220. var layout = options.layout;
  20221. var nodes = options.eles.nodes();
  20222. var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  20223. nodes.positions(getScaledPos);
  20224. // Trigger layoutReady only on first call
  20225. if (true !== layoutInfo.ready) {
  20226. // s = 'Triggering layoutready';
  20227. // logDebug(s);
  20228. layoutInfo.ready = true;
  20229. layout.one('layoutready', options.ready);
  20230. layout.emit({
  20231. type: 'layoutready',
  20232. layout: this
  20233. });
  20234. }
  20235. };
  20236. /**
  20237. * @brief : Logs a debug message in JS console, if DEBUG is ON
  20238. */
  20239. // var logDebug = function(text) {
  20240. // if (DEBUG) {
  20241. // console.debug(text);
  20242. // }
  20243. // };
  20244. /**
  20245. * @brief : Performs one iteration of the physical simulation
  20246. * @arg layoutInfo : LayoutInfo object already initialized
  20247. * @arg cy : Cytoscape object
  20248. * @arg options : Layout options
  20249. */
  20250. var step = function step(layoutInfo, options, _step) {
  20251. // var s = "\n\n###############################";
  20252. // s += "\nSTEP: " + step;
  20253. // s += "\n###############################\n";
  20254. // logDebug(s);
  20255. // Calculate node repulsions
  20256. calculateNodeForces(layoutInfo, options);
  20257. // Calculate edge forces
  20258. calculateEdgeForces(layoutInfo);
  20259. // Calculate gravity forces
  20260. calculateGravityForces(layoutInfo, options);
  20261. // Propagate forces from parent to child
  20262. propagateForces(layoutInfo);
  20263. // Update positions based on calculated forces
  20264. updatePositions(layoutInfo);
  20265. };
  20266. /**
  20267. * @brief : Computes the node repulsion forces
  20268. */
  20269. var calculateNodeForces = function calculateNodeForces(layoutInfo, options) {
  20270. // Go through each of the graphs in graphSet
  20271. // Nodes only repel each other if they belong to the same graph
  20272. // var s = 'calculateNodeForces';
  20273. // logDebug(s);
  20274. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20275. var graph = layoutInfo.graphSet[i];
  20276. var numNodes = graph.length;
  20277. // s = "Set: " + graph.toString();
  20278. // logDebug(s);
  20279. // Now get all the pairs of nodes
  20280. // Only get each pair once, (A, B) = (B, A)
  20281. for (var j = 0; j < numNodes; j++) {
  20282. var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
  20283. for (var k = j + 1; k < numNodes; k++) {
  20284. var node2 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[k]]];
  20285. nodeRepulsion(node1, node2, layoutInfo, options);
  20286. }
  20287. }
  20288. }
  20289. };
  20290. var randomDistance = function randomDistance(max) {
  20291. return -1 + 2 * max * Math.random();
  20292. };
  20293. /**
  20294. * @brief : Compute the node repulsion forces between a pair of nodes
  20295. */
  20296. var nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {
  20297. // var s = "Node repulsion. Node1: " + node1.id + " Node2: " + node2.id;
  20298. var cmptId1 = node1.cmptId;
  20299. var cmptId2 = node2.cmptId;
  20300. if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {
  20301. return;
  20302. }
  20303. // Get direction of line connecting both node centers
  20304. var directionX = node2.positionX - node1.positionX;
  20305. var directionY = node2.positionY - node1.positionY;
  20306. var maxRandDist = 1;
  20307. // s += "\ndirectionX: " + directionX + ", directionY: " + directionY;
  20308. // If both centers are the same, apply a random force
  20309. if (0 === directionX && 0 === directionY) {
  20310. directionX = randomDistance(maxRandDist);
  20311. directionY = randomDistance(maxRandDist);
  20312. }
  20313. var overlap = nodesOverlap(node1, node2, directionX, directionY);
  20314. if (overlap > 0) {
  20315. // s += "\nNodes DO overlap.";
  20316. // s += "\nOverlap: " + overlap;
  20317. // If nodes overlap, repulsion force is proportional
  20318. // to the overlap
  20319. var force = options.nodeOverlap * overlap;
  20320. // Compute the module and components of the force vector
  20321. var distance = Math.sqrt(directionX * directionX + directionY * directionY);
  20322. // s += "\nDistance: " + distance;
  20323. var forceX = force * directionX / distance;
  20324. var forceY = force * directionY / distance;
  20325. } else {
  20326. // s += "\nNodes do NOT overlap.";
  20327. // If there's no overlap, force is inversely proportional
  20328. // to squared distance
  20329. // Get clipping points for both nodes
  20330. var point1 = findClippingPoint(node1, directionX, directionY);
  20331. var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY);
  20332. // Use clipping points to compute distance
  20333. var distanceX = point2.x - point1.x;
  20334. var distanceY = point2.y - point1.y;
  20335. var distanceSqr = distanceX * distanceX + distanceY * distanceY;
  20336. var distance = Math.sqrt(distanceSqr);
  20337. // s += "\nDistance: " + distance;
  20338. // Compute the module and components of the force vector
  20339. var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;
  20340. var forceX = force * distanceX / distance;
  20341. var forceY = force * distanceY / distance;
  20342. }
  20343. // Apply force
  20344. if (!node1.isLocked) {
  20345. node1.offsetX -= forceX;
  20346. node1.offsetY -= forceY;
  20347. }
  20348. if (!node2.isLocked) {
  20349. node2.offsetX += forceX;
  20350. node2.offsetY += forceY;
  20351. }
  20352. // s += "\nForceX: " + forceX + " ForceY: " + forceY;
  20353. // logDebug(s);
  20354. return;
  20355. };
  20356. /**
  20357. * @brief : Determines whether two nodes overlap or not
  20358. * @return : Amount of overlapping (0 => no overlap)
  20359. */
  20360. var nodesOverlap = function nodesOverlap(node1, node2, dX, dY) {
  20361. if (dX > 0) {
  20362. var overlapX = node1.maxX - node2.minX;
  20363. } else {
  20364. var overlapX = node2.maxX - node1.minX;
  20365. }
  20366. if (dY > 0) {
  20367. var overlapY = node1.maxY - node2.minY;
  20368. } else {
  20369. var overlapY = node2.maxY - node1.minY;
  20370. }
  20371. if (overlapX >= 0 && overlapY >= 0) {
  20372. return Math.sqrt(overlapX * overlapX + overlapY * overlapY);
  20373. } else {
  20374. return 0;
  20375. }
  20376. };
  20377. /**
  20378. * @brief : Finds the point in which an edge (direction dX, dY) intersects
  20379. * the rectangular bounding box of it's source/target node
  20380. */
  20381. var findClippingPoint = function findClippingPoint(node, dX, dY) {
  20382. // Shorcuts
  20383. var X = node.positionX;
  20384. var Y = node.positionY;
  20385. var H = node.height || 1;
  20386. var W = node.width || 1;
  20387. var dirSlope = dY / dX;
  20388. var nodeSlope = H / W;
  20389. // var s = 'Computing clipping point of node ' + node.id +
  20390. // " . Height: " + H + ", Width: " + W +
  20391. // "\nDirection " + dX + ", " + dY;
  20392. //
  20393. // Compute intersection
  20394. var res = {};
  20395. // Case: Vertical direction (up)
  20396. if (0 === dX && 0 < dY) {
  20397. res.x = X;
  20398. // s += "\nUp direction";
  20399. res.y = Y + H / 2;
  20400. return res;
  20401. }
  20402. // Case: Vertical direction (down)
  20403. if (0 === dX && 0 > dY) {
  20404. res.x = X;
  20405. res.y = Y + H / 2;
  20406. // s += "\nDown direction";
  20407. return res;
  20408. }
  20409. // Case: Intersects the right border
  20410. if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
  20411. res.x = X + W / 2;
  20412. res.y = Y + W * dY / 2 / dX;
  20413. // s += "\nRightborder";
  20414. return res;
  20415. }
  20416. // Case: Intersects the left border
  20417. if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
  20418. res.x = X - W / 2;
  20419. res.y = Y - W * dY / 2 / dX;
  20420. // s += "\nLeftborder";
  20421. return res;
  20422. }
  20423. // Case: Intersects the top border
  20424. if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
  20425. res.x = X + H * dX / 2 / dY;
  20426. res.y = Y + H / 2;
  20427. // s += "\nTop border";
  20428. return res;
  20429. }
  20430. // Case: Intersects the bottom border
  20431. if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
  20432. res.x = X - H * dX / 2 / dY;
  20433. res.y = Y - H / 2;
  20434. // s += "\nBottom border";
  20435. return res;
  20436. }
  20437. // s += "\nClipping point found at " + res.x + ", " + res.y;
  20438. // logDebug(s);
  20439. return res;
  20440. };
  20441. /**
  20442. * @brief : Calculates all edge forces
  20443. */
  20444. var calculateEdgeForces = function calculateEdgeForces(layoutInfo, options) {
  20445. // Iterate over all edges
  20446. for (var i = 0; i < layoutInfo.edgeSize; i++) {
  20447. // Get edge, source & target nodes
  20448. var edge = layoutInfo.layoutEdges[i];
  20449. var sourceIx = layoutInfo.idToIndex[edge.sourceId];
  20450. var source = layoutInfo.layoutNodes[sourceIx];
  20451. var targetIx = layoutInfo.idToIndex[edge.targetId];
  20452. var target = layoutInfo.layoutNodes[targetIx];
  20453. // Get direction of line connecting both node centers
  20454. var directionX = target.positionX - source.positionX;
  20455. var directionY = target.positionY - source.positionY;
  20456. // If both centers are the same, do nothing.
  20457. // A random force has already been applied as node repulsion
  20458. if (0 === directionX && 0 === directionY) {
  20459. continue;
  20460. }
  20461. // Get clipping points for both nodes
  20462. var point1 = findClippingPoint(source, directionX, directionY);
  20463. var point2 = findClippingPoint(target, -1 * directionX, -1 * directionY);
  20464. var lx = point2.x - point1.x;
  20465. var ly = point2.y - point1.y;
  20466. var l = Math.sqrt(lx * lx + ly * ly);
  20467. var force = Math.pow(edge.idealLength - l, 2) / edge.elasticity;
  20468. if (0 !== l) {
  20469. var forceX = force * lx / l;
  20470. var forceY = force * ly / l;
  20471. } else {
  20472. var forceX = 0;
  20473. var forceY = 0;
  20474. }
  20475. // Add this force to target and source nodes
  20476. if (!source.isLocked) {
  20477. source.offsetX += forceX;
  20478. source.offsetY += forceY;
  20479. }
  20480. if (!target.isLocked) {
  20481. target.offsetX -= forceX;
  20482. target.offsetY -= forceY;
  20483. }
  20484. // var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;
  20485. // s += "\nDistance: " + l + " Force: (" + forceX + ", " + forceY + ")";
  20486. // logDebug(s);
  20487. }
  20488. };
  20489. /**
  20490. * @brief : Computes gravity forces for all nodes
  20491. */
  20492. var calculateGravityForces = function calculateGravityForces(layoutInfo, options) {
  20493. if (options.gravity === 0) {
  20494. return;
  20495. }
  20496. var distThreshold = 1;
  20497. // var s = 'calculateGravityForces';
  20498. // logDebug(s);
  20499. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20500. var graph = layoutInfo.graphSet[i];
  20501. var numNodes = graph.length;
  20502. // s = "Set: " + graph.toString();
  20503. // logDebug(s);
  20504. // Compute graph center
  20505. if (0 === i) {
  20506. var centerX = layoutInfo.clientHeight / 2;
  20507. var centerY = layoutInfo.clientWidth / 2;
  20508. } else {
  20509. // Get Parent node for this graph, and use its position as center
  20510. var temp = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[0]]];
  20511. var parent = layoutInfo.layoutNodes[layoutInfo.idToIndex[temp.parentId]];
  20512. var centerX = parent.positionX;
  20513. var centerY = parent.positionY;
  20514. }
  20515. // s = "Center found at: " + centerX + ", " + centerY;
  20516. // logDebug(s);
  20517. // Apply force to all nodes in graph
  20518. for (var j = 0; j < numNodes; j++) {
  20519. var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
  20520. // s = "Node: " + node.id;
  20521. if (node.isLocked) {
  20522. continue;
  20523. }
  20524. var dx = centerX - node.positionX;
  20525. var dy = centerY - node.positionY;
  20526. var d = Math.sqrt(dx * dx + dy * dy);
  20527. if (d > distThreshold) {
  20528. var fx = options.gravity * dx / d;
  20529. var fy = options.gravity * dy / d;
  20530. node.offsetX += fx;
  20531. node.offsetY += fy;
  20532. // s += ": Applied force: " + fx + ", " + fy;
  20533. }
  20534. // logDebug(s);
  20535. }
  20536. }
  20537. };
  20538. /**
  20539. * @brief : This function propagates the existing offsets from
  20540. * parent nodes to its descendents.
  20541. * @arg layoutInfo : layoutInfo Object
  20542. * @arg cy : cytoscape Object
  20543. * @arg options : Layout options
  20544. */
  20545. var propagateForces = function propagateForces(layoutInfo, options) {
  20546. // Inline implementation of a queue, used for traversing the graph in BFS order
  20547. var queue = [];
  20548. var start = 0; // Points to the start the queue
  20549. var end = -1; // Points to the end of the queue
  20550. // logDebug('propagateForces');
  20551. // Start by visiting the nodes in the root graph
  20552. queue.push.apply(queue, layoutInfo.graphSet[0]);
  20553. end += layoutInfo.graphSet[0].length;
  20554. // Traverse the graph, level by level,
  20555. while (start <= end) {
  20556. // Get the node to visit and remove it from queue
  20557. var nodeId = queue[start++];
  20558. var nodeIndex = layoutInfo.idToIndex[nodeId];
  20559. var node = layoutInfo.layoutNodes[nodeIndex];
  20560. var children = node.children;
  20561. // We only need to process the node if it's compound
  20562. if (0 < children.length && !node.isLocked) {
  20563. var offX = node.offsetX;
  20564. var offY = node.offsetY;
  20565. // var s = "Propagating offset from parent node : " + node.id +
  20566. // ". OffsetX: " + offX + ". OffsetY: " + offY;
  20567. // s += "\n Children: " + children.toString();
  20568. // logDebug(s);
  20569. for (var i = 0; i < children.length; i++) {
  20570. var childNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[children[i]]];
  20571. // Propagate offset
  20572. childNode.offsetX += offX;
  20573. childNode.offsetY += offY;
  20574. // Add children to queue to be visited
  20575. queue[++end] = children[i];
  20576. }
  20577. // Reset parent offsets
  20578. node.offsetX = 0;
  20579. node.offsetY = 0;
  20580. }
  20581. }
  20582. };
  20583. /**
  20584. * @brief : Updates the layout model positions, based on
  20585. * the accumulated forces
  20586. */
  20587. var updatePositions = function updatePositions(layoutInfo, options) {
  20588. // var s = 'Updating positions';
  20589. // logDebug(s);
  20590. // Reset boundaries for compound nodes
  20591. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20592. var n = layoutInfo.layoutNodes[i];
  20593. if (0 < n.children.length) {
  20594. // logDebug("Resetting boundaries of compound node: " + n.id);
  20595. n.maxX = undefined;
  20596. n.minX = undefined;
  20597. n.maxY = undefined;
  20598. n.minY = undefined;
  20599. }
  20600. }
  20601. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20602. var n = layoutInfo.layoutNodes[i];
  20603. if (0 < n.children.length || n.isLocked) {
  20604. // No need to set compound or locked node position
  20605. // logDebug("Skipping position update of node: " + n.id);
  20606. continue;
  20607. }
  20608. // s = "Node: " + n.id + " Previous position: (" +
  20609. // n.positionX + ", " + n.positionY + ").";
  20610. // Limit displacement in order to improve stability
  20611. var tempForce = limitForce(n.offsetX, n.offsetY, layoutInfo.temperature);
  20612. n.positionX += tempForce.x;
  20613. n.positionY += tempForce.y;
  20614. n.offsetX = 0;
  20615. n.offsetY = 0;
  20616. n.minX = n.positionX - n.width;
  20617. n.maxX = n.positionX + n.width;
  20618. n.minY = n.positionY - n.height;
  20619. n.maxY = n.positionY + n.height;
  20620. // s += " New Position: (" + n.positionX + ", " + n.positionY + ").";
  20621. // logDebug(s);
  20622. // Update ancestry boudaries
  20623. _updateAncestryBoundaries(n, layoutInfo);
  20624. }
  20625. // Update size, position of compund nodes
  20626. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20627. var n = layoutInfo.layoutNodes[i];
  20628. if (0 < n.children.length && !n.isLocked) {
  20629. n.positionX = (n.maxX + n.minX) / 2;
  20630. n.positionY = (n.maxY + n.minY) / 2;
  20631. n.width = n.maxX - n.minX;
  20632. n.height = n.maxY - n.minY;
  20633. // s = "Updating position, size of compound node " + n.id;
  20634. // s += "\nPositionX: " + n.positionX + ", PositionY: " + n.positionY;
  20635. // s += "\nWidth: " + n.width + ", Height: " + n.height;
  20636. // logDebug(s);
  20637. }
  20638. }
  20639. };
  20640. /**
  20641. * @brief : Limits a force (forceX, forceY) to be not
  20642. * greater (in modulo) than max.
  20643. 8 Preserves force direction.
  20644. */
  20645. var limitForce = function limitForce(forceX, forceY, max) {
  20646. // var s = "Limiting force: (" + forceX + ", " + forceY + "). Max: " + max;
  20647. var force = Math.sqrt(forceX * forceX + forceY * forceY);
  20648. if (force > max) {
  20649. var res = {
  20650. x: max * forceX / force,
  20651. y: max * forceY / force
  20652. };
  20653. } else {
  20654. var res = {
  20655. x: forceX,
  20656. y: forceY
  20657. };
  20658. }
  20659. // s += ".\nResult: (" + res.x + ", " + res.y + ")";
  20660. // logDebug(s);
  20661. return res;
  20662. };
  20663. /**
  20664. * @brief : Function used for keeping track of compound node
  20665. * sizes, since they should bound all their subnodes.
  20666. */
  20667. var _updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {
  20668. // var s = "Propagating new position/size of node " + node.id;
  20669. var parentId = node.parentId;
  20670. if (null == parentId) {
  20671. // If there's no parent, we are done
  20672. // s += ". No parent node.";
  20673. // logDebug(s);
  20674. return;
  20675. }
  20676. // Get Parent Node
  20677. var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];
  20678. var flag = false;
  20679. // MaxX
  20680. if (null == p.maxX || node.maxX + p.padRight > p.maxX) {
  20681. p.maxX = node.maxX + p.padRight;
  20682. flag = true;
  20683. // s += "\nNew maxX for parent node " + p.id + ": " + p.maxX;
  20684. }
  20685. // MinX
  20686. if (null == p.minX || node.minX - p.padLeft < p.minX) {
  20687. p.minX = node.minX - p.padLeft;
  20688. flag = true;
  20689. // s += "\nNew minX for parent node " + p.id + ": " + p.minX;
  20690. }
  20691. // MaxY
  20692. if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {
  20693. p.maxY = node.maxY + p.padBottom;
  20694. flag = true;
  20695. // s += "\nNew maxY for parent node " + p.id + ": " + p.maxY;
  20696. }
  20697. // MinY
  20698. if (null == p.minY || node.minY - p.padTop < p.minY) {
  20699. p.minY = node.minY - p.padTop;
  20700. flag = true;
  20701. // s += "\nNew minY for parent node " + p.id + ": " + p.minY;
  20702. }
  20703. // If updated boundaries, propagate changes upward
  20704. if (flag) {
  20705. // logDebug(s);
  20706. return _updateAncestryBoundaries(p, layoutInfo);
  20707. }
  20708. // s += ". No changes in boundaries/position of parent node " + p.id;
  20709. // logDebug(s);
  20710. return;
  20711. };
  20712. var separateComponents = function separateComponents(layoutInfo, options) {
  20713. var nodes = layoutInfo.layoutNodes;
  20714. var components = [];
  20715. for (var i = 0; i < nodes.length; i++) {
  20716. var node = nodes[i];
  20717. var cid = node.cmptId;
  20718. var component = components[cid] = components[cid] || [];
  20719. component.push(node);
  20720. }
  20721. var totalA = 0;
  20722. for (var i = 0; i < components.length; i++) {
  20723. var c = components[i];
  20724. if (!c) {
  20725. continue;
  20726. }
  20727. c.x1 = Infinity;
  20728. c.x2 = -Infinity;
  20729. c.y1 = Infinity;
  20730. c.y2 = -Infinity;
  20731. for (var j = 0; j < c.length; j++) {
  20732. var n = c[j];
  20733. c.x1 = Math.min(c.x1, n.positionX - n.width / 2);
  20734. c.x2 = Math.max(c.x2, n.positionX + n.width / 2);
  20735. c.y1 = Math.min(c.y1, n.positionY - n.height / 2);
  20736. c.y2 = Math.max(c.y2, n.positionY + n.height / 2);
  20737. }
  20738. c.w = c.x2 - c.x1;
  20739. c.h = c.y2 - c.y1;
  20740. totalA += c.w * c.h;
  20741. }
  20742. components.sort(function (c1, c2) {
  20743. return c2.w * c2.h - c1.w * c1.h;
  20744. });
  20745. var x = 0;
  20746. var y = 0;
  20747. var usedW = 0;
  20748. var rowH = 0;
  20749. var maxRowW = Math.sqrt(totalA) * layoutInfo.clientWidth / layoutInfo.clientHeight;
  20750. for (var i = 0; i < components.length; i++) {
  20751. var c = components[i];
  20752. if (!c) {
  20753. continue;
  20754. }
  20755. for (var j = 0; j < c.length; j++) {
  20756. var n = c[j];
  20757. if (!n.isLocked) {
  20758. n.positionX += x - c.x1;
  20759. n.positionY += y - c.y1;
  20760. }
  20761. }
  20762. x += c.w + options.componentSpacing;
  20763. usedW += c.w + options.componentSpacing;
  20764. rowH = Math.max(rowH, c.h);
  20765. if (usedW > maxRowW) {
  20766. y += rowH + options.componentSpacing;
  20767. x = 0;
  20768. usedW = 0;
  20769. rowH = 0;
  20770. }
  20771. }
  20772. };
  20773. var defaults$3 = {
  20774. fit: true,
  20775. // whether to fit the viewport to the graph
  20776. padding: 30,
  20777. // padding used on fit
  20778. boundingBox: undefined,
  20779. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  20780. avoidOverlap: true,
  20781. // prevents node overlap, may overflow boundingBox if not enough space
  20782. avoidOverlapPadding: 10,
  20783. // extra spacing around nodes when avoidOverlap: true
  20784. nodeDimensionsIncludeLabels: false,
  20785. // Excludes the label when calculating node bounding boxes for the layout algorithm
  20786. spacingFactor: undefined,
  20787. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  20788. condense: false,
  20789. // uses all available space on false, uses minimal space on true
  20790. rows: undefined,
  20791. // force num of rows in the grid
  20792. cols: undefined,
  20793. // force num of columns in the grid
  20794. position: function position(node) {},
  20795. // returns { row, col } for element
  20796. sort: undefined,
  20797. // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  20798. animate: false,
  20799. // whether to transition the node positions
  20800. animationDuration: 500,
  20801. // duration of animation in ms if enabled
  20802. animationEasing: undefined,
  20803. // easing of animation if enabled
  20804. animateFilter: function animateFilter(node, i) {
  20805. return true;
  20806. },
  20807. // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts
  20808. ready: undefined,
  20809. // callback on layoutready
  20810. stop: undefined,
  20811. // callback on layoutstop
  20812. transform: function transform(node, position) {
  20813. return position;
  20814. } // transform a given node position. Useful for changing flow direction in discrete layouts
  20815. };
  20816. function GridLayout(options) {
  20817. this.options = extend({}, defaults$3, options);
  20818. }
  20819. GridLayout.prototype.run = function () {
  20820. var params = this.options;
  20821. var options = params;
  20822. var cy = params.cy;
  20823. var eles = options.eles;
  20824. var nodes = eles.nodes().not(':parent');
  20825. if (options.sort) {
  20826. nodes = nodes.sort(options.sort);
  20827. }
  20828. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  20829. x1: 0,
  20830. y1: 0,
  20831. w: cy.width(),
  20832. h: cy.height()
  20833. });
  20834. if (bb.h === 0 || bb.w === 0) {
  20835. eles.nodes().layoutPositions(this, options, function (ele) {
  20836. return {
  20837. x: bb.x1,
  20838. y: bb.y1
  20839. };
  20840. });
  20841. } else {
  20842. // width/height * splits^2 = cells where splits is number of times to split width
  20843. var cells = nodes.size();
  20844. var splits = Math.sqrt(cells * bb.h / bb.w);
  20845. var rows = Math.round(splits);
  20846. var cols = Math.round(bb.w / bb.h * splits);
  20847. var small = function small(val) {
  20848. if (val == null) {
  20849. return Math.min(rows, cols);
  20850. } else {
  20851. var min = Math.min(rows, cols);
  20852. if (min == rows) {
  20853. rows = val;
  20854. } else {
  20855. cols = val;
  20856. }
  20857. }
  20858. };
  20859. var large = function large(val) {
  20860. if (val == null) {
  20861. return Math.max(rows, cols);
  20862. } else {
  20863. var max = Math.max(rows, cols);
  20864. if (max == rows) {
  20865. rows = val;
  20866. } else {
  20867. cols = val;
  20868. }
  20869. }
  20870. };
  20871. var oRows = options.rows;
  20872. var oCols = options.cols != null ? options.cols : options.columns;
  20873. // if rows or columns were set in options, use those values
  20874. if (oRows != null && oCols != null) {
  20875. rows = oRows;
  20876. cols = oCols;
  20877. } else if (oRows != null && oCols == null) {
  20878. rows = oRows;
  20879. cols = Math.ceil(cells / rows);
  20880. } else if (oRows == null && oCols != null) {
  20881. cols = oCols;
  20882. rows = Math.ceil(cells / cols);
  20883. }
  20884. // otherwise use the automatic values and adjust accordingly
  20885. // if rounding was up, see if we can reduce rows or columns
  20886. else if (cols * rows > cells) {
  20887. var sm = small();
  20888. var lg = large();
  20889. // reducing the small side takes away the most cells, so try it first
  20890. if ((sm - 1) * lg >= cells) {
  20891. small(sm - 1);
  20892. } else if ((lg - 1) * sm >= cells) {
  20893. large(lg - 1);
  20894. }
  20895. } else {
  20896. // if rounding was too low, add rows or columns
  20897. while (cols * rows < cells) {
  20898. var _sm = small();
  20899. var _lg = large();
  20900. // try to add to larger side first (adds less in multiplication)
  20901. if ((_lg + 1) * _sm >= cells) {
  20902. large(_lg + 1);
  20903. } else {
  20904. small(_sm + 1);
  20905. }
  20906. }
  20907. }
  20908. var cellWidth = bb.w / cols;
  20909. var cellHeight = bb.h / rows;
  20910. if (options.condense) {
  20911. cellWidth = 0;
  20912. cellHeight = 0;
  20913. }
  20914. if (options.avoidOverlap) {
  20915. for (var i = 0; i < nodes.length; i++) {
  20916. var node = nodes[i];
  20917. var pos = node._private.position;
  20918. if (pos.x == null || pos.y == null) {
  20919. // for bb
  20920. pos.x = 0;
  20921. pos.y = 0;
  20922. }
  20923. var nbb = node.layoutDimensions(options);
  20924. var p = options.avoidOverlapPadding;
  20925. var w = nbb.w + p;
  20926. var h = nbb.h + p;
  20927. cellWidth = Math.max(cellWidth, w);
  20928. cellHeight = Math.max(cellHeight, h);
  20929. }
  20930. }
  20931. var cellUsed = {}; // e.g. 'c-0-2' => true
  20932. var used = function used(row, col) {
  20933. return cellUsed['c-' + row + '-' + col] ? true : false;
  20934. };
  20935. var use = function use(row, col) {
  20936. cellUsed['c-' + row + '-' + col] = true;
  20937. };
  20938. // to keep track of current cell position
  20939. var row = 0;
  20940. var col = 0;
  20941. var moveToNextCell = function moveToNextCell() {
  20942. col++;
  20943. if (col >= cols) {
  20944. col = 0;
  20945. row++;
  20946. }
  20947. };
  20948. // get a cache of all the manual positions
  20949. var id2manPos = {};
  20950. for (var _i = 0; _i < nodes.length; _i++) {
  20951. var _node = nodes[_i];
  20952. var rcPos = options.position(_node);
  20953. if (rcPos && (rcPos.row !== undefined || rcPos.col !== undefined)) {
  20954. // must have at least row or col def'd
  20955. var _pos = {
  20956. row: rcPos.row,
  20957. col: rcPos.col
  20958. };
  20959. if (_pos.col === undefined) {
  20960. // find unused col
  20961. _pos.col = 0;
  20962. while (used(_pos.row, _pos.col)) {
  20963. _pos.col++;
  20964. }
  20965. } else if (_pos.row === undefined) {
  20966. // find unused row
  20967. _pos.row = 0;
  20968. while (used(_pos.row, _pos.col)) {
  20969. _pos.row++;
  20970. }
  20971. }
  20972. id2manPos[_node.id()] = _pos;
  20973. use(_pos.row, _pos.col);
  20974. }
  20975. }
  20976. var getPos = function getPos(element, i) {
  20977. var x, y;
  20978. if (element.locked() || element.isParent()) {
  20979. return false;
  20980. }
  20981. // see if we have a manual position set
  20982. var rcPos = id2manPos[element.id()];
  20983. if (rcPos) {
  20984. x = rcPos.col * cellWidth + cellWidth / 2 + bb.x1;
  20985. y = rcPos.row * cellHeight + cellHeight / 2 + bb.y1;
  20986. } else {
  20987. // otherwise set automatically
  20988. while (used(row, col)) {
  20989. moveToNextCell();
  20990. }
  20991. x = col * cellWidth + cellWidth / 2 + bb.x1;
  20992. y = row * cellHeight + cellHeight / 2 + bb.y1;
  20993. use(row, col);
  20994. moveToNextCell();
  20995. }
  20996. return {
  20997. x: x,
  20998. y: y
  20999. };
  21000. };
  21001. nodes.layoutPositions(this, options, getPos);
  21002. }
  21003. return this; // chaining
  21004. };
  21005. // default layout options
  21006. var defaults$2 = {
  21007. ready: function ready() {},
  21008. // on layoutready
  21009. stop: function stop() {} // on layoutstop
  21010. };
  21011. // constructor
  21012. // options : object containing layout options
  21013. function NullLayout(options) {
  21014. this.options = extend({}, defaults$2, options);
  21015. }
  21016. // runs the layout
  21017. NullLayout.prototype.run = function () {
  21018. var options = this.options;
  21019. var eles = options.eles; // elements to consider in the layout
  21020. var layout = this;
  21021. // cy is automatically populated for us in the constructor
  21022. // (disable eslint for next line as this serves as example layout code to external developers)
  21023. // eslint-disable-next-line no-unused-vars
  21024. options.cy;
  21025. layout.emit('layoutstart');
  21026. // puts all nodes at (0, 0)
  21027. // n.b. most layouts would use layoutPositions(), instead of positions() and manual events
  21028. eles.nodes().positions(function () {
  21029. return {
  21030. x: 0,
  21031. y: 0
  21032. };
  21033. });
  21034. // trigger layoutready when each node has had its position set at least once
  21035. layout.one('layoutready', options.ready);
  21036. layout.emit('layoutready');
  21037. // trigger layoutstop when the layout stops (e.g. finishes)
  21038. layout.one('layoutstop', options.stop);
  21039. layout.emit('layoutstop');
  21040. return this; // chaining
  21041. };
  21042. // called on continuous layouts to stop them before they finish
  21043. NullLayout.prototype.stop = function () {
  21044. return this; // chaining
  21045. };
  21046. var defaults$1 = {
  21047. positions: undefined,
  21048. // map of (node id) => (position obj); or function(node){ return somPos; }
  21049. zoom: undefined,
  21050. // the zoom level to set (prob want fit = false if set)
  21051. pan: undefined,
  21052. // the pan level to set (prob want fit = false if set)
  21053. fit: true,
  21054. // whether to fit to viewport
  21055. padding: 30,
  21056. // padding on fit
  21057. spacingFactor: undefined,
  21058. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  21059. animate: false,
  21060. // whether to transition the node positions
  21061. animationDuration: 500,
  21062. // duration of animation in ms if enabled
  21063. animationEasing: undefined,
  21064. // easing of animation if enabled
  21065. animateFilter: function animateFilter(node, i) {
  21066. return true;
  21067. },
  21068. // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts
  21069. ready: undefined,
  21070. // callback on layoutready
  21071. stop: undefined,
  21072. // callback on layoutstop
  21073. transform: function transform(node, position) {
  21074. return position;
  21075. } // transform a given node position. Useful for changing flow direction in discrete layouts
  21076. };
  21077. function PresetLayout(options) {
  21078. this.options = extend({}, defaults$1, options);
  21079. }
  21080. PresetLayout.prototype.run = function () {
  21081. var options = this.options;
  21082. var eles = options.eles;
  21083. var nodes = eles.nodes();
  21084. var posIsFn = fn$6(options.positions);
  21085. function getPosition(node) {
  21086. if (options.positions == null) {
  21087. return copyPosition(node.position());
  21088. }
  21089. if (posIsFn) {
  21090. return options.positions(node);
  21091. }
  21092. var pos = options.positions[node._private.data.id];
  21093. if (pos == null) {
  21094. return null;
  21095. }
  21096. return pos;
  21097. }
  21098. nodes.layoutPositions(this, options, function (node, i) {
  21099. var position = getPosition(node);
  21100. if (node.locked() || position == null) {
  21101. return false;
  21102. }
  21103. return position;
  21104. });
  21105. return this; // chaining
  21106. };
  21107. var defaults = {
  21108. fit: true,
  21109. // whether to fit to viewport
  21110. padding: 30,
  21111. // fit padding
  21112. boundingBox: undefined,
  21113. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  21114. animate: false,
  21115. // whether to transition the node positions
  21116. animationDuration: 500,
  21117. // duration of animation in ms if enabled
  21118. animationEasing: undefined,
  21119. // easing of animation if enabled
  21120. animateFilter: function animateFilter(node, i) {
  21121. return true;
  21122. },
  21123. // a function that determines whether the node should be animated. All nodes animated by default on animate enabled. Non-animated nodes are positioned immediately when the layout starts
  21124. ready: undefined,
  21125. // callback on layoutready
  21126. stop: undefined,
  21127. // callback on layoutstop
  21128. transform: function transform(node, position) {
  21129. return position;
  21130. } // transform a given node position. Useful for changing flow direction in discrete layouts
  21131. };
  21132. function RandomLayout(options) {
  21133. this.options = extend({}, defaults, options);
  21134. }
  21135. RandomLayout.prototype.run = function () {
  21136. var options = this.options;
  21137. var cy = options.cy;
  21138. var eles = options.eles;
  21139. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  21140. x1: 0,
  21141. y1: 0,
  21142. w: cy.width(),
  21143. h: cy.height()
  21144. });
  21145. var getPos = function getPos(node, i) {
  21146. return {
  21147. x: bb.x1 + Math.round(Math.random() * bb.w),
  21148. y: bb.y1 + Math.round(Math.random() * bb.h)
  21149. };
  21150. };
  21151. eles.nodes().layoutPositions(this, options, getPos);
  21152. return this; // chaining
  21153. };
  21154. var layout = [{
  21155. name: 'breadthfirst',
  21156. impl: BreadthFirstLayout
  21157. }, {
  21158. name: 'circle',
  21159. impl: CircleLayout
  21160. }, {
  21161. name: 'concentric',
  21162. impl: ConcentricLayout
  21163. }, {
  21164. name: 'cose',
  21165. impl: CoseLayout
  21166. }, {
  21167. name: 'grid',
  21168. impl: GridLayout
  21169. }, {
  21170. name: 'null',
  21171. impl: NullLayout
  21172. }, {
  21173. name: 'preset',
  21174. impl: PresetLayout
  21175. }, {
  21176. name: 'random',
  21177. impl: RandomLayout
  21178. }];
  21179. function NullRenderer(options) {
  21180. this.options = options;
  21181. this.notifications = 0; // for testing
  21182. }
  21183. var noop = function noop() {};
  21184. var throwImgErr = function throwImgErr() {
  21185. throw new Error('A headless instance can not render images');
  21186. };
  21187. NullRenderer.prototype = {
  21188. recalculateRenderedStyle: noop,
  21189. notify: function notify() {
  21190. this.notifications++;
  21191. },
  21192. init: noop,
  21193. isHeadless: function isHeadless() {
  21194. return true;
  21195. },
  21196. png: throwImgErr,
  21197. jpg: throwImgErr
  21198. };
  21199. var BRp$f = {};
  21200. BRp$f.arrowShapeWidth = 0.3;
  21201. BRp$f.registerArrowShapes = function () {
  21202. var arrowShapes = this.arrowShapes = {};
  21203. var renderer = this;
  21204. // Contract for arrow shapes:
  21205. // 0, 0 is arrow tip
  21206. // (0, 1) is direction towards node
  21207. // (1, 0) is right
  21208. //
  21209. // functional api:
  21210. // collide: check x, y in shape
  21211. // roughCollide: called before collide, no false negatives
  21212. // draw: draw
  21213. // spacing: dist(arrowTip, nodeBoundary)
  21214. // gap: dist(edgeTip, nodeBoundary), edgeTip may != arrowTip
  21215. var bbCollide = function bbCollide(x, y, size, angle, translation, edgeWidth, padding) {
  21216. var x1 = translation.x - size / 2 - padding;
  21217. var x2 = translation.x + size / 2 + padding;
  21218. var y1 = translation.y - size / 2 - padding;
  21219. var y2 = translation.y + size / 2 + padding;
  21220. var inside = x1 <= x && x <= x2 && y1 <= y && y <= y2;
  21221. return inside;
  21222. };
  21223. var transform = function transform(x, y, size, angle, translation) {
  21224. var xRotated = x * Math.cos(angle) - y * Math.sin(angle);
  21225. var yRotated = x * Math.sin(angle) + y * Math.cos(angle);
  21226. var xScaled = xRotated * size;
  21227. var yScaled = yRotated * size;
  21228. var xTranslated = xScaled + translation.x;
  21229. var yTranslated = yScaled + translation.y;
  21230. return {
  21231. x: xTranslated,
  21232. y: yTranslated
  21233. };
  21234. };
  21235. var transformPoints = function transformPoints(pts, size, angle, translation) {
  21236. var retPts = [];
  21237. for (var i = 0; i < pts.length; i += 2) {
  21238. var x = pts[i];
  21239. var y = pts[i + 1];
  21240. retPts.push(transform(x, y, size, angle, translation));
  21241. }
  21242. return retPts;
  21243. };
  21244. var pointsToArr = function pointsToArr(pts) {
  21245. var ret = [];
  21246. for (var i = 0; i < pts.length; i++) {
  21247. var p = pts[i];
  21248. ret.push(p.x, p.y);
  21249. }
  21250. return ret;
  21251. };
  21252. var standardGap = function standardGap(edge) {
  21253. return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;
  21254. };
  21255. var defineArrowShape = function defineArrowShape(name, defn) {
  21256. if (string(defn)) {
  21257. defn = arrowShapes[defn];
  21258. }
  21259. arrowShapes[name] = extend({
  21260. name: name,
  21261. points: [-0.15, -0.3, 0.15, -0.3, 0.15, 0.3, -0.15, 0.3],
  21262. collide: function collide(x, y, size, angle, translation, padding) {
  21263. var points = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21264. var inside = pointInsidePolygonPoints(x, y, points);
  21265. return inside;
  21266. },
  21267. roughCollide: bbCollide,
  21268. draw: function draw(context, size, angle, translation) {
  21269. var points = transformPoints(this.points, size, angle, translation);
  21270. renderer.arrowShapeImpl('polygon')(context, points);
  21271. },
  21272. spacing: function spacing(edge) {
  21273. return 0;
  21274. },
  21275. gap: standardGap
  21276. }, defn);
  21277. };
  21278. defineArrowShape('none', {
  21279. collide: falsify,
  21280. roughCollide: falsify,
  21281. draw: noop$1,
  21282. spacing: zeroify,
  21283. gap: zeroify
  21284. });
  21285. defineArrowShape('triangle', {
  21286. points: [-0.15, -0.3, 0, 0, 0.15, -0.3]
  21287. });
  21288. defineArrowShape('arrow', 'triangle');
  21289. defineArrowShape('triangle-backcurve', {
  21290. points: arrowShapes['triangle'].points,
  21291. controlPoint: [0, -0.15],
  21292. roughCollide: bbCollide,
  21293. draw: function draw(context, size, angle, translation, edgeWidth) {
  21294. var ptsTrans = transformPoints(this.points, size, angle, translation);
  21295. var ctrlPt = this.controlPoint;
  21296. var ctrlPtTrans = transform(ctrlPt[0], ctrlPt[1], size, angle, translation);
  21297. renderer.arrowShapeImpl(this.name)(context, ptsTrans, ctrlPtTrans);
  21298. },
  21299. gap: function gap(edge) {
  21300. return standardGap(edge) * 0.8;
  21301. }
  21302. });
  21303. defineArrowShape('triangle-tee', {
  21304. points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
  21305. pointsTee: [-0.15, -0.4, -0.15, -0.5, 0.15, -0.5, 0.15, -0.4],
  21306. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21307. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21308. var teePts = pointsToArr(transformPoints(this.pointsTee, size + 2 * padding, angle, translation));
  21309. var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
  21310. return inside;
  21311. },
  21312. draw: function draw(context, size, angle, translation, edgeWidth) {
  21313. var triPts = transformPoints(this.points, size, angle, translation);
  21314. var teePts = transformPoints(this.pointsTee, size, angle, translation);
  21315. renderer.arrowShapeImpl(this.name)(context, triPts, teePts);
  21316. }
  21317. });
  21318. defineArrowShape('circle-triangle', {
  21319. radius: 0.15,
  21320. pointsTr: [0, -0.15, 0.15, -0.45, -0.15, -0.45, 0, -0.15],
  21321. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21322. var t = translation;
  21323. var circleInside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
  21324. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21325. return pointInsidePolygonPoints(x, y, triPts) || circleInside;
  21326. },
  21327. draw: function draw(context, size, angle, translation, edgeWidth) {
  21328. var triPts = transformPoints(this.pointsTr, size, angle, translation);
  21329. renderer.arrowShapeImpl(this.name)(context, triPts, translation.x, translation.y, this.radius * size);
  21330. },
  21331. spacing: function spacing(edge) {
  21332. return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
  21333. }
  21334. });
  21335. defineArrowShape('triangle-cross', {
  21336. points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
  21337. baseCrossLinePts: [-0.15, -0.4,
  21338. // first half of the rectangle
  21339. -0.15, -0.4, 0.15, -0.4,
  21340. // second half of the rectangle
  21341. 0.15, -0.4],
  21342. crossLinePts: function crossLinePts(size, edgeWidth) {
  21343. // shift points so that the distance between the cross points matches edge width
  21344. var p = this.baseCrossLinePts.slice();
  21345. var shiftFactor = edgeWidth / size;
  21346. var y0 = 3;
  21347. var y1 = 5;
  21348. p[y0] = p[y0] - shiftFactor;
  21349. p[y1] = p[y1] - shiftFactor;
  21350. return p;
  21351. },
  21352. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21353. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21354. var teePts = pointsToArr(transformPoints(this.crossLinePts(size, edgeWidth), size + 2 * padding, angle, translation));
  21355. var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
  21356. return inside;
  21357. },
  21358. draw: function draw(context, size, angle, translation, edgeWidth) {
  21359. var triPts = transformPoints(this.points, size, angle, translation);
  21360. var crossLinePts = transformPoints(this.crossLinePts(size, edgeWidth), size, angle, translation);
  21361. renderer.arrowShapeImpl(this.name)(context, triPts, crossLinePts);
  21362. }
  21363. });
  21364. defineArrowShape('vee', {
  21365. points: [-0.15, -0.3, 0, 0, 0.15, -0.3, 0, -0.15],
  21366. gap: function gap(edge) {
  21367. return standardGap(edge) * 0.525;
  21368. }
  21369. });
  21370. defineArrowShape('circle', {
  21371. radius: 0.15,
  21372. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21373. var t = translation;
  21374. var inside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
  21375. return inside;
  21376. },
  21377. draw: function draw(context, size, angle, translation, edgeWidth) {
  21378. renderer.arrowShapeImpl(this.name)(context, translation.x, translation.y, this.radius * size);
  21379. },
  21380. spacing: function spacing(edge) {
  21381. return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
  21382. }
  21383. });
  21384. defineArrowShape('tee', {
  21385. points: [-0.15, 0, -0.15, -0.1, 0.15, -0.1, 0.15, 0],
  21386. spacing: function spacing(edge) {
  21387. return 1;
  21388. },
  21389. gap: function gap(edge) {
  21390. return 1;
  21391. }
  21392. });
  21393. defineArrowShape('square', {
  21394. points: [-0.15, 0.00, 0.15, 0.00, 0.15, -0.3, -0.15, -0.3]
  21395. });
  21396. defineArrowShape('diamond', {
  21397. points: [-0.15, -0.15, 0, -0.3, 0.15, -0.15, 0, 0],
  21398. gap: function gap(edge) {
  21399. return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
  21400. }
  21401. });
  21402. defineArrowShape('chevron', {
  21403. points: [0, 0, -0.15, -0.15, -0.1, -0.2, 0, -0.1, 0.1, -0.2, 0.15, -0.15],
  21404. gap: function gap(edge) {
  21405. return 0.95 * edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
  21406. }
  21407. });
  21408. };
  21409. var BRp$e = {};
  21410. // Project mouse
  21411. BRp$e.projectIntoViewport = function (clientX, clientY) {
  21412. var cy = this.cy;
  21413. var offsets = this.findContainerClientCoords();
  21414. var offsetLeft = offsets[0];
  21415. var offsetTop = offsets[1];
  21416. var scale = offsets[4];
  21417. var pan = cy.pan();
  21418. var zoom = cy.zoom();
  21419. var x = ((clientX - offsetLeft) / scale - pan.x) / zoom;
  21420. var y = ((clientY - offsetTop) / scale - pan.y) / zoom;
  21421. return [x, y];
  21422. };
  21423. BRp$e.findContainerClientCoords = function () {
  21424. if (this.containerBB) {
  21425. return this.containerBB;
  21426. }
  21427. var container = this.container;
  21428. var rect = container.getBoundingClientRect();
  21429. var style = this.cy.window().getComputedStyle(container);
  21430. var styleValue = function styleValue(name) {
  21431. return parseFloat(style.getPropertyValue(name));
  21432. };
  21433. var padding = {
  21434. left: styleValue('padding-left'),
  21435. right: styleValue('padding-right'),
  21436. top: styleValue('padding-top'),
  21437. bottom: styleValue('padding-bottom')
  21438. };
  21439. var border = {
  21440. left: styleValue('border-left-width'),
  21441. right: styleValue('border-right-width'),
  21442. top: styleValue('border-top-width'),
  21443. bottom: styleValue('border-bottom-width')
  21444. };
  21445. var clientWidth = container.clientWidth;
  21446. var clientHeight = container.clientHeight;
  21447. var paddingHor = padding.left + padding.right;
  21448. var paddingVer = padding.top + padding.bottom;
  21449. var borderHor = border.left + border.right;
  21450. var scale = rect.width / (clientWidth + borderHor);
  21451. var unscaledW = clientWidth - paddingHor;
  21452. var unscaledH = clientHeight - paddingVer;
  21453. var left = rect.left + padding.left + border.left;
  21454. var top = rect.top + padding.top + border.top;
  21455. return this.containerBB = [left, top, unscaledW, unscaledH, scale];
  21456. };
  21457. BRp$e.invalidateContainerClientCoordsCache = function () {
  21458. this.containerBB = null;
  21459. };
  21460. BRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {
  21461. return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];
  21462. };
  21463. BRp$e.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  21464. var self = this;
  21465. var r = this;
  21466. var eles = r.getCachedZSortedEles();
  21467. var near = []; // 1 node max, 1 edge max
  21468. var zoom = r.cy.zoom();
  21469. var hasCompounds = r.cy.hasCompoundNodes();
  21470. var edgeThreshold = (isTouch ? 24 : 8) / zoom;
  21471. var nodeThreshold = (isTouch ? 8 : 2) / zoom;
  21472. var labelThreshold = (isTouch ? 8 : 2) / zoom;
  21473. var minSqDist = Infinity;
  21474. var nearEdge;
  21475. var nearNode;
  21476. if (interactiveElementsOnly) {
  21477. eles = eles.interactive;
  21478. }
  21479. function addEle(ele, sqDist) {
  21480. if (ele.isNode()) {
  21481. if (nearNode) {
  21482. return; // can't replace node
  21483. } else {
  21484. nearNode = ele;
  21485. near.push(ele);
  21486. }
  21487. }
  21488. if (ele.isEdge() && (sqDist == null || sqDist < minSqDist)) {
  21489. if (nearEdge) {
  21490. // then replace existing edge
  21491. // can replace only if same z-index
  21492. if (nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value && nearEdge.pstyle('z-compound-depth').value === ele.pstyle('z-compound-depth').value) {
  21493. for (var i = 0; i < near.length; i++) {
  21494. if (near[i].isEdge()) {
  21495. near[i] = ele;
  21496. nearEdge = ele;
  21497. minSqDist = sqDist != null ? sqDist : minSqDist;
  21498. break;
  21499. }
  21500. }
  21501. }
  21502. } else {
  21503. near.push(ele);
  21504. nearEdge = ele;
  21505. minSqDist = sqDist != null ? sqDist : minSqDist;
  21506. }
  21507. }
  21508. }
  21509. function checkNode(node) {
  21510. var width = node.outerWidth() + 2 * nodeThreshold;
  21511. var height = node.outerHeight() + 2 * nodeThreshold;
  21512. var hw = width / 2;
  21513. var hh = height / 2;
  21514. var pos = node.position();
  21515. var cornerRadius = node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue;
  21516. var rs = node._private.rscratch;
  21517. if (pos.x - hw <= x && x <= pos.x + hw // bb check x
  21518. && pos.y - hh <= y && y <= pos.y + hh // bb check y
  21519. ) {
  21520. var shape = r.nodeShapes[self.getNodeShape(node)];
  21521. if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y, cornerRadius, rs)) {
  21522. addEle(node, 0);
  21523. return true;
  21524. }
  21525. }
  21526. }
  21527. function checkEdge(edge) {
  21528. var _p = edge._private;
  21529. var rs = _p.rscratch;
  21530. var styleWidth = edge.pstyle('width').pfValue;
  21531. var scale = edge.pstyle('arrow-scale').value;
  21532. var width = styleWidth / 2 + edgeThreshold; // more like a distance radius from centre
  21533. var widthSq = width * width;
  21534. var width2 = width * 2;
  21535. var src = _p.source;
  21536. var tgt = _p.target;
  21537. var sqDist;
  21538. if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {
  21539. var pts = rs.allpts;
  21540. for (var i = 0; i + 3 < pts.length; i += 2) {
  21541. if (inLineVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], width2) && widthSq > (sqDist = sqdistToFiniteLine(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3]))) {
  21542. addEle(edge, sqDist);
  21543. return true;
  21544. }
  21545. }
  21546. } else if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
  21547. var pts = rs.allpts;
  21548. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  21549. if (inBezierVicinity(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5], width2) && widthSq > (sqDist = sqdistToQuadraticBezier(x, y, pts[i], pts[i + 1], pts[i + 2], pts[i + 3], pts[i + 4], pts[i + 5]))) {
  21550. addEle(edge, sqDist);
  21551. return true;
  21552. }
  21553. }
  21554. }
  21555. // if we're close to the edge but didn't hit it, maybe we hit its arrows
  21556. var src = src || _p.source;
  21557. var tgt = tgt || _p.target;
  21558. var arSize = self.getArrowWidth(styleWidth, scale);
  21559. var arrows = [{
  21560. name: 'source',
  21561. x: rs.arrowStartX,
  21562. y: rs.arrowStartY,
  21563. angle: rs.srcArrowAngle
  21564. }, {
  21565. name: 'target',
  21566. x: rs.arrowEndX,
  21567. y: rs.arrowEndY,
  21568. angle: rs.tgtArrowAngle
  21569. }, {
  21570. name: 'mid-source',
  21571. x: rs.midX,
  21572. y: rs.midY,
  21573. angle: rs.midsrcArrowAngle
  21574. }, {
  21575. name: 'mid-target',
  21576. x: rs.midX,
  21577. y: rs.midY,
  21578. angle: rs.midtgtArrowAngle
  21579. }];
  21580. for (var i = 0; i < arrows.length; i++) {
  21581. var ar = arrows[i];
  21582. var shape = r.arrowShapes[edge.pstyle(ar.name + '-arrow-shape').value];
  21583. var edgeWidth = edge.pstyle('width').pfValue;
  21584. if (shape.roughCollide(x, y, arSize, ar.angle, {
  21585. x: ar.x,
  21586. y: ar.y
  21587. }, edgeWidth, edgeThreshold) && shape.collide(x, y, arSize, ar.angle, {
  21588. x: ar.x,
  21589. y: ar.y
  21590. }, edgeWidth, edgeThreshold)) {
  21591. addEle(edge);
  21592. return true;
  21593. }
  21594. }
  21595. // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)
  21596. if (hasCompounds && near.length > 0) {
  21597. checkNode(src);
  21598. checkNode(tgt);
  21599. }
  21600. }
  21601. function preprop(obj, name, pre) {
  21602. return getPrefixedProperty(obj, name, pre);
  21603. }
  21604. function checkLabel(ele, prefix) {
  21605. var _p = ele._private;
  21606. var th = labelThreshold;
  21607. var prefixDash;
  21608. if (prefix) {
  21609. prefixDash = prefix + '-';
  21610. } else {
  21611. prefixDash = '';
  21612. }
  21613. ele.boundingBox();
  21614. var bb = _p.labelBounds[prefix || 'main'];
  21615. var text = ele.pstyle(prefixDash + 'label').value;
  21616. var eventsEnabled = ele.pstyle('text-events').strValue === 'yes';
  21617. if (!eventsEnabled || !text) {
  21618. return;
  21619. }
  21620. var lx = preprop(_p.rscratch, 'labelX', prefix);
  21621. var ly = preprop(_p.rscratch, 'labelY', prefix);
  21622. var theta = preprop(_p.rscratch, 'labelAngle', prefix);
  21623. var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  21624. var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  21625. var lx1 = bb.x1 - th - ox; // (-ox, -oy) as bb already includes margin
  21626. var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)
  21627. var ly1 = bb.y1 - th - oy;
  21628. var ly2 = bb.y2 + th - oy;
  21629. if (theta) {
  21630. var cos = Math.cos(theta);
  21631. var sin = Math.sin(theta);
  21632. var rotate = function rotate(x, y) {
  21633. x = x - lx;
  21634. y = y - ly;
  21635. return {
  21636. x: x * cos - y * sin + lx,
  21637. y: x * sin + y * cos + ly
  21638. };
  21639. };
  21640. var px1y1 = rotate(lx1, ly1);
  21641. var px1y2 = rotate(lx1, ly2);
  21642. var px2y1 = rotate(lx2, ly1);
  21643. var px2y2 = rotate(lx2, ly2);
  21644. var points = [
  21645. // with the margin added after the rotation is applied
  21646. px1y1.x + ox, px1y1.y + oy, px2y1.x + ox, px2y1.y + oy, px2y2.x + ox, px2y2.y + oy, px1y2.x + ox, px1y2.y + oy];
  21647. if (pointInsidePolygonPoints(x, y, points)) {
  21648. addEle(ele);
  21649. return true;
  21650. }
  21651. } else {
  21652. // do a cheaper bb check
  21653. if (inBoundingBox(bb, x, y)) {
  21654. addEle(ele);
  21655. return true;
  21656. }
  21657. }
  21658. }
  21659. for (var i = eles.length - 1; i >= 0; i--) {
  21660. // reverse order for precedence
  21661. var ele = eles[i];
  21662. if (ele.isNode()) {
  21663. checkNode(ele) || checkLabel(ele);
  21664. } else {
  21665. // then edge
  21666. checkEdge(ele) || checkLabel(ele) || checkLabel(ele, 'source') || checkLabel(ele, 'target');
  21667. }
  21668. }
  21669. return near;
  21670. };
  21671. // 'Give me everything from this box'
  21672. BRp$e.getAllInBox = function (x1, y1, x2, y2) {
  21673. var eles = this.getCachedZSortedEles().interactive;
  21674. var zoom = this.cy.zoom();
  21675. var labelThreshold = 2 / zoom;
  21676. var box = [];
  21677. var x1c = Math.min(x1, x2);
  21678. var x2c = Math.max(x1, x2);
  21679. var y1c = Math.min(y1, y2);
  21680. var y2c = Math.max(y1, y2);
  21681. x1 = x1c;
  21682. x2 = x2c;
  21683. y1 = y1c;
  21684. y2 = y2c;
  21685. var boxBb = makeBoundingBox({
  21686. x1: x1,
  21687. y1: y1,
  21688. x2: x2,
  21689. y2: y2
  21690. });
  21691. var selectionBox = [{
  21692. x: boxBb.x1,
  21693. y: boxBb.y1
  21694. }, {
  21695. x: boxBb.x2,
  21696. y: boxBb.y1
  21697. }, {
  21698. x: boxBb.x2,
  21699. y: boxBb.y2
  21700. }, {
  21701. x: boxBb.x1,
  21702. y: boxBb.y2
  21703. }];
  21704. var boxEdges = [[selectionBox[0], selectionBox[1]], [selectionBox[1], selectionBox[2]], [selectionBox[2], selectionBox[3]], [selectionBox[3], selectionBox[0]]];
  21705. function preprop(obj, name, pre) {
  21706. return getPrefixedProperty(obj, name, pre);
  21707. }
  21708. function getRotatedLabelBox(ele, prefix) {
  21709. var _p = ele._private;
  21710. var th = labelThreshold;
  21711. var prefixDash = '';
  21712. ele.boundingBox();
  21713. var bb = _p.labelBounds['main'];
  21714. // If the bounding box is not available, return null.
  21715. // This indicates that the label box cannot be calculated, which is consistent
  21716. // with the expected behavior of this function. Returning null allows the caller
  21717. // to handle the absence of a bounding box explicitly.
  21718. if (!bb) {
  21719. return null;
  21720. }
  21721. var lx = preprop(_p.rscratch, 'labelX', prefix);
  21722. var ly = preprop(_p.rscratch, 'labelY', prefix);
  21723. var theta = preprop(_p.rscratch, 'labelAngle', prefix);
  21724. var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  21725. var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  21726. var lx1 = bb.x1 - th - ox;
  21727. var lx2 = bb.x2 + th - ox;
  21728. var ly1 = bb.y1 - th - oy;
  21729. var ly2 = bb.y2 + th - oy;
  21730. if (theta) {
  21731. var cos = Math.cos(theta);
  21732. var sin = Math.sin(theta);
  21733. var rotate = function rotate(x, y) {
  21734. x = x - lx;
  21735. y = y - ly;
  21736. return {
  21737. x: x * cos - y * sin + lx,
  21738. y: x * sin + y * cos + ly
  21739. };
  21740. };
  21741. return [rotate(lx1, ly1), rotate(lx2, ly1), rotate(lx2, ly2), rotate(lx1, ly2)];
  21742. } else {
  21743. return [{
  21744. x: lx1,
  21745. y: ly1
  21746. }, {
  21747. x: lx2,
  21748. y: ly1
  21749. }, {
  21750. x: lx2,
  21751. y: ly2
  21752. }, {
  21753. x: lx1,
  21754. y: ly2
  21755. }];
  21756. }
  21757. }
  21758. function doLinesIntersect(p1, p2, q1, q2) {
  21759. function ccw(a, b, c) {
  21760. return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
  21761. }
  21762. return ccw(p1, q1, q2) !== ccw(p2, q1, q2) && ccw(p1, p2, q1) !== ccw(p1, p2, q2);
  21763. }
  21764. for (var e = 0; e < eles.length; e++) {
  21765. var ele = eles[e];
  21766. if (ele.isNode()) {
  21767. var node = ele;
  21768. var textEvents = node.pstyle('text-events').strValue === 'yes';
  21769. var nodeBoxSelectMode = node.pstyle('box-selection').strValue;
  21770. var labelBoxSelectEnabled = node.pstyle('box-select-labels').strValue === 'yes';
  21771. if (nodeBoxSelectMode === 'none') {
  21772. continue;
  21773. }
  21774. var includeLabels = (nodeBoxSelectMode === 'overlap' || labelBoxSelectEnabled) && textEvents;
  21775. var nodeBb = node.boundingBox({
  21776. includeNodes: true,
  21777. includeEdges: false,
  21778. includeLabels: includeLabels
  21779. });
  21780. if (nodeBoxSelectMode === 'contain') {
  21781. var selected = false;
  21782. if (labelBoxSelectEnabled && textEvents) {
  21783. var rotatedLabelBox = getRotatedLabelBox(node);
  21784. if (rotatedLabelBox && satPolygonIntersection(rotatedLabelBox, selectionBox)) {
  21785. box.push(node);
  21786. selected = true;
  21787. }
  21788. }
  21789. if (!selected && boundingBoxInBoundingBox(boxBb, nodeBb)) {
  21790. box.push(node);
  21791. }
  21792. } else if (nodeBoxSelectMode === 'overlap') {
  21793. if (boundingBoxesIntersect(boxBb, nodeBb)) {
  21794. var nodeBodyBb = node.boundingBox({
  21795. includeNodes: true,
  21796. includeEdges: true,
  21797. includeLabels: false,
  21798. includeMainLabels: false,
  21799. includeSourceLabels: false,
  21800. includeTargetLabels: false
  21801. });
  21802. var nodeBodyCorners = [{
  21803. x: nodeBodyBb.x1,
  21804. y: nodeBodyBb.y1
  21805. }, {
  21806. x: nodeBodyBb.x2,
  21807. y: nodeBodyBb.y1
  21808. }, {
  21809. x: nodeBodyBb.x2,
  21810. y: nodeBodyBb.y2
  21811. }, {
  21812. x: nodeBodyBb.x1,
  21813. y: nodeBodyBb.y2
  21814. }];
  21815. // if node body intersects, no need to check label
  21816. if (satPolygonIntersection(nodeBodyCorners, selectionBox)) {
  21817. box.push(node);
  21818. } else {
  21819. // only check label if node body didn't intersect
  21820. var _rotatedLabelBox = getRotatedLabelBox(node);
  21821. if (_rotatedLabelBox && satPolygonIntersection(_rotatedLabelBox, selectionBox)) {
  21822. box.push(node);
  21823. }
  21824. }
  21825. }
  21826. }
  21827. } else {
  21828. var edge = ele;
  21829. var _p = edge._private;
  21830. var rs = _p.rscratch;
  21831. var edgeBoxSelectMode = edge.pstyle('box-selection').strValue;
  21832. if (edgeBoxSelectMode === 'none') {
  21833. continue;
  21834. }
  21835. if (edgeBoxSelectMode === 'contain') {
  21836. if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {
  21837. continue;
  21838. }
  21839. if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {
  21840. continue;
  21841. }
  21842. if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound' || rs.edgeType === 'segments' || rs.edgeType === 'haystack') {
  21843. var pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
  21844. var allInside = true;
  21845. for (var i = 0; i < pts.length; i++) {
  21846. if (!pointInBoundingBox(boxBb, pts[i])) {
  21847. allInside = false;
  21848. break;
  21849. }
  21850. }
  21851. if (allInside) {
  21852. box.push(edge);
  21853. }
  21854. } else if (rs.edgeType === 'straight') {
  21855. box.push(edge);
  21856. }
  21857. } else if (edgeBoxSelectMode === 'overlap') {
  21858. var _selected = false;
  21859. // Check: either endpoint inside box
  21860. if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null && (inBoundingBox(boxBb, rs.startX, rs.startY) || inBoundingBox(boxBb, rs.endX, rs.endY))) {
  21861. box.push(edge);
  21862. _selected = true;
  21863. }
  21864. // Haystack fallback (only check if not already selected)
  21865. else if (!_selected && rs.edgeType === 'haystack') {
  21866. var haystackPts = _p.rstyle.haystackPts;
  21867. for (var _i = 0; _i < haystackPts.length; _i++) {
  21868. if (pointInBoundingBox(boxBb, haystackPts[_i])) {
  21869. box.push(edge);
  21870. _selected = true;
  21871. break;
  21872. }
  21873. }
  21874. }
  21875. // Segment intersection check (only if not already selected)
  21876. if (!_selected) {
  21877. var _pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
  21878. // straight edges
  21879. if ((!_pts || _pts.length < 2) && rs.edgeType === 'straight') {
  21880. if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null) {
  21881. _pts = [{
  21882. x: rs.startX,
  21883. y: rs.startY
  21884. }, {
  21885. x: rs.endX,
  21886. y: rs.endY
  21887. }];
  21888. }
  21889. }
  21890. if (!_pts || _pts.length < 2) continue;
  21891. for (var _i2 = 0; _i2 < _pts.length - 1; _i2++) {
  21892. var segStart = _pts[_i2];
  21893. var segEnd = _pts[_i2 + 1];
  21894. for (var b = 0; b < boxEdges.length; b++) {
  21895. var _boxEdges$b = _slicedToArray(boxEdges[b], 2),
  21896. boxStart = _boxEdges$b[0],
  21897. boxEnd = _boxEdges$b[1];
  21898. if (doLinesIntersect(segStart, segEnd, boxStart, boxEnd)) {
  21899. box.push(edge);
  21900. _selected = true;
  21901. break;
  21902. }
  21903. }
  21904. if (_selected) break;
  21905. }
  21906. }
  21907. }
  21908. }
  21909. }
  21910. return box;
  21911. };
  21912. var BRp$d = {};
  21913. BRp$d.calculateArrowAngles = function (edge) {
  21914. var rs = edge._private.rscratch;
  21915. var isHaystack = rs.edgeType === 'haystack';
  21916. var isBezier = rs.edgeType === 'bezier';
  21917. var isMultibezier = rs.edgeType === 'multibezier';
  21918. var isSegments = rs.edgeType === 'segments';
  21919. var isCompound = rs.edgeType === 'compound';
  21920. var isSelf = rs.edgeType === 'self';
  21921. // Displacement gives direction for arrowhead orientation
  21922. var dispX, dispY;
  21923. var startX, startY, endX, endY, midX, midY;
  21924. if (isHaystack) {
  21925. startX = rs.haystackPts[0];
  21926. startY = rs.haystackPts[1];
  21927. endX = rs.haystackPts[2];
  21928. endY = rs.haystackPts[3];
  21929. } else {
  21930. startX = rs.arrowStartX;
  21931. startY = rs.arrowStartY;
  21932. endX = rs.arrowEndX;
  21933. endY = rs.arrowEndY;
  21934. }
  21935. midX = rs.midX;
  21936. midY = rs.midY;
  21937. // source
  21938. //
  21939. if (isSegments) {
  21940. dispX = startX - rs.segpts[0];
  21941. dispY = startY - rs.segpts[1];
  21942. } else if (isMultibezier || isCompound || isSelf || isBezier) {
  21943. var pts = rs.allpts;
  21944. var bX = qbezierAt(pts[0], pts[2], pts[4], 0.1);
  21945. var bY = qbezierAt(pts[1], pts[3], pts[5], 0.1);
  21946. dispX = startX - bX;
  21947. dispY = startY - bY;
  21948. } else {
  21949. dispX = startX - midX;
  21950. dispY = startY - midY;
  21951. }
  21952. rs.srcArrowAngle = getAngleFromDisp(dispX, dispY);
  21953. // mid target
  21954. //
  21955. var midX = rs.midX;
  21956. var midY = rs.midY;
  21957. if (isHaystack) {
  21958. midX = (startX + endX) / 2;
  21959. midY = (startY + endY) / 2;
  21960. }
  21961. dispX = endX - startX;
  21962. dispY = endY - startY;
  21963. if (isSegments) {
  21964. var pts = rs.allpts;
  21965. if (pts.length / 2 % 2 === 0) {
  21966. var i2 = pts.length / 2;
  21967. var i1 = i2 - 2;
  21968. dispX = pts[i2] - pts[i1];
  21969. dispY = pts[i2 + 1] - pts[i1 + 1];
  21970. } else if (rs.isRound) {
  21971. dispX = rs.midVector[1];
  21972. dispY = -rs.midVector[0];
  21973. } else {
  21974. var i2 = pts.length / 2 - 1;
  21975. var i1 = i2 - 2;
  21976. dispX = pts[i2] - pts[i1];
  21977. dispY = pts[i2 + 1] - pts[i1 + 1];
  21978. }
  21979. } else if (isMultibezier || isCompound || isSelf) {
  21980. var pts = rs.allpts;
  21981. var cpts = rs.ctrlpts;
  21982. var bp0x, bp0y;
  21983. var bp1x, bp1y;
  21984. if (cpts.length / 2 % 2 === 0) {
  21985. var p0 = pts.length / 2 - 1; // startpt
  21986. var ic = p0 + 2;
  21987. var p1 = ic + 2;
  21988. bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0);
  21989. bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0);
  21990. bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0001);
  21991. bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0001);
  21992. } else {
  21993. var ic = pts.length / 2 - 1; // ctrpt
  21994. var p0 = ic - 2; // startpt
  21995. var p1 = ic + 2; // endpt
  21996. bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.4999);
  21997. bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.4999);
  21998. bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.5);
  21999. bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.5);
  22000. }
  22001. dispX = bp1x - bp0x;
  22002. dispY = bp1y - bp0y;
  22003. }
  22004. rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);
  22005. rs.midDispX = dispX;
  22006. rs.midDispY = dispY;
  22007. // mid source
  22008. //
  22009. dispX *= -1;
  22010. dispY *= -1;
  22011. if (isSegments) {
  22012. var pts = rs.allpts;
  22013. if (pts.length / 2 % 2 === 0) ; else if (!rs.isRound) {
  22014. var i2 = pts.length / 2 - 1;
  22015. var i3 = i2 + 2;
  22016. dispX = -(pts[i3] - pts[i2]);
  22017. dispY = -(pts[i3 + 1] - pts[i2 + 1]);
  22018. }
  22019. }
  22020. rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY);
  22021. // target
  22022. //
  22023. if (isSegments) {
  22024. dispX = endX - rs.segpts[rs.segpts.length - 2];
  22025. dispY = endY - rs.segpts[rs.segpts.length - 1];
  22026. } else if (isMultibezier || isCompound || isSelf || isBezier) {
  22027. var pts = rs.allpts;
  22028. var l = pts.length;
  22029. var bX = qbezierAt(pts[l - 6], pts[l - 4], pts[l - 2], 0.9);
  22030. var bY = qbezierAt(pts[l - 5], pts[l - 3], pts[l - 1], 0.9);
  22031. dispX = endX - bX;
  22032. dispY = endY - bY;
  22033. } else {
  22034. dispX = endX - midX;
  22035. dispY = endY - midY;
  22036. }
  22037. rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);
  22038. };
  22039. BRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {
  22040. var cache = this.arrowWidthCache = this.arrowWidthCache || {};
  22041. var cachedVal = cache[edgeWidth + ', ' + scale];
  22042. if (cachedVal) {
  22043. return cachedVal;
  22044. }
  22045. cachedVal = Math.max(Math.pow(edgeWidth * 13.37, 0.9), 29) * scale;
  22046. cache[edgeWidth + ', ' + scale] = cachedVal;
  22047. return cachedVal;
  22048. };
  22049. /**
  22050. * Explained by Blindman67 at https://stackoverflow.com/a/44856925/11028828
  22051. */
  22052. // Declare reused variable to avoid reallocating variables every time the function is called
  22053. var x,
  22054. y,
  22055. v1 = {},
  22056. v2 = {},
  22057. sinA,
  22058. sinA90,
  22059. radDirection,
  22060. drawDirection,
  22061. angle,
  22062. halfAngle,
  22063. cRadius,
  22064. lenOut,
  22065. radius,
  22066. limit;
  22067. var startX, startY, stopX, stopY;
  22068. var lastPoint;
  22069. // convert 2 points into vector form, polar form, and normalised
  22070. var asVec = function asVec(p, pp, v) {
  22071. v.x = pp.x - p.x;
  22072. v.y = pp.y - p.y;
  22073. v.len = Math.sqrt(v.x * v.x + v.y * v.y);
  22074. v.nx = v.x / v.len;
  22075. v.ny = v.y / v.len;
  22076. v.ang = Math.atan2(v.ny, v.nx);
  22077. };
  22078. var invertVec = function invertVec(originalV, invertedV) {
  22079. invertedV.x = originalV.x * -1;
  22080. invertedV.y = originalV.y * -1;
  22081. invertedV.nx = originalV.nx * -1;
  22082. invertedV.ny = originalV.ny * -1;
  22083. invertedV.ang = originalV.ang > 0 ? -(Math.PI - originalV.ang) : Math.PI + originalV.ang;
  22084. };
  22085. var calcCornerArc = function calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius) {
  22086. //-----------------------------------------
  22087. // Part 1
  22088. previousPoint !== lastPoint ? asVec(currentPoint, previousPoint, v1) : invertVec(v2, v1); // Avoid recalculating vec if it is the invert of the last one calculated
  22089. asVec(currentPoint, nextPoint, v2);
  22090. sinA = v1.nx * v2.ny - v1.ny * v2.nx;
  22091. sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;
  22092. angle = Math.asin(Math.max(-1, Math.min(1, sinA)));
  22093. if (Math.abs(angle) < 1e-6) {
  22094. x = currentPoint.x;
  22095. y = currentPoint.y;
  22096. cRadius = radius = 0;
  22097. return;
  22098. }
  22099. //-----------------------------------------
  22100. radDirection = 1;
  22101. drawDirection = false;
  22102. if (sinA90 < 0) {
  22103. if (angle < 0) {
  22104. angle = Math.PI + angle;
  22105. } else {
  22106. angle = Math.PI - angle;
  22107. radDirection = -1;
  22108. drawDirection = true;
  22109. }
  22110. } else {
  22111. if (angle > 0) {
  22112. radDirection = -1;
  22113. drawDirection = true;
  22114. }
  22115. }
  22116. if (currentPoint.radius !== undefined) {
  22117. radius = currentPoint.radius;
  22118. } else {
  22119. radius = radiusMax;
  22120. }
  22121. //-----------------------------------------
  22122. // Part 2
  22123. halfAngle = angle / 2;
  22124. //-----------------------------------------
  22125. limit = Math.min(v1.len / 2, v2.len / 2);
  22126. if (isArcRadius) {
  22127. //-----------------------------------------
  22128. // Part 3
  22129. lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));
  22130. //-----------------------------------------
  22131. // Special part A
  22132. if (lenOut > limit) {
  22133. lenOut = limit;
  22134. cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  22135. } else {
  22136. cRadius = radius;
  22137. }
  22138. } else {
  22139. lenOut = Math.min(limit, radius);
  22140. cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  22141. }
  22142. //-----------------------------------------
  22143. //-----------------------------------------
  22144. // Part 4
  22145. stopX = currentPoint.x + v2.nx * lenOut;
  22146. stopY = currentPoint.y + v2.ny * lenOut;
  22147. //-----------------------------------------
  22148. // Part 5
  22149. x = stopX - v2.ny * cRadius * radDirection;
  22150. y = stopY + v2.nx * cRadius * radDirection;
  22151. //-----------------------------------------
  22152. // Additional Part : calculate start point E
  22153. startX = currentPoint.x + v1.nx * lenOut;
  22154. startY = currentPoint.y + v1.ny * lenOut;
  22155. // Save last point to avoid recalculating vector when not needed
  22156. lastPoint = currentPoint;
  22157. };
  22158. /**
  22159. * Draw corner provided by {@link getRoundCorner}
  22160. *
  22161. * @param ctx :CanvasRenderingContext2D
  22162. * @param roundCorner {{cx:number, cy:number, radius:number, endAngle: number, startAngle: number, counterClockwise: boolean}}
  22163. */
  22164. function drawPreparedRoundCorner(ctx, roundCorner) {
  22165. if (roundCorner.radius === 0) ctx.lineTo(roundCorner.cx, roundCorner.cy);else ctx.arc(roundCorner.cx, roundCorner.cy, roundCorner.radius, roundCorner.startAngle, roundCorner.endAngle, roundCorner.counterClockwise);
  22166. }
  22167. /**
  22168. * Get round corner from a point and its previous and next neighbours in a path
  22169. *
  22170. * @param previousPoint {{x: number, y:number, radius: number?}}
  22171. * @param currentPoint {{x: number, y:number, radius: number?}}
  22172. * @param nextPoint {{x: number, y:number, radius: number?}}
  22173. * @param radiusMax :number
  22174. * @param isArcRadius :boolean
  22175. * @return {{
  22176. * cx:number, cy:number, radius:number,
  22177. * startX:number, startY:number,
  22178. * stopX:number, stopY: number,
  22179. * endAngle: number, startAngle: number, counterClockwise: boolean
  22180. * }}
  22181. */
  22182. function getRoundCorner(previousPoint, currentPoint, nextPoint, radiusMax) {
  22183. var isArcRadius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  22184. if (radiusMax === 0 || currentPoint.radius === 0) return {
  22185. cx: currentPoint.x,
  22186. cy: currentPoint.y,
  22187. radius: 0,
  22188. startX: currentPoint.x,
  22189. startY: currentPoint.y,
  22190. stopX: currentPoint.x,
  22191. stopY: currentPoint.y,
  22192. startAngle: undefined,
  22193. endAngle: undefined,
  22194. counterClockwise: undefined
  22195. };
  22196. calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius);
  22197. return {
  22198. cx: x,
  22199. cy: y,
  22200. radius: cRadius,
  22201. startX: startX,
  22202. startY: startY,
  22203. stopX: stopX,
  22204. stopY: stopY,
  22205. startAngle: v1.ang + Math.PI / 2 * radDirection,
  22206. endAngle: v2.ang - Math.PI / 2 * radDirection,
  22207. counterClockwise: drawDirection
  22208. };
  22209. }
  22210. var AVOID_IMPOSSIBLE_BEZIER_CONSTANT = 0.01;
  22211. var AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L = Math.sqrt(2 * AVOID_IMPOSSIBLE_BEZIER_CONSTANT);
  22212. var BRp$c = {};
  22213. BRp$c.findMidptPtsEtc = function (edge, pairInfo) {
  22214. var posPts = pairInfo.posPts,
  22215. intersectionPts = pairInfo.intersectionPts,
  22216. vectorNormInverse = pairInfo.vectorNormInverse;
  22217. var midptPts;
  22218. // n.b. assumes all edges in bezier bundle have same endpoints specified
  22219. var srcManEndpt = edge.pstyle('source-endpoint');
  22220. var tgtManEndpt = edge.pstyle('target-endpoint');
  22221. var haveManualEndPts = srcManEndpt.units != null && tgtManEndpt.units != null;
  22222. var recalcVectorNormInverse = function recalcVectorNormInverse(x1, y1, x2, y2) {
  22223. var dy = y2 - y1;
  22224. var dx = x2 - x1;
  22225. var l = Math.sqrt(dx * dx + dy * dy);
  22226. return {
  22227. x: -dy / l,
  22228. y: dx / l
  22229. };
  22230. };
  22231. var edgeDistances = edge.pstyle('edge-distances').value;
  22232. switch (edgeDistances) {
  22233. case 'node-position':
  22234. midptPts = posPts;
  22235. break;
  22236. case 'intersection':
  22237. midptPts = intersectionPts;
  22238. break;
  22239. case 'endpoints':
  22240. {
  22241. if (haveManualEndPts) {
  22242. var _this$manualEndptToPx = this.manualEndptToPx(edge.source()[0], srcManEndpt),
  22243. _this$manualEndptToPx2 = _slicedToArray(_this$manualEndptToPx, 2),
  22244. x1 = _this$manualEndptToPx2[0],
  22245. y1 = _this$manualEndptToPx2[1];
  22246. var _this$manualEndptToPx3 = this.manualEndptToPx(edge.target()[0], tgtManEndpt),
  22247. _this$manualEndptToPx4 = _slicedToArray(_this$manualEndptToPx3, 2),
  22248. x2 = _this$manualEndptToPx4[0],
  22249. y2 = _this$manualEndptToPx4[1];
  22250. var endPts = {
  22251. x1: x1,
  22252. y1: y1,
  22253. x2: x2,
  22254. y2: y2
  22255. };
  22256. vectorNormInverse = recalcVectorNormInverse(x1, y1, x2, y2);
  22257. midptPts = endPts;
  22258. } else {
  22259. warn("Edge ".concat(edge.id(), " has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint. Falling back on edge-distances:intersection (default)."));
  22260. midptPts = intersectionPts; // back to default
  22261. }
  22262. break;
  22263. }
  22264. }
  22265. return {
  22266. midptPts: midptPts,
  22267. vectorNormInverse: vectorNormInverse
  22268. };
  22269. };
  22270. BRp$c.findHaystackPoints = function (edges) {
  22271. for (var i = 0; i < edges.length; i++) {
  22272. var edge = edges[i];
  22273. var _p = edge._private;
  22274. var rs = _p.rscratch;
  22275. if (!rs.haystack) {
  22276. var angle = Math.random() * 2 * Math.PI;
  22277. rs.source = {
  22278. x: Math.cos(angle),
  22279. y: Math.sin(angle)
  22280. };
  22281. angle = Math.random() * 2 * Math.PI;
  22282. rs.target = {
  22283. x: Math.cos(angle),
  22284. y: Math.sin(angle)
  22285. };
  22286. }
  22287. var src = _p.source;
  22288. var tgt = _p.target;
  22289. var srcPos = src.position();
  22290. var tgtPos = tgt.position();
  22291. var srcW = src.width();
  22292. var tgtW = tgt.width();
  22293. var srcH = src.height();
  22294. var tgtH = tgt.height();
  22295. var radius = edge.pstyle('haystack-radius').value;
  22296. var halfRadius = radius / 2; // b/c have to half width/height
  22297. rs.haystackPts = rs.allpts = [rs.source.x * srcW * halfRadius + srcPos.x, rs.source.y * srcH * halfRadius + srcPos.y, rs.target.x * tgtW * halfRadius + tgtPos.x, rs.target.y * tgtH * halfRadius + tgtPos.y];
  22298. rs.midX = (rs.allpts[0] + rs.allpts[2]) / 2;
  22299. rs.midY = (rs.allpts[1] + rs.allpts[3]) / 2;
  22300. // always override as haystack in case set to different type previously
  22301. rs.edgeType = 'haystack';
  22302. rs.haystack = true;
  22303. this.storeEdgeProjections(edge);
  22304. this.calculateArrowAngles(edge);
  22305. this.recalculateEdgeLabelProjections(edge);
  22306. this.calculateLabelAngles(edge);
  22307. }
  22308. };
  22309. BRp$c.findSegmentsPoints = function (edge, pairInfo) {
  22310. // Segments (multiple straight lines)
  22311. var rs = edge._private.rscratch;
  22312. var segmentWs = edge.pstyle('segment-weights');
  22313. var segmentDs = edge.pstyle('segment-distances');
  22314. var segmentRs = edge.pstyle('segment-radii');
  22315. var segmentTs = edge.pstyle('radius-type');
  22316. var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);
  22317. var lastRadius = segmentRs.pfValue[segmentRs.pfValue.length - 1];
  22318. var lastRadiusType = segmentTs.pfValue[segmentTs.pfValue.length - 1];
  22319. rs.edgeType = 'segments';
  22320. rs.segpts = [];
  22321. rs.radii = [];
  22322. rs.isArcRadius = [];
  22323. for (var s = 0; s < segmentsN; s++) {
  22324. var w = segmentWs.pfValue[s];
  22325. var d = segmentDs.pfValue[s];
  22326. var w1 = 1 - w;
  22327. var w2 = w;
  22328. var _this$findMidptPtsEtc = this.findMidptPtsEtc(edge, pairInfo),
  22329. midptPts = _this$findMidptPtsEtc.midptPts,
  22330. vectorNormInverse = _this$findMidptPtsEtc.vectorNormInverse;
  22331. var adjustedMidpt = {
  22332. x: midptPts.x1 * w1 + midptPts.x2 * w2,
  22333. y: midptPts.y1 * w1 + midptPts.y2 * w2
  22334. };
  22335. rs.segpts.push(adjustedMidpt.x + vectorNormInverse.x * d, adjustedMidpt.y + vectorNormInverse.y * d);
  22336. rs.radii.push(segmentRs.pfValue[s] !== undefined ? segmentRs.pfValue[s] : lastRadius);
  22337. rs.isArcRadius.push((segmentTs.pfValue[s] !== undefined ? segmentTs.pfValue[s] : lastRadiusType) === 'arc-radius');
  22338. }
  22339. };
  22340. BRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  22341. // Self-edge
  22342. var rs = edge._private.rscratch;
  22343. var dirCounts = pairInfo.dirCounts,
  22344. srcPos = pairInfo.srcPos;
  22345. var ctrlptDists = edge.pstyle('control-point-distances');
  22346. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22347. var loopDir = edge.pstyle('loop-direction').pfValue;
  22348. var loopSwp = edge.pstyle('loop-sweep').pfValue;
  22349. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22350. rs.edgeType = 'self';
  22351. var j = i;
  22352. var loopDist = stepSize;
  22353. if (edgeIsUnbundled) {
  22354. j = 0;
  22355. loopDist = ctrlptDist;
  22356. }
  22357. var loopAngle = loopDir - Math.PI / 2;
  22358. var outAngle = loopAngle - loopSwp / 2;
  22359. var inAngle = loopAngle + loopSwp / 2;
  22360. // increase by step size for overlapping loops, keyed on direction and sweep values
  22361. var dc = String(loopDir + '_' + loopSwp);
  22362. j = dirCounts[dc] === undefined ? dirCounts[dc] = 0 : ++dirCounts[dc];
  22363. rs.ctrlpts = [srcPos.x + Math.cos(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(outAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.x + Math.cos(inAngle) * 1.4 * loopDist * (j / 3 + 1), srcPos.y + Math.sin(inAngle) * 1.4 * loopDist * (j / 3 + 1)];
  22364. };
  22365. BRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  22366. // Compound edge
  22367. var rs = edge._private.rscratch;
  22368. rs.edgeType = 'compound';
  22369. var srcPos = pairInfo.srcPos,
  22370. tgtPos = pairInfo.tgtPos,
  22371. srcW = pairInfo.srcW,
  22372. srcH = pairInfo.srcH,
  22373. tgtW = pairInfo.tgtW,
  22374. tgtH = pairInfo.tgtH;
  22375. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22376. var ctrlptDists = edge.pstyle('control-point-distances');
  22377. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22378. var j = i;
  22379. var loopDist = stepSize;
  22380. if (edgeIsUnbundled) {
  22381. j = 0;
  22382. loopDist = ctrlptDist;
  22383. }
  22384. var loopW = 50;
  22385. var loopaPos = {
  22386. x: srcPos.x - srcW / 2,
  22387. y: srcPos.y - srcH / 2
  22388. };
  22389. var loopbPos = {
  22390. x: tgtPos.x - tgtW / 2,
  22391. y: tgtPos.y - tgtH / 2
  22392. };
  22393. var loopPos = {
  22394. x: Math.min(loopaPos.x, loopbPos.x),
  22395. y: Math.min(loopaPos.y, loopbPos.y)
  22396. };
  22397. // avoids cases with impossible beziers
  22398. var minCompoundStretch = 0.5;
  22399. var compoundStretchA = Math.max(minCompoundStretch, Math.log(srcW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22400. var compoundStretchB = Math.max(minCompoundStretch, Math.log(tgtW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22401. rs.ctrlpts = [loopPos.x, loopPos.y - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchA, loopPos.x - (1 + Math.pow(loopW, 1.12) / 100) * loopDist * (j / 3 + 1) * compoundStretchB, loopPos.y];
  22402. };
  22403. BRp$c.findStraightEdgePoints = function (edge) {
  22404. // Straight edge within bundle
  22405. edge._private.rscratch.edgeType = 'straight';
  22406. };
  22407. BRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {
  22408. var rs = edge._private.rscratch;
  22409. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22410. var ctrlptDists = edge.pstyle('control-point-distances');
  22411. var ctrlptWs = edge.pstyle('control-point-weights');
  22412. var bezierN = ctrlptDists && ctrlptWs ? Math.min(ctrlptDists.value.length, ctrlptWs.value.length) : 1;
  22413. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22414. var ctrlptWeight = ctrlptWs.value[0];
  22415. // (Multi)bezier
  22416. var multi = edgeIsUnbundled;
  22417. rs.edgeType = multi ? 'multibezier' : 'bezier';
  22418. rs.ctrlpts = [];
  22419. for (var b = 0; b < bezierN; b++) {
  22420. var normctrlptDist = (0.5 - pairInfo.eles.length / 2 + i) * stepSize * (edgeIsSwapped ? -1 : 1);
  22421. var manctrlptDist = undefined;
  22422. var sign = signum(normctrlptDist);
  22423. if (multi) {
  22424. ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size
  22425. ctrlptWeight = ctrlptWs.value[b];
  22426. }
  22427. if (edgeIsUnbundled) {
  22428. // multi or single unbundled
  22429. manctrlptDist = ctrlptDist;
  22430. } else {
  22431. manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;
  22432. }
  22433. var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;
  22434. var w1 = 1 - ctrlptWeight;
  22435. var w2 = ctrlptWeight;
  22436. var _this$findMidptPtsEtc2 = this.findMidptPtsEtc(edge, pairInfo),
  22437. midptPts = _this$findMidptPtsEtc2.midptPts,
  22438. vectorNormInverse = _this$findMidptPtsEtc2.vectorNormInverse;
  22439. var adjustedMidpt = {
  22440. x: midptPts.x1 * w1 + midptPts.x2 * w2,
  22441. y: midptPts.y1 * w1 + midptPts.y2 * w2
  22442. };
  22443. rs.ctrlpts.push(adjustedMidpt.x + vectorNormInverse.x * distanceFromMidpoint, adjustedMidpt.y + vectorNormInverse.y * distanceFromMidpoint);
  22444. }
  22445. };
  22446. BRp$c.findTaxiPoints = function (edge, pairInfo) {
  22447. // Taxicab geometry with two turns maximum
  22448. var rs = edge._private.rscratch;
  22449. rs.edgeType = 'segments';
  22450. var VERTICAL = 'vertical';
  22451. var HORIZONTAL = 'horizontal';
  22452. var LEFTWARD = 'leftward';
  22453. var RIGHTWARD = 'rightward';
  22454. var DOWNWARD = 'downward';
  22455. var UPWARD = 'upward';
  22456. var AUTO = 'auto';
  22457. var posPts = pairInfo.posPts,
  22458. srcW = pairInfo.srcW,
  22459. srcH = pairInfo.srcH,
  22460. tgtW = pairInfo.tgtW,
  22461. tgtH = pairInfo.tgtH;
  22462. var edgeDistances = edge.pstyle('edge-distances').value;
  22463. var dIncludesNodeBody = edgeDistances !== 'node-position';
  22464. var taxiDir = edge.pstyle('taxi-direction').value;
  22465. var rawTaxiDir = taxiDir; // unprocessed value
  22466. var taxiTurn = edge.pstyle('taxi-turn');
  22467. var turnIsPercent = taxiTurn.units === '%';
  22468. var taxiTurnPfVal = taxiTurn.pfValue;
  22469. var turnIsNegative = taxiTurnPfVal < 0; // i.e. from target side
  22470. var minD = edge.pstyle('taxi-turn-min-distance').pfValue;
  22471. var dw = dIncludesNodeBody ? (srcW + tgtW) / 2 : 0;
  22472. var dh = dIncludesNodeBody ? (srcH + tgtH) / 2 : 0;
  22473. var pdx = posPts.x2 - posPts.x1;
  22474. var pdy = posPts.y2 - posPts.y1;
  22475. // take away the effective w/h from the magnitude of the delta value
  22476. var subDWH = function subDWH(dxy, dwh) {
  22477. if (dxy > 0) {
  22478. return Math.max(dxy - dwh, 0);
  22479. } else {
  22480. return Math.min(dxy + dwh, 0);
  22481. }
  22482. };
  22483. var dx = subDWH(pdx, dw);
  22484. var dy = subDWH(pdy, dh);
  22485. var isExplicitDir = false;
  22486. if (rawTaxiDir === AUTO) {
  22487. taxiDir = Math.abs(dx) > Math.abs(dy) ? HORIZONTAL : VERTICAL;
  22488. } else if (rawTaxiDir === UPWARD || rawTaxiDir === DOWNWARD) {
  22489. taxiDir = VERTICAL;
  22490. isExplicitDir = true;
  22491. } else if (rawTaxiDir === LEFTWARD || rawTaxiDir === RIGHTWARD) {
  22492. taxiDir = HORIZONTAL;
  22493. isExplicitDir = true;
  22494. }
  22495. var isVert = taxiDir === VERTICAL;
  22496. var l = isVert ? dy : dx;
  22497. var pl = isVert ? pdy : pdx;
  22498. var sgnL = signum(pl);
  22499. var forcedDir = false;
  22500. if (!(isExplicitDir && (turnIsPercent || turnIsNegative)) // forcing in this case would cause weird growing in the opposite direction
  22501. && (rawTaxiDir === DOWNWARD && pl < 0 || rawTaxiDir === UPWARD && pl > 0 || rawTaxiDir === LEFTWARD && pl > 0 || rawTaxiDir === RIGHTWARD && pl < 0)) {
  22502. sgnL *= -1;
  22503. l = sgnL * Math.abs(l);
  22504. forcedDir = true;
  22505. }
  22506. var d;
  22507. if (turnIsPercent) {
  22508. var p = taxiTurnPfVal < 0 ? 1 + taxiTurnPfVal : taxiTurnPfVal;
  22509. d = p * l;
  22510. } else {
  22511. var k = taxiTurnPfVal < 0 ? l : 0;
  22512. d = k + taxiTurnPfVal * sgnL;
  22513. }
  22514. var getIsTooClose = function getIsTooClose(d) {
  22515. return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);
  22516. };
  22517. var isTooCloseSrc = getIsTooClose(d);
  22518. var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));
  22519. var isTooClose = isTooCloseSrc || isTooCloseTgt;
  22520. if (isTooClose && !forcedDir) {
  22521. // non-ideal routing
  22522. if (isVert) {
  22523. // vertical fallbacks
  22524. var lShapeInsideSrc = Math.abs(pl) <= srcH / 2;
  22525. var lShapeInsideTgt = Math.abs(pdx) <= tgtW / 2;
  22526. if (lShapeInsideSrc) {
  22527. // horizontal Z-shape (direction not respected)
  22528. var x = (posPts.x1 + posPts.x2) / 2;
  22529. var y1 = posPts.y1,
  22530. y2 = posPts.y2;
  22531. rs.segpts = [x, y1, x, y2];
  22532. } else if (lShapeInsideTgt) {
  22533. // vertical Z-shape (distance not respected)
  22534. var y = (posPts.y1 + posPts.y2) / 2;
  22535. var x1 = posPts.x1,
  22536. x2 = posPts.x2;
  22537. rs.segpts = [x1, y, x2, y];
  22538. } else {
  22539. // L-shape fallback (turn distance not respected, but works well with tree siblings)
  22540. rs.segpts = [posPts.x1, posPts.y2];
  22541. }
  22542. } else {
  22543. // horizontal fallbacks
  22544. var _lShapeInsideSrc = Math.abs(pl) <= srcW / 2;
  22545. var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;
  22546. if (_lShapeInsideSrc) {
  22547. // vertical Z-shape (direction not respected)
  22548. var _y = (posPts.y1 + posPts.y2) / 2;
  22549. var _x = posPts.x1,
  22550. _x2 = posPts.x2;
  22551. rs.segpts = [_x, _y, _x2, _y];
  22552. } else if (_lShapeInsideTgt) {
  22553. // horizontal Z-shape (turn distance not respected)
  22554. var _x3 = (posPts.x1 + posPts.x2) / 2;
  22555. var _y2 = posPts.y1,
  22556. _y3 = posPts.y2;
  22557. rs.segpts = [_x3, _y2, _x3, _y3];
  22558. } else {
  22559. // L-shape (turn distance not respected, but works well for tree siblings)
  22560. rs.segpts = [posPts.x2, posPts.y1];
  22561. }
  22562. }
  22563. } else {
  22564. // ideal routing
  22565. if (isVert) {
  22566. var _y4 = posPts.y1 + d + (dIncludesNodeBody ? srcH / 2 * sgnL : 0);
  22567. var _x4 = posPts.x1,
  22568. _x5 = posPts.x2;
  22569. rs.segpts = [_x4, _y4, _x5, _y4];
  22570. } else {
  22571. // horizontal
  22572. var _x6 = posPts.x1 + d + (dIncludesNodeBody ? srcW / 2 * sgnL : 0);
  22573. var _y5 = posPts.y1,
  22574. _y6 = posPts.y2;
  22575. rs.segpts = [_x6, _y5, _x6, _y6];
  22576. }
  22577. }
  22578. if (rs.isRound) {
  22579. var radius = edge.pstyle('taxi-radius').value;
  22580. var isArcRadius = edge.pstyle('radius-type').value[0] === 'arc-radius';
  22581. rs.radii = new Array(rs.segpts.length / 2).fill(radius);
  22582. rs.isArcRadius = new Array(rs.segpts.length / 2).fill(isArcRadius);
  22583. }
  22584. };
  22585. BRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {
  22586. var rs = edge._private.rscratch;
  22587. // can only correct beziers for now...
  22588. if (rs.edgeType === 'bezier') {
  22589. var srcPos = pairInfo.srcPos,
  22590. tgtPos = pairInfo.tgtPos,
  22591. srcW = pairInfo.srcW,
  22592. srcH = pairInfo.srcH,
  22593. tgtW = pairInfo.tgtW,
  22594. tgtH = pairInfo.tgtH,
  22595. srcShape = pairInfo.srcShape,
  22596. tgtShape = pairInfo.tgtShape,
  22597. srcCornerRadius = pairInfo.srcCornerRadius,
  22598. tgtCornerRadius = pairInfo.tgtCornerRadius,
  22599. srcRs = pairInfo.srcRs,
  22600. tgtRs = pairInfo.tgtRs;
  22601. var badStart = !number$1(rs.startX) || !number$1(rs.startY);
  22602. var badAStart = !number$1(rs.arrowStartX) || !number$1(rs.arrowStartY);
  22603. var badEnd = !number$1(rs.endX) || !number$1(rs.endY);
  22604. var badAEnd = !number$1(rs.arrowEndX) || !number$1(rs.arrowEndY);
  22605. var minCpADistFactor = 3;
  22606. var arrowW = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
  22607. var minCpADist = minCpADistFactor * arrowW;
  22608. var startACpDist = dist({
  22609. x: rs.ctrlpts[0],
  22610. y: rs.ctrlpts[1]
  22611. }, {
  22612. x: rs.startX,
  22613. y: rs.startY
  22614. });
  22615. var closeStartACp = startACpDist < minCpADist;
  22616. var endACpDist = dist({
  22617. x: rs.ctrlpts[0],
  22618. y: rs.ctrlpts[1]
  22619. }, {
  22620. x: rs.endX,
  22621. y: rs.endY
  22622. });
  22623. var closeEndACp = endACpDist < minCpADist;
  22624. var overlapping = false;
  22625. if (badStart || badAStart || closeStartACp) {
  22626. overlapping = true;
  22627. // project control point along line from src centre to outside the src shape
  22628. // (otherwise intersection will yield nothing)
  22629. var cpD = {
  22630. // delta
  22631. x: rs.ctrlpts[0] - srcPos.x,
  22632. y: rs.ctrlpts[1] - srcPos.y
  22633. };
  22634. var cpL = Math.sqrt(cpD.x * cpD.x + cpD.y * cpD.y); // length of line
  22635. var cpM = {
  22636. // normalised delta
  22637. x: cpD.x / cpL,
  22638. y: cpD.y / cpL
  22639. };
  22640. var radius = Math.max(srcW, srcH);
  22641. var cpProj = {
  22642. // *2 radius guarantees outside shape
  22643. x: rs.ctrlpts[0] + cpM.x * 2 * radius,
  22644. y: rs.ctrlpts[1] + cpM.y * 2 * radius
  22645. };
  22646. var srcCtrlPtIntn = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, cpProj.x, cpProj.y, 0, srcCornerRadius, srcRs);
  22647. if (closeStartACp) {
  22648. rs.ctrlpts[0] = rs.ctrlpts[0] + cpM.x * (minCpADist - startACpDist);
  22649. rs.ctrlpts[1] = rs.ctrlpts[1] + cpM.y * (minCpADist - startACpDist);
  22650. } else {
  22651. rs.ctrlpts[0] = srcCtrlPtIntn[0] + cpM.x * minCpADist;
  22652. rs.ctrlpts[1] = srcCtrlPtIntn[1] + cpM.y * minCpADist;
  22653. }
  22654. }
  22655. if (badEnd || badAEnd || closeEndACp) {
  22656. overlapping = true;
  22657. // project control point along line from tgt centre to outside the tgt shape
  22658. // (otherwise intersection will yield nothing)
  22659. var _cpD = {
  22660. // delta
  22661. x: rs.ctrlpts[0] - tgtPos.x,
  22662. y: rs.ctrlpts[1] - tgtPos.y
  22663. };
  22664. var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line
  22665. var _cpM = {
  22666. // normalised delta
  22667. x: _cpD.x / _cpL,
  22668. y: _cpD.y / _cpL
  22669. };
  22670. var _radius = Math.max(srcW, srcH);
  22671. var _cpProj = {
  22672. // *2 radius guarantees outside shape
  22673. x: rs.ctrlpts[0] + _cpM.x * 2 * _radius,
  22674. y: rs.ctrlpts[1] + _cpM.y * 2 * _radius
  22675. };
  22676. var tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0, tgtCornerRadius, tgtRs);
  22677. if (closeEndACp) {
  22678. rs.ctrlpts[0] = rs.ctrlpts[0] + _cpM.x * (minCpADist - endACpDist);
  22679. rs.ctrlpts[1] = rs.ctrlpts[1] + _cpM.y * (minCpADist - endACpDist);
  22680. } else {
  22681. rs.ctrlpts[0] = tgtCtrlPtIntn[0] + _cpM.x * minCpADist;
  22682. rs.ctrlpts[1] = tgtCtrlPtIntn[1] + _cpM.y * minCpADist;
  22683. }
  22684. }
  22685. if (overlapping) {
  22686. // recalc endpts
  22687. this.findEndpoints(edge);
  22688. }
  22689. }
  22690. };
  22691. BRp$c.storeAllpts = function (edge) {
  22692. var rs = edge._private.rscratch;
  22693. if (rs.edgeType === 'multibezier' || rs.edgeType === 'bezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
  22694. rs.allpts = [];
  22695. rs.allpts.push(rs.startX, rs.startY);
  22696. for (var b = 0; b + 1 < rs.ctrlpts.length; b += 2) {
  22697. // ctrl pt itself
  22698. rs.allpts.push(rs.ctrlpts[b], rs.ctrlpts[b + 1]);
  22699. // the midpt between ctrlpts as intermediate destination pts
  22700. if (b + 3 < rs.ctrlpts.length) {
  22701. rs.allpts.push((rs.ctrlpts[b] + rs.ctrlpts[b + 2]) / 2, (rs.ctrlpts[b + 1] + rs.ctrlpts[b + 3]) / 2);
  22702. }
  22703. }
  22704. rs.allpts.push(rs.endX, rs.endY);
  22705. var m, mt;
  22706. if (rs.ctrlpts.length / 2 % 2 === 0) {
  22707. m = rs.allpts.length / 2 - 1;
  22708. rs.midX = rs.allpts[m];
  22709. rs.midY = rs.allpts[m + 1];
  22710. } else {
  22711. m = rs.allpts.length / 2 - 3;
  22712. mt = 0.5;
  22713. rs.midX = qbezierAt(rs.allpts[m], rs.allpts[m + 2], rs.allpts[m + 4], mt);
  22714. rs.midY = qbezierAt(rs.allpts[m + 1], rs.allpts[m + 3], rs.allpts[m + 5], mt);
  22715. }
  22716. } else if (rs.edgeType === 'straight') {
  22717. // need to calc these after endpts
  22718. rs.allpts = [rs.startX, rs.startY, rs.endX, rs.endY];
  22719. // default midpt for labels etc
  22720. rs.midX = (rs.startX + rs.endX + rs.arrowStartX + rs.arrowEndX) / 4;
  22721. rs.midY = (rs.startY + rs.endY + rs.arrowStartY + rs.arrowEndY) / 4;
  22722. } else if (rs.edgeType === 'segments') {
  22723. rs.allpts = [];
  22724. rs.allpts.push(rs.startX, rs.startY);
  22725. rs.allpts.push.apply(rs.allpts, rs.segpts);
  22726. rs.allpts.push(rs.endX, rs.endY);
  22727. if (rs.isRound) {
  22728. rs.roundCorners = [];
  22729. for (var i = 2; i + 3 < rs.allpts.length; i += 2) {
  22730. var radius = rs.radii[i / 2 - 1];
  22731. var isArcRadius = rs.isArcRadius[i / 2 - 1];
  22732. rs.roundCorners.push(getRoundCorner({
  22733. x: rs.allpts[i - 2],
  22734. y: rs.allpts[i - 1]
  22735. }, {
  22736. x: rs.allpts[i],
  22737. y: rs.allpts[i + 1],
  22738. radius: radius
  22739. }, {
  22740. x: rs.allpts[i + 2],
  22741. y: rs.allpts[i + 3]
  22742. }, radius, isArcRadius));
  22743. }
  22744. }
  22745. if (rs.segpts.length % 4 === 0) {
  22746. var i2 = rs.segpts.length / 2;
  22747. var i1 = i2 - 2;
  22748. rs.midX = (rs.segpts[i1] + rs.segpts[i2]) / 2;
  22749. rs.midY = (rs.segpts[i1 + 1] + rs.segpts[i2 + 1]) / 2;
  22750. } else {
  22751. var _i = rs.segpts.length / 2 - 1;
  22752. if (!rs.isRound) {
  22753. rs.midX = rs.segpts[_i];
  22754. rs.midY = rs.segpts[_i + 1];
  22755. } else {
  22756. var point = {
  22757. x: rs.segpts[_i],
  22758. y: rs.segpts[_i + 1]
  22759. };
  22760. var corner = rs.roundCorners[_i / 2];
  22761. if (corner.radius === 0) {
  22762. // On collinear points
  22763. var nextPoint = {
  22764. x: rs.segpts[_i + 2],
  22765. y: rs.segpts[_i + 3]
  22766. };
  22767. rs.midX = point.x;
  22768. rs.midY = point.y;
  22769. rs.midVector = [point.y - nextPoint.y, nextPoint.x - point.x];
  22770. } else {
  22771. // On rounded points
  22772. var v = [point.x - corner.cx, point.y - corner.cy];
  22773. var factor = corner.radius / Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));
  22774. v = v.map(function (c) {
  22775. return c * factor;
  22776. });
  22777. rs.midX = corner.cx + v[0];
  22778. rs.midY = corner.cy + v[1];
  22779. rs.midVector = v;
  22780. }
  22781. }
  22782. }
  22783. }
  22784. };
  22785. BRp$c.checkForInvalidEdgeWarning = function (edge) {
  22786. var rs = edge[0]._private.rscratch;
  22787. if (rs.nodesOverlap || number$1(rs.startX) && number$1(rs.startY) && number$1(rs.endX) && number$1(rs.endY)) {
  22788. rs.loggedErr = false;
  22789. } else {
  22790. if (!rs.loggedErr) {
  22791. rs.loggedErr = true;
  22792. warn('Edge `' + edge.id() + '` has invalid endpoints and so it is impossible to draw. Adjust your edge style (e.g. control points) accordingly or use an alternative edge type. This is expected behaviour when the source node and the target node overlap.');
  22793. }
  22794. }
  22795. };
  22796. BRp$c.findEdgeControlPoints = function (edges) {
  22797. var _this = this;
  22798. if (!edges || edges.length === 0) {
  22799. return;
  22800. }
  22801. var r = this;
  22802. var cy = r.cy;
  22803. var hasCompounds = cy.hasCompoundNodes();
  22804. var hashTable = new Map$1();
  22805. var getKey = function getKey(pairId, edgeIsUnbundled) {
  22806. return [].concat(_toConsumableArray(pairId), [edgeIsUnbundled ? 1 : 0]).join('-');
  22807. };
  22808. var pairIds = [];
  22809. var haystackEdges = [];
  22810. // create a table of edge (src, tgt) => list of edges between them
  22811. for (var i = 0; i < edges.length; i++) {
  22812. var edge = edges[i];
  22813. var _p = edge._private;
  22814. var curveStyle = edge.pstyle('curve-style').value;
  22815. // ignore edges who are not to be displayed
  22816. // they shouldn't take up space
  22817. if (edge.removed() || !edge.takesUpSpace()) {
  22818. continue;
  22819. }
  22820. if (curveStyle === 'haystack') {
  22821. haystackEdges.push(edge);
  22822. continue;
  22823. }
  22824. var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || curveStyle === 'straight' || curveStyle === 'straight-triangle' || endsWith(curveStyle, 'taxi');
  22825. var edgeIsBezier = curveStyle === 'unbundled-bezier' || curveStyle === 'bezier';
  22826. var src = _p.source;
  22827. var tgt = _p.target;
  22828. var srcIndex = src.poolIndex();
  22829. var tgtIndex = tgt.poolIndex();
  22830. var pairId = [srcIndex, tgtIndex].sort();
  22831. var key = getKey(pairId, edgeIsUnbundled);
  22832. var tableEntry = hashTable.get(key);
  22833. if (tableEntry == null) {
  22834. tableEntry = {
  22835. eles: []
  22836. };
  22837. pairIds.push({
  22838. pairId: pairId,
  22839. edgeIsUnbundled: edgeIsUnbundled
  22840. });
  22841. hashTable.set(key, tableEntry);
  22842. }
  22843. tableEntry.eles.push(edge);
  22844. if (edgeIsUnbundled) {
  22845. tableEntry.hasUnbundled = true;
  22846. }
  22847. if (edgeIsBezier) {
  22848. tableEntry.hasBezier = true;
  22849. }
  22850. }
  22851. // for each pair (src, tgt), create the ctrl pts
  22852. // Nested for loop is OK; total number of iterations for both loops = edgeCount
  22853. var _loop = function _loop() {
  22854. var _pairIds$p = pairIds[p],
  22855. pairId = _pairIds$p.pairId,
  22856. edgeIsUnbundled = _pairIds$p.edgeIsUnbundled;
  22857. var key = getKey(pairId, edgeIsUnbundled);
  22858. var pairInfo = hashTable.get(key);
  22859. var swappedpairInfo;
  22860. if (!pairInfo.hasUnbundled) {
  22861. var pllEdges = pairInfo.eles[0].parallelEdges().filter(function (e) {
  22862. return e.isBundledBezier();
  22863. });
  22864. clearArray(pairInfo.eles);
  22865. pllEdges.forEach(function (edge) {
  22866. return pairInfo.eles.push(edge);
  22867. });
  22868. // for each pair id, the edges should be sorted by index
  22869. pairInfo.eles.sort(function (edge1, edge2) {
  22870. return edge1.poolIndex() - edge2.poolIndex();
  22871. });
  22872. }
  22873. var firstEdge = pairInfo.eles[0];
  22874. var src = firstEdge.source();
  22875. var tgt = firstEdge.target();
  22876. // make sure src/tgt distinction is consistent w.r.t. pairId
  22877. if (src.poolIndex() > tgt.poolIndex()) {
  22878. var temp = src;
  22879. src = tgt;
  22880. tgt = temp;
  22881. }
  22882. var srcPos = pairInfo.srcPos = src.position();
  22883. var tgtPos = pairInfo.tgtPos = tgt.position();
  22884. var srcW = pairInfo.srcW = src.outerWidth();
  22885. var srcH = pairInfo.srcH = src.outerHeight();
  22886. var tgtW = pairInfo.tgtW = tgt.outerWidth();
  22887. var tgtH = pairInfo.tgtH = tgt.outerHeight();
  22888. var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];
  22889. var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];
  22890. var srcCornerRadius = pairInfo.srcCornerRadius = src.pstyle('corner-radius').value === 'auto' ? 'auto' : src.pstyle('corner-radius').pfValue;
  22891. var tgtCornerRadius = pairInfo.tgtCornerRadius = tgt.pstyle('corner-radius').value === 'auto' ? 'auto' : tgt.pstyle('corner-radius').pfValue;
  22892. var tgtRs = pairInfo.tgtRs = tgt._private.rscratch;
  22893. var srcRs = pairInfo.srcRs = src._private.rscratch;
  22894. pairInfo.dirCounts = {
  22895. 'north': 0,
  22896. 'west': 0,
  22897. 'south': 0,
  22898. 'east': 0,
  22899. 'northwest': 0,
  22900. 'southwest': 0,
  22901. 'northeast': 0,
  22902. 'southeast': 0
  22903. };
  22904. for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {
  22905. var _edge = pairInfo.eles[_i2];
  22906. var rs = _edge[0]._private.rscratch;
  22907. var _curveStyle = _edge.pstyle('curve-style').value;
  22908. var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || endsWith(_curveStyle, 'segments') || endsWith(_curveStyle, 'taxi');
  22909. // whether the normalised pair order is the reverse of the edge's src-tgt order
  22910. var edgeIsSwapped = !src.same(_edge.source());
  22911. if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {
  22912. pairInfo.calculatedIntersection = true;
  22913. // pt outside src shape to calc distance/displacement from src to tgt
  22914. var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0, srcCornerRadius, srcRs);
  22915. var srcIntn = pairInfo.srcIntn = srcOutside;
  22916. // pt outside tgt shape to calc distance/displacement from src to tgt
  22917. var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0, tgtCornerRadius, tgtRs);
  22918. var tgtIntn = pairInfo.tgtIntn = tgtOutside;
  22919. var intersectionPts = pairInfo.intersectionPts = {
  22920. x1: srcOutside[0],
  22921. x2: tgtOutside[0],
  22922. y1: srcOutside[1],
  22923. y2: tgtOutside[1]
  22924. };
  22925. var posPts = pairInfo.posPts = {
  22926. x1: srcPos.x,
  22927. x2: tgtPos.x,
  22928. y1: srcPos.y,
  22929. y2: tgtPos.y
  22930. };
  22931. var dy = tgtOutside[1] - srcOutside[1];
  22932. var dx = tgtOutside[0] - srcOutside[0];
  22933. var l = Math.sqrt(dx * dx + dy * dy);
  22934. if (number$1(l) && l >= AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L) ; else {
  22935. l = Math.sqrt(Math.max(dx * dx, AVOID_IMPOSSIBLE_BEZIER_CONSTANT) + Math.max(dy * dy, AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22936. }
  22937. var vector = pairInfo.vector = {
  22938. x: dx,
  22939. y: dy
  22940. };
  22941. var vectorNorm = pairInfo.vectorNorm = {
  22942. x: vector.x / l,
  22943. y: vector.y / l
  22944. };
  22945. var vectorNormInverse = {
  22946. x: -vectorNorm.y,
  22947. y: vectorNorm.x
  22948. };
  22949. // if node shapes overlap, then no ctrl pts to draw
  22950. pairInfo.nodesOverlap = !number$1(l) || tgtShape.checkPoint(srcOutside[0], srcOutside[1], 0, tgtW, tgtH, tgtPos.x, tgtPos.y, tgtCornerRadius, tgtRs) || srcShape.checkPoint(tgtOutside[0], tgtOutside[1], 0, srcW, srcH, srcPos.x, srcPos.y, srcCornerRadius, srcRs);
  22951. pairInfo.vectorNormInverse = vectorNormInverse;
  22952. swappedpairInfo = {
  22953. nodesOverlap: pairInfo.nodesOverlap,
  22954. dirCounts: pairInfo.dirCounts,
  22955. calculatedIntersection: true,
  22956. hasBezier: pairInfo.hasBezier,
  22957. hasUnbundled: pairInfo.hasUnbundled,
  22958. eles: pairInfo.eles,
  22959. srcPos: tgtPos,
  22960. srcRs: tgtRs,
  22961. tgtPos: srcPos,
  22962. tgtRs: srcRs,
  22963. srcW: tgtW,
  22964. srcH: tgtH,
  22965. tgtW: srcW,
  22966. tgtH: srcH,
  22967. srcIntn: tgtIntn,
  22968. tgtIntn: srcIntn,
  22969. srcShape: tgtShape,
  22970. tgtShape: srcShape,
  22971. posPts: {
  22972. x1: posPts.x2,
  22973. y1: posPts.y2,
  22974. x2: posPts.x1,
  22975. y2: posPts.y1
  22976. },
  22977. intersectionPts: {
  22978. x1: intersectionPts.x2,
  22979. y1: intersectionPts.y2,
  22980. x2: intersectionPts.x1,
  22981. y2: intersectionPts.y1
  22982. },
  22983. vector: {
  22984. x: -vector.x,
  22985. y: -vector.y
  22986. },
  22987. vectorNorm: {
  22988. x: -vectorNorm.x,
  22989. y: -vectorNorm.y
  22990. },
  22991. vectorNormInverse: {
  22992. x: -vectorNormInverse.x,
  22993. y: -vectorNormInverse.y
  22994. }
  22995. };
  22996. }
  22997. var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;
  22998. rs.nodesOverlap = passedPairInfo.nodesOverlap;
  22999. rs.srcIntn = passedPairInfo.srcIntn;
  23000. rs.tgtIntn = passedPairInfo.tgtIntn;
  23001. rs.isRound = _curveStyle.startsWith('round');
  23002. if (hasCompounds && (src.isParent() || src.isChild() || tgt.isParent() || tgt.isChild()) && (src.parents().anySame(tgt) || tgt.parents().anySame(src) || src.same(tgt) && src.isParent())) {
  23003. _this.findCompoundLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
  23004. } else if (src === tgt) {
  23005. _this.findLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
  23006. } else if (_curveStyle.endsWith('segments')) {
  23007. _this.findSegmentsPoints(_edge, passedPairInfo);
  23008. } else if (_curveStyle.endsWith('taxi')) {
  23009. _this.findTaxiPoints(_edge, passedPairInfo);
  23010. } else if (_curveStyle === 'straight' || !_edgeIsUnbundled && pairInfo.eles.length % 2 === 1 && _i2 === Math.floor(pairInfo.eles.length / 2)) {
  23011. _this.findStraightEdgePoints(_edge);
  23012. } else {
  23013. _this.findBezierPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled, edgeIsSwapped);
  23014. }
  23015. _this.findEndpoints(_edge);
  23016. _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);
  23017. _this.checkForInvalidEdgeWarning(_edge);
  23018. _this.storeAllpts(_edge);
  23019. _this.storeEdgeProjections(_edge);
  23020. _this.calculateArrowAngles(_edge);
  23021. _this.recalculateEdgeLabelProjections(_edge);
  23022. _this.calculateLabelAngles(_edge);
  23023. } // for pair edges
  23024. };
  23025. for (var p = 0; p < pairIds.length; p++) {
  23026. _loop();
  23027. } // for pair ids
  23028. // haystacks avoid the expense of pairInfo stuff (intersections etc.)
  23029. this.findHaystackPoints(haystackEdges);
  23030. };
  23031. function getPts(pts) {
  23032. var retPts = [];
  23033. if (pts == null) {
  23034. return;
  23035. }
  23036. for (var i = 0; i < pts.length; i += 2) {
  23037. var x = pts[i];
  23038. var y = pts[i + 1];
  23039. retPts.push({
  23040. x: x,
  23041. y: y
  23042. });
  23043. }
  23044. return retPts;
  23045. }
  23046. BRp$c.getSegmentPoints = function (edge) {
  23047. var rs = edge[0]._private.rscratch;
  23048. this.recalculateRenderedStyle(edge);
  23049. var type = rs.edgeType;
  23050. if (type === 'segments') {
  23051. return getPts(rs.segpts);
  23052. }
  23053. };
  23054. BRp$c.getControlPoints = function (edge) {
  23055. var rs = edge[0]._private.rscratch;
  23056. this.recalculateRenderedStyle(edge);
  23057. var type = rs.edgeType;
  23058. if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {
  23059. return getPts(rs.ctrlpts);
  23060. }
  23061. };
  23062. BRp$c.getEdgeMidpoint = function (edge) {
  23063. var rs = edge[0]._private.rscratch;
  23064. this.recalculateRenderedStyle(edge);
  23065. return {
  23066. x: rs.midX,
  23067. y: rs.midY
  23068. };
  23069. };
  23070. var BRp$b = {};
  23071. BRp$b.manualEndptToPx = function (node, prop) {
  23072. var r = this;
  23073. var npos = node.position();
  23074. var w = node.outerWidth();
  23075. var h = node.outerHeight();
  23076. var rs = node._private.rscratch;
  23077. if (prop.value.length === 2) {
  23078. var p = [prop.pfValue[0], prop.pfValue[1]];
  23079. if (prop.units[0] === '%') {
  23080. p[0] = p[0] * w;
  23081. }
  23082. if (prop.units[1] === '%') {
  23083. p[1] = p[1] * h;
  23084. }
  23085. p[0] += npos.x;
  23086. p[1] += npos.y;
  23087. return p;
  23088. } else {
  23089. var angle = prop.pfValue[0];
  23090. angle = -Math.PI / 2 + angle; // start at 12 o'clock
  23091. var l = 2 * Math.max(w, h);
  23092. var _p = [npos.x + Math.cos(angle) * l, npos.y + Math.sin(angle) * l];
  23093. return r.nodeShapes[this.getNodeShape(node)].intersectLine(npos.x, npos.y, w, h, _p[0], _p[1], 0, node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue, rs);
  23094. }
  23095. };
  23096. BRp$b.findEndpoints = function (edge) {
  23097. var _ref, _tgtManEndpt$pfValue, _ref2, _srcManEndpt$pfValue;
  23098. var r = this;
  23099. var intersect;
  23100. var source = edge.source()[0];
  23101. var target = edge.target()[0];
  23102. var srcPos = source.position();
  23103. var tgtPos = target.position();
  23104. var tgtArShape = edge.pstyle('target-arrow-shape').value;
  23105. var srcArShape = edge.pstyle('source-arrow-shape').value;
  23106. var tgtDist = edge.pstyle('target-distance-from-node').pfValue;
  23107. var srcDist = edge.pstyle('source-distance-from-node').pfValue;
  23108. var srcRs = source._private.rscratch;
  23109. var tgtRs = target._private.rscratch;
  23110. var curveStyle = edge.pstyle('curve-style').value;
  23111. var rs = edge._private.rscratch;
  23112. var et = rs.edgeType;
  23113. var taxi = endsWith(curveStyle, 'taxi'); // Covers taxi and round-taxi
  23114. var self = et === 'self' || et === 'compound';
  23115. var bezier = et === 'bezier' || et === 'multibezier' || self;
  23116. var multi = et !== 'bezier';
  23117. var lines = et === 'straight' || et === 'segments';
  23118. var segments = et === 'segments';
  23119. var hasEndpts = bezier || multi || lines;
  23120. var overrideEndpts = self || taxi;
  23121. var srcManEndpt = edge.pstyle('source-endpoint');
  23122. var srcManEndptVal = overrideEndpts ? 'outside-to-node' : srcManEndpt.value;
  23123. var srcCornerRadius = source.pstyle('corner-radius').value === 'auto' ? 'auto' : source.pstyle('corner-radius').pfValue;
  23124. var tgtManEndpt = edge.pstyle('target-endpoint');
  23125. var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;
  23126. var tgtCornerRadius = target.pstyle('corner-radius').value === 'auto' ? 'auto' : target.pstyle('corner-radius').pfValue;
  23127. rs.srcManEndpt = srcManEndpt;
  23128. rs.tgtManEndpt = tgtManEndpt;
  23129. var p1; // last known point of edge on target side
  23130. var p2; // last known point of edge on source side
  23131. var p1_i; // point to intersect with target shape
  23132. var p2_i; // point to intersect with source shape
  23133. var tgtManEndptPt = (_ref = (tgtManEndpt === null || tgtManEndpt === undefined || (_tgtManEndpt$pfValue = tgtManEndpt.pfValue) === null || _tgtManEndpt$pfValue === undefined ? undefined : _tgtManEndpt$pfValue.length) === 2 ? tgtManEndpt.pfValue : null) !== null && _ref !== undefined ? _ref : [0, 0];
  23134. var srcManEndptPt = (_ref2 = (srcManEndpt === null || srcManEndpt === undefined || (_srcManEndpt$pfValue = srcManEndpt.pfValue) === null || _srcManEndpt$pfValue === undefined ? undefined : _srcManEndpt$pfValue.length) === 2 ? srcManEndpt.pfValue : null) !== null && _ref2 !== undefined ? _ref2 : [0, 0];
  23135. if (bezier) {
  23136. var cpStart = [rs.ctrlpts[0], rs.ctrlpts[1]];
  23137. var cpEnd = multi ? [rs.ctrlpts[rs.ctrlpts.length - 2], rs.ctrlpts[rs.ctrlpts.length - 1]] : cpStart;
  23138. p1 = cpEnd;
  23139. p2 = cpStart;
  23140. } else if (lines) {
  23141. var srcArrowFromPt = !segments ? [tgtPos.x + tgtManEndptPt[0], tgtPos.y + tgtManEndptPt[1]] : rs.segpts.slice(0, 2);
  23142. var tgtArrowFromPt = !segments ? [srcPos.x + srcManEndptPt[0], srcPos.y + srcManEndptPt[1]] : rs.segpts.slice(rs.segpts.length - 2);
  23143. p1 = tgtArrowFromPt;
  23144. p2 = srcArrowFromPt;
  23145. }
  23146. if (tgtManEndptVal === 'inside-to-node') {
  23147. intersect = [tgtPos.x, tgtPos.y];
  23148. } else if (tgtManEndpt.units) {
  23149. intersect = this.manualEndptToPx(target, tgtManEndpt);
  23150. } else if (tgtManEndptVal === 'outside-to-line') {
  23151. intersect = rs.tgtIntn; // use cached value from ctrlpt calc
  23152. } else {
  23153. if (tgtManEndptVal === 'outside-to-node' || tgtManEndptVal === 'outside-to-node-or-label') {
  23154. p1_i = p1;
  23155. } else if (tgtManEndptVal === 'outside-to-line' || tgtManEndptVal === 'outside-to-line-or-label') {
  23156. p1_i = [srcPos.x, srcPos.y];
  23157. }
  23158. intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0, tgtCornerRadius, tgtRs);
  23159. if (tgtManEndptVal === 'outside-to-node-or-label' || tgtManEndptVal === 'outside-to-line-or-label') {
  23160. var trs = target._private.rscratch;
  23161. var lw = trs.labelWidth;
  23162. var lh = trs.labelHeight;
  23163. var lx = trs.labelX;
  23164. var ly = trs.labelY;
  23165. var lw2 = lw / 2;
  23166. var lh2 = lh / 2;
  23167. var va = target.pstyle('text-valign').value;
  23168. if (va === 'top') {
  23169. ly -= lh2;
  23170. } else if (va === 'bottom') {
  23171. ly += lh2;
  23172. }
  23173. var ha = target.pstyle('text-halign').value;
  23174. if (ha === 'left') {
  23175. lx -= lw2;
  23176. } else if (ha === 'right') {
  23177. lx += lw2;
  23178. }
  23179. var labelIntersect = polygonIntersectLine(p1_i[0], p1_i[1], [lx - lw2, ly - lh2, lx + lw2, ly - lh2, lx + lw2, ly + lh2, lx - lw2, ly + lh2], tgtPos.x, tgtPos.y);
  23180. if (labelIntersect.length > 0) {
  23181. var refPt = srcPos;
  23182. var intSqdist = sqdist(refPt, array2point(intersect));
  23183. var labIntSqdist = sqdist(refPt, array2point(labelIntersect));
  23184. var minSqDist = intSqdist;
  23185. if (labIntSqdist < intSqdist) {
  23186. intersect = labelIntersect;
  23187. minSqDist = labIntSqdist;
  23188. }
  23189. if (labelIntersect.length > 2) {
  23190. var labInt2SqDist = sqdist(refPt, {
  23191. x: labelIntersect[2],
  23192. y: labelIntersect[3]
  23193. });
  23194. if (labInt2SqDist < minSqDist) {
  23195. intersect = [labelIntersect[2], labelIntersect[3]];
  23196. }
  23197. }
  23198. }
  23199. }
  23200. }
  23201. var arrowEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].spacing(edge) + tgtDist);
  23202. var edgeEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].gap(edge) + tgtDist);
  23203. rs.endX = edgeEnd[0];
  23204. rs.endY = edgeEnd[1];
  23205. rs.arrowEndX = arrowEnd[0];
  23206. rs.arrowEndY = arrowEnd[1];
  23207. if (srcManEndptVal === 'inside-to-node') {
  23208. intersect = [srcPos.x, srcPos.y];
  23209. } else if (srcManEndpt.units) {
  23210. intersect = this.manualEndptToPx(source, srcManEndpt);
  23211. } else if (srcManEndptVal === 'outside-to-line') {
  23212. intersect = rs.srcIntn; // use cached value from ctrlpt calc
  23213. } else {
  23214. if (srcManEndptVal === 'outside-to-node' || srcManEndptVal === 'outside-to-node-or-label') {
  23215. p2_i = p2;
  23216. } else if (srcManEndptVal === 'outside-to-line' || srcManEndptVal === 'outside-to-line-or-label') {
  23217. p2_i = [tgtPos.x, tgtPos.y];
  23218. }
  23219. intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0, srcCornerRadius, srcRs);
  23220. if (srcManEndptVal === 'outside-to-node-or-label' || srcManEndptVal === 'outside-to-line-or-label') {
  23221. var srs = source._private.rscratch;
  23222. var _lw = srs.labelWidth;
  23223. var _lh = srs.labelHeight;
  23224. var _lx = srs.labelX;
  23225. var _ly = srs.labelY;
  23226. var _lw2 = _lw / 2;
  23227. var _lh2 = _lh / 2;
  23228. var _va = source.pstyle('text-valign').value;
  23229. if (_va === 'top') {
  23230. _ly -= _lh2;
  23231. } else if (_va === 'bottom') {
  23232. _ly += _lh2;
  23233. }
  23234. var _ha = source.pstyle('text-halign').value;
  23235. if (_ha === 'left') {
  23236. _lx -= _lw2;
  23237. } else if (_ha === 'right') {
  23238. _lx += _lw2;
  23239. }
  23240. var _labelIntersect = polygonIntersectLine(p2_i[0], p2_i[1], [_lx - _lw2, _ly - _lh2, _lx + _lw2, _ly - _lh2, _lx + _lw2, _ly + _lh2, _lx - _lw2, _ly + _lh2], srcPos.x, srcPos.y);
  23241. if (_labelIntersect.length > 0) {
  23242. var _refPt = tgtPos;
  23243. var _intSqdist = sqdist(_refPt, array2point(intersect));
  23244. var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));
  23245. var _minSqDist = _intSqdist;
  23246. if (_labIntSqdist < _intSqdist) {
  23247. intersect = [_labelIntersect[0], _labelIntersect[1]];
  23248. _minSqDist = _labIntSqdist;
  23249. }
  23250. if (_labelIntersect.length > 2) {
  23251. var _labInt2SqDist = sqdist(_refPt, {
  23252. x: _labelIntersect[2],
  23253. y: _labelIntersect[3]
  23254. });
  23255. if (_labInt2SqDist < _minSqDist) {
  23256. intersect = [_labelIntersect[2], _labelIntersect[3]];
  23257. }
  23258. }
  23259. }
  23260. }
  23261. }
  23262. var arrowStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].spacing(edge) + srcDist);
  23263. var edgeStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].gap(edge) + srcDist);
  23264. rs.startX = edgeStart[0];
  23265. rs.startY = edgeStart[1];
  23266. rs.arrowStartX = arrowStart[0];
  23267. rs.arrowStartY = arrowStart[1];
  23268. if (hasEndpts) {
  23269. if (!number$1(rs.startX) || !number$1(rs.startY) || !number$1(rs.endX) || !number$1(rs.endY)) {
  23270. rs.badLine = true;
  23271. } else {
  23272. rs.badLine = false;
  23273. }
  23274. }
  23275. };
  23276. BRp$b.getSourceEndpoint = function (edge) {
  23277. var rs = edge[0]._private.rscratch;
  23278. this.recalculateRenderedStyle(edge);
  23279. switch (rs.edgeType) {
  23280. case 'haystack':
  23281. return {
  23282. x: rs.haystackPts[0],
  23283. y: rs.haystackPts[1]
  23284. };
  23285. default:
  23286. return {
  23287. x: rs.arrowStartX,
  23288. y: rs.arrowStartY
  23289. };
  23290. }
  23291. };
  23292. BRp$b.getTargetEndpoint = function (edge) {
  23293. var rs = edge[0]._private.rscratch;
  23294. this.recalculateRenderedStyle(edge);
  23295. switch (rs.edgeType) {
  23296. case 'haystack':
  23297. return {
  23298. x: rs.haystackPts[2],
  23299. y: rs.haystackPts[3]
  23300. };
  23301. default:
  23302. return {
  23303. x: rs.arrowEndX,
  23304. y: rs.arrowEndY
  23305. };
  23306. }
  23307. };
  23308. var BRp$a = {};
  23309. function pushBezierPts(r, edge, pts) {
  23310. var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {
  23311. return qbezierAt(p1, p2, p3, t);
  23312. };
  23313. var _p = edge._private;
  23314. var bpts = _p.rstyle.bezierPts;
  23315. for (var i = 0; i < r.bezierProjPcts.length; i++) {
  23316. var p = r.bezierProjPcts[i];
  23317. bpts.push({
  23318. x: qbezierAt$1(pts[0], pts[2], pts[4], p),
  23319. y: qbezierAt$1(pts[1], pts[3], pts[5], p)
  23320. });
  23321. }
  23322. }
  23323. BRp$a.storeEdgeProjections = function (edge) {
  23324. var _p = edge._private;
  23325. var rs = _p.rscratch;
  23326. var et = rs.edgeType;
  23327. // clear the cached points state
  23328. _p.rstyle.bezierPts = null;
  23329. _p.rstyle.linePts = null;
  23330. _p.rstyle.haystackPts = null;
  23331. if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {
  23332. _p.rstyle.bezierPts = [];
  23333. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  23334. pushBezierPts(this, edge, rs.allpts.slice(i, i + 6));
  23335. }
  23336. } else if (et === 'segments') {
  23337. var lpts = _p.rstyle.linePts = [];
  23338. for (var i = 0; i + 1 < rs.allpts.length; i += 2) {
  23339. lpts.push({
  23340. x: rs.allpts[i],
  23341. y: rs.allpts[i + 1]
  23342. });
  23343. }
  23344. } else if (et === 'haystack') {
  23345. var hpts = rs.haystackPts;
  23346. _p.rstyle.haystackPts = [{
  23347. x: hpts[0],
  23348. y: hpts[1]
  23349. }, {
  23350. x: hpts[2],
  23351. y: hpts[3]
  23352. }];
  23353. }
  23354. _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
  23355. };
  23356. BRp$a.recalculateEdgeProjections = function (edges) {
  23357. this.findEdgeControlPoints(edges);
  23358. };
  23359. var BRp$9 = {};
  23360. BRp$9.recalculateNodeLabelProjection = function (node) {
  23361. var content = node.pstyle('label').strValue;
  23362. if (emptyString(content)) {
  23363. return;
  23364. }
  23365. var textX, textY;
  23366. var _p = node._private;
  23367. var nodeWidth = node.width();
  23368. var nodeHeight = node.height();
  23369. var padding = node.padding();
  23370. var nodePos = node.position();
  23371. var textHalign = node.pstyle('text-halign').strValue;
  23372. var textValign = node.pstyle('text-valign').strValue;
  23373. var rs = _p.rscratch;
  23374. var rstyle = _p.rstyle;
  23375. switch (textHalign) {
  23376. case 'left':
  23377. textX = nodePos.x - nodeWidth / 2 - padding;
  23378. break;
  23379. case 'right':
  23380. textX = nodePos.x + nodeWidth / 2 + padding;
  23381. break;
  23382. default:
  23383. // e.g. center
  23384. textX = nodePos.x;
  23385. }
  23386. switch (textValign) {
  23387. case 'top':
  23388. textY = nodePos.y - nodeHeight / 2 - padding;
  23389. break;
  23390. case 'bottom':
  23391. textY = nodePos.y + nodeHeight / 2 + padding;
  23392. break;
  23393. default:
  23394. // e.g. middle
  23395. textY = nodePos.y;
  23396. }
  23397. rs.labelX = textX;
  23398. rs.labelY = textY;
  23399. rstyle.labelX = textX;
  23400. rstyle.labelY = textY;
  23401. this.calculateLabelAngles(node);
  23402. this.applyLabelDimensions(node);
  23403. };
  23404. var lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {
  23405. var angle = Math.atan(dy / dx);
  23406. if (dx === 0 && angle < 0) {
  23407. angle = angle * -1;
  23408. }
  23409. return angle;
  23410. };
  23411. var lineAngle = function lineAngle(p0, p1) {
  23412. var dx = p1.x - p0.x;
  23413. var dy = p1.y - p0.y;
  23414. return lineAngleFromDelta(dx, dy);
  23415. };
  23416. var bezierAngle = function bezierAngle(p0, p1, p2, t) {
  23417. var t0 = bound(0, t - 0.001, 1);
  23418. var t1 = bound(0, t + 0.001, 1);
  23419. var lp0 = qbezierPtAt(p0, p1, p2, t0);
  23420. var lp1 = qbezierPtAt(p0, p1, p2, t1);
  23421. return lineAngle(lp0, lp1);
  23422. };
  23423. BRp$9.recalculateEdgeLabelProjections = function (edge) {
  23424. var p;
  23425. var _p = edge._private;
  23426. var rs = _p.rscratch;
  23427. var r = this;
  23428. var content = {
  23429. mid: edge.pstyle('label').strValue,
  23430. source: edge.pstyle('source-label').strValue,
  23431. target: edge.pstyle('target-label').strValue
  23432. };
  23433. if (content.mid || content.source || content.target) ; else {
  23434. return; // no labels => no calcs
  23435. }
  23436. // add center point to style so bounding box calculations can use it
  23437. //
  23438. p = {
  23439. x: rs.midX,
  23440. y: rs.midY
  23441. };
  23442. var setRs = function setRs(propName, prefix, value) {
  23443. setPrefixedProperty(_p.rscratch, propName, prefix, value);
  23444. setPrefixedProperty(_p.rstyle, propName, prefix, value);
  23445. };
  23446. setRs('labelX', null, p.x);
  23447. setRs('labelY', null, p.y);
  23448. var midAngle = lineAngleFromDelta(rs.midDispX, rs.midDispY);
  23449. setRs('labelAutoAngle', null, midAngle);
  23450. var _createControlPointInfo = function createControlPointInfo() {
  23451. if (_createControlPointInfo.cache) {
  23452. return _createControlPointInfo.cache;
  23453. } // use cache so only 1x per edge
  23454. var ctrlpts = [];
  23455. // store each ctrlpt info init
  23456. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  23457. var p0 = {
  23458. x: rs.allpts[i],
  23459. y: rs.allpts[i + 1]
  23460. };
  23461. var p1 = {
  23462. x: rs.allpts[i + 2],
  23463. y: rs.allpts[i + 3]
  23464. }; // ctrlpt
  23465. var p2 = {
  23466. x: rs.allpts[i + 4],
  23467. y: rs.allpts[i + 5]
  23468. };
  23469. ctrlpts.push({
  23470. p0: p0,
  23471. p1: p1,
  23472. p2: p2,
  23473. startDist: 0,
  23474. length: 0,
  23475. segments: []
  23476. });
  23477. }
  23478. var bpts = _p.rstyle.bezierPts;
  23479. var nProjs = r.bezierProjPcts.length;
  23480. function addSegment(cp, p0, p1, t0, t1) {
  23481. var length = dist(p0, p1);
  23482. var prevSegment = cp.segments[cp.segments.length - 1];
  23483. var segment = {
  23484. p0: p0,
  23485. p1: p1,
  23486. t0: t0,
  23487. t1: t1,
  23488. startDist: prevSegment ? prevSegment.startDist + prevSegment.length : 0,
  23489. length: length
  23490. };
  23491. cp.segments.push(segment);
  23492. cp.length += length;
  23493. }
  23494. // update each ctrlpt with segment info
  23495. for (var _i = 0; _i < ctrlpts.length; _i++) {
  23496. var cp = ctrlpts[_i];
  23497. var prevCp = ctrlpts[_i - 1];
  23498. if (prevCp) {
  23499. cp.startDist = prevCp.startDist + prevCp.length;
  23500. }
  23501. addSegment(cp, cp.p0, bpts[_i * nProjs], 0, r.bezierProjPcts[0]); // first
  23502. for (var j = 0; j < nProjs - 1; j++) {
  23503. addSegment(cp, bpts[_i * nProjs + j], bpts[_i * nProjs + j + 1], r.bezierProjPcts[j], r.bezierProjPcts[j + 1]);
  23504. }
  23505. addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last
  23506. }
  23507. return _createControlPointInfo.cache = ctrlpts;
  23508. };
  23509. var calculateEndProjection = function calculateEndProjection(prefix) {
  23510. var angle;
  23511. var isSrc = prefix === 'source';
  23512. if (!content[prefix]) {
  23513. return;
  23514. }
  23515. var offset = edge.pstyle(prefix + '-text-offset').pfValue;
  23516. switch (rs.edgeType) {
  23517. case 'self':
  23518. case 'compound':
  23519. case 'bezier':
  23520. case 'multibezier':
  23521. {
  23522. var cps = _createControlPointInfo();
  23523. var selected;
  23524. var startDist = 0;
  23525. var totalDist = 0;
  23526. // find the segment we're on
  23527. for (var i = 0; i < cps.length; i++) {
  23528. var _cp = cps[isSrc ? i : cps.length - 1 - i];
  23529. for (var j = 0; j < _cp.segments.length; j++) {
  23530. var _seg = _cp.segments[isSrc ? j : _cp.segments.length - 1 - j];
  23531. var lastSeg = i === cps.length - 1 && j === _cp.segments.length - 1;
  23532. startDist = totalDist;
  23533. totalDist += _seg.length;
  23534. if (totalDist >= offset || lastSeg) {
  23535. selected = {
  23536. cp: _cp,
  23537. segment: _seg
  23538. };
  23539. break;
  23540. }
  23541. }
  23542. if (selected) {
  23543. break;
  23544. }
  23545. }
  23546. var cp = selected.cp;
  23547. var seg = selected.segment;
  23548. var tSegment = (offset - startDist) / seg.length;
  23549. var segDt = seg.t1 - seg.t0;
  23550. var t = isSrc ? seg.t0 + segDt * tSegment : seg.t1 - segDt * tSegment;
  23551. t = bound(0, t, 1);
  23552. p = qbezierPtAt(cp.p0, cp.p1, cp.p2, t);
  23553. angle = bezierAngle(cp.p0, cp.p1, cp.p2, t);
  23554. break;
  23555. }
  23556. case 'straight':
  23557. case 'segments':
  23558. case 'haystack':
  23559. {
  23560. var d = 0,
  23561. di,
  23562. d0;
  23563. var p0, p1;
  23564. var l = rs.allpts.length;
  23565. for (var _i2 = 0; _i2 + 3 < l; _i2 += 2) {
  23566. if (isSrc) {
  23567. p0 = {
  23568. x: rs.allpts[_i2],
  23569. y: rs.allpts[_i2 + 1]
  23570. };
  23571. p1 = {
  23572. x: rs.allpts[_i2 + 2],
  23573. y: rs.allpts[_i2 + 3]
  23574. };
  23575. } else {
  23576. p0 = {
  23577. x: rs.allpts[l - 2 - _i2],
  23578. y: rs.allpts[l - 1 - _i2]
  23579. };
  23580. p1 = {
  23581. x: rs.allpts[l - 4 - _i2],
  23582. y: rs.allpts[l - 3 - _i2]
  23583. };
  23584. }
  23585. di = dist(p0, p1);
  23586. d0 = d;
  23587. d += di;
  23588. if (d >= offset) {
  23589. break;
  23590. }
  23591. }
  23592. var pD = offset - d0;
  23593. var _t = pD / di;
  23594. _t = bound(0, _t, 1);
  23595. p = lineAt(p0, p1, _t);
  23596. angle = lineAngle(p0, p1);
  23597. break;
  23598. }
  23599. }
  23600. setRs('labelX', prefix, p.x);
  23601. setRs('labelY', prefix, p.y);
  23602. setRs('labelAutoAngle', prefix, angle);
  23603. };
  23604. calculateEndProjection('source');
  23605. calculateEndProjection('target');
  23606. this.applyLabelDimensions(edge);
  23607. };
  23608. BRp$9.applyLabelDimensions = function (ele) {
  23609. this.applyPrefixedLabelDimensions(ele);
  23610. if (ele.isEdge()) {
  23611. this.applyPrefixedLabelDimensions(ele, 'source');
  23612. this.applyPrefixedLabelDimensions(ele, 'target');
  23613. }
  23614. };
  23615. BRp$9.applyPrefixedLabelDimensions = function (ele, prefix) {
  23616. var _p = ele._private;
  23617. var text = this.getLabelText(ele, prefix);
  23618. var cacheKey = hashString(text, ele._private.labelDimsKey);
  23619. // save recalc if the label is the same as before
  23620. if (getPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix) === cacheKey) {
  23621. return; // then the label dimensions + text are the same
  23622. }
  23623. // save the key
  23624. setPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix, cacheKey);
  23625. var labelDims = this.calculateLabelDimensions(ele, text);
  23626. var lineHeight = ele.pstyle('line-height').pfValue;
  23627. var textWrap = ele.pstyle('text-wrap').strValue;
  23628. var lines = getPrefixedProperty(_p.rscratch, 'labelWrapCachedLines', prefix) || [];
  23629. var numLines = textWrap !== 'wrap' ? 1 : Math.max(lines.length, 1);
  23630. var normPerLineHeight = labelDims.height / numLines;
  23631. var labelLineHeight = normPerLineHeight * lineHeight;
  23632. var width = labelDims.width;
  23633. var height = labelDims.height + (numLines - 1) * (lineHeight - 1) * normPerLineHeight;
  23634. setPrefixedProperty(_p.rstyle, 'labelWidth', prefix, width);
  23635. setPrefixedProperty(_p.rscratch, 'labelWidth', prefix, width);
  23636. setPrefixedProperty(_p.rstyle, 'labelHeight', prefix, height);
  23637. setPrefixedProperty(_p.rscratch, 'labelHeight', prefix, height);
  23638. setPrefixedProperty(_p.rscratch, 'labelLineHeight', prefix, labelLineHeight);
  23639. };
  23640. BRp$9.getLabelText = function (ele, prefix) {
  23641. var _p = ele._private;
  23642. var pfd = prefix ? prefix + '-' : '';
  23643. var text = ele.pstyle(pfd + 'label').strValue;
  23644. var textTransform = ele.pstyle('text-transform').value;
  23645. var rscratch = function rscratch(propName, value) {
  23646. if (value) {
  23647. setPrefixedProperty(_p.rscratch, propName, prefix, value);
  23648. return value;
  23649. } else {
  23650. return getPrefixedProperty(_p.rscratch, propName, prefix);
  23651. }
  23652. };
  23653. // for empty text, skip all processing
  23654. if (!text) {
  23655. return '';
  23656. }
  23657. if (textTransform == 'none') ; else if (textTransform == 'uppercase') {
  23658. text = text.toUpperCase();
  23659. } else if (textTransform == 'lowercase') {
  23660. text = text.toLowerCase();
  23661. }
  23662. var wrapStyle = ele.pstyle('text-wrap').value;
  23663. if (wrapStyle === 'wrap') {
  23664. var labelKey = rscratch('labelKey');
  23665. // save recalc if the label is the same as before
  23666. if (labelKey != null && rscratch('labelWrapKey') === labelKey) {
  23667. return rscratch('labelWrapCachedText');
  23668. }
  23669. var zwsp = "\u200B";
  23670. var lines = text.split('\n');
  23671. var maxW = ele.pstyle('text-max-width').pfValue;
  23672. var overflow = ele.pstyle('text-overflow-wrap').value;
  23673. var overflowAny = overflow === 'anywhere';
  23674. var wrappedLines = [];
  23675. var separatorRegex = /[\s\u200b]+|$/g; // Include end of string to add last word
  23676. for (var l = 0; l < lines.length; l++) {
  23677. var line = lines[l];
  23678. var lineDims = this.calculateLabelDimensions(ele, line);
  23679. var lineW = lineDims.width;
  23680. if (overflowAny) {
  23681. var processedLine = line.split('').join(zwsp);
  23682. line = processedLine;
  23683. }
  23684. if (lineW > maxW) {
  23685. // line is too long
  23686. var separatorMatches = line.matchAll(separatorRegex);
  23687. var subline = '';
  23688. var previousIndex = 0;
  23689. // Add fake match
  23690. var _iterator = _createForOfIteratorHelper(separatorMatches),
  23691. _step;
  23692. try {
  23693. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  23694. var separatorMatch = _step.value;
  23695. var wordSeparator = separatorMatch[0];
  23696. var word = line.substring(previousIndex, separatorMatch.index);
  23697. previousIndex = separatorMatch.index + wordSeparator.length;
  23698. var testLine = subline.length === 0 ? word : subline + word + wordSeparator;
  23699. var testDims = this.calculateLabelDimensions(ele, testLine);
  23700. var testW = testDims.width;
  23701. if (testW <= maxW) {
  23702. // word fits on current line
  23703. subline += word + wordSeparator;
  23704. } else {
  23705. // word starts new line
  23706. if (subline) {
  23707. wrappedLines.push(subline);
  23708. }
  23709. subline = word + wordSeparator;
  23710. }
  23711. }
  23712. // if there's remaining text, put it in a wrapped line
  23713. } catch (err) {
  23714. _iterator.e(err);
  23715. } finally {
  23716. _iterator.f();
  23717. }
  23718. if (!subline.match(/^[\s\u200b]+$/)) {
  23719. wrappedLines.push(subline);
  23720. }
  23721. } else {
  23722. // line is already short enough
  23723. wrappedLines.push(line);
  23724. }
  23725. } // for
  23726. rscratch('labelWrapCachedLines', wrappedLines);
  23727. text = rscratch('labelWrapCachedText', wrappedLines.join('\n'));
  23728. rscratch('labelWrapKey', labelKey);
  23729. } else if (wrapStyle === 'ellipsis') {
  23730. var _maxW = ele.pstyle('text-max-width').pfValue;
  23731. var ellipsized = '';
  23732. var ellipsis = "\u2026";
  23733. var incLastCh = false;
  23734. if (this.calculateLabelDimensions(ele, text).width < _maxW) {
  23735. // the label already fits
  23736. return text;
  23737. }
  23738. for (var i = 0; i < text.length; i++) {
  23739. var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;
  23740. if (widthWithNextCh > _maxW) {
  23741. break;
  23742. }
  23743. ellipsized += text[i];
  23744. if (i === text.length - 1) {
  23745. incLastCh = true;
  23746. }
  23747. }
  23748. if (!incLastCh) {
  23749. ellipsized += ellipsis;
  23750. }
  23751. return ellipsized;
  23752. } // if ellipsize
  23753. return text;
  23754. };
  23755. BRp$9.getLabelJustification = function (ele) {
  23756. var justification = ele.pstyle('text-justification').strValue;
  23757. var textHalign = ele.pstyle('text-halign').strValue;
  23758. if (justification === 'auto') {
  23759. if (ele.isNode()) {
  23760. switch (textHalign) {
  23761. case 'left':
  23762. return 'right';
  23763. case 'right':
  23764. return 'left';
  23765. default:
  23766. return 'center';
  23767. }
  23768. } else {
  23769. return 'center';
  23770. }
  23771. } else {
  23772. return justification;
  23773. }
  23774. };
  23775. BRp$9.calculateLabelDimensions = function (ele, text) {
  23776. var r = this;
  23777. var containerWindow = r.cy.window();
  23778. var document = containerWindow.document;
  23779. var padding = 0; // add padding around text dims, as the measurement isn't that accurate
  23780. var fStyle = ele.pstyle('font-style').strValue;
  23781. var size = ele.pstyle('font-size').pfValue;
  23782. var family = ele.pstyle('font-family').strValue;
  23783. var weight = ele.pstyle('font-weight').strValue;
  23784. var canvas = this.labelCalcCanvas;
  23785. var c2d = this.labelCalcCanvasContext;
  23786. if (!canvas) {
  23787. canvas = this.labelCalcCanvas = document.createElement('canvas');
  23788. c2d = this.labelCalcCanvasContext = canvas.getContext('2d');
  23789. var ds = canvas.style;
  23790. ds.position = 'absolute';
  23791. ds.left = '-9999px';
  23792. ds.top = '-9999px';
  23793. ds.zIndex = '-1';
  23794. ds.visibility = 'hidden';
  23795. ds.pointerEvents = 'none';
  23796. }
  23797. c2d.font = "".concat(fStyle, " ").concat(weight, " ").concat(size, "px ").concat(family);
  23798. var width = 0;
  23799. var height = 0;
  23800. var lines = text.split('\n');
  23801. for (var i = 0; i < lines.length; i++) {
  23802. var line = lines[i];
  23803. var metrics = c2d.measureText(line);
  23804. var w = Math.ceil(metrics.width);
  23805. var h = size;
  23806. width = Math.max(w, width);
  23807. height += h;
  23808. }
  23809. width += padding;
  23810. height += padding;
  23811. return {
  23812. width: width,
  23813. height: height
  23814. };
  23815. };
  23816. BRp$9.calculateLabelAngle = function (ele, prefix) {
  23817. var _p = ele._private;
  23818. var rs = _p.rscratch;
  23819. var isEdge = ele.isEdge();
  23820. var prefixDash = prefix ? prefix + '-' : '';
  23821. var rot = ele.pstyle(prefixDash + 'text-rotation');
  23822. var rotStr = rot.strValue;
  23823. if (rotStr === 'none') {
  23824. return 0;
  23825. } else if (isEdge && rotStr === 'autorotate') {
  23826. return rs.labelAutoAngle;
  23827. } else if (rotStr === 'autorotate') {
  23828. return 0;
  23829. } else {
  23830. return rot.pfValue;
  23831. }
  23832. };
  23833. BRp$9.calculateLabelAngles = function (ele) {
  23834. var r = this;
  23835. var isEdge = ele.isEdge();
  23836. var _p = ele._private;
  23837. var rs = _p.rscratch;
  23838. rs.labelAngle = r.calculateLabelAngle(ele);
  23839. if (isEdge) {
  23840. rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');
  23841. rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');
  23842. }
  23843. };
  23844. var BRp$8 = {};
  23845. var TOO_SMALL_CUT_RECT = 28;
  23846. var warnedCutRect = false;
  23847. BRp$8.getNodeShape = function (node) {
  23848. var r = this;
  23849. var shape = node.pstyle('shape').value;
  23850. if (shape === 'cutrectangle' && (node.width() < TOO_SMALL_CUT_RECT || node.height() < TOO_SMALL_CUT_RECT)) {
  23851. if (!warnedCutRect) {
  23852. warn('The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead');
  23853. warnedCutRect = true;
  23854. }
  23855. return 'rectangle';
  23856. }
  23857. if (node.isParent()) {
  23858. if (shape === 'rectangle' || shape === 'roundrectangle' || shape === 'round-rectangle' || shape === 'cutrectangle' || shape === 'cut-rectangle' || shape === 'barrel') {
  23859. return shape;
  23860. } else {
  23861. return 'rectangle';
  23862. }
  23863. }
  23864. if (shape === 'polygon') {
  23865. var points = node.pstyle('shape-polygon-points').value;
  23866. return r.nodeShapes.makePolygon(points).name;
  23867. }
  23868. return shape;
  23869. };
  23870. var BRp$7 = {};
  23871. BRp$7.registerCalculationListeners = function () {
  23872. var cy = this.cy;
  23873. var elesToUpdate = cy.collection();
  23874. var r = this;
  23875. var enqueue = function enqueue(eles) {
  23876. var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  23877. elesToUpdate.merge(eles);
  23878. if (dirtyStyleCaches) {
  23879. for (var i = 0; i < eles.length; i++) {
  23880. var ele = eles[i];
  23881. var _p = ele._private;
  23882. var rstyle = _p.rstyle;
  23883. rstyle.clean = false;
  23884. rstyle.cleanConnected = false;
  23885. }
  23886. }
  23887. };
  23888. r.binder(cy).on('bounds.* dirty.*', function onDirtyBounds(e) {
  23889. var ele = e.target;
  23890. enqueue(ele);
  23891. }).on('style.* background.*', function onDirtyStyle(e) {
  23892. var ele = e.target;
  23893. enqueue(ele, false);
  23894. });
  23895. var updateEleCalcs = function updateEleCalcs(willDraw) {
  23896. if (willDraw) {
  23897. var fns = r.onUpdateEleCalcsFns;
  23898. // because we need to have up-to-date style (e.g. stylesheet mappers)
  23899. // before calculating rendered style (and pstyle might not be called yet)
  23900. elesToUpdate.cleanStyle();
  23901. for (var i = 0; i < elesToUpdate.length; i++) {
  23902. var ele = elesToUpdate[i];
  23903. var rstyle = ele._private.rstyle;
  23904. if (ele.isNode() && !rstyle.cleanConnected) {
  23905. enqueue(ele.connectedEdges());
  23906. rstyle.cleanConnected = true;
  23907. }
  23908. }
  23909. if (fns) {
  23910. for (var _i = 0; _i < fns.length; _i++) {
  23911. var fn = fns[_i];
  23912. fn(willDraw, elesToUpdate);
  23913. }
  23914. }
  23915. r.recalculateRenderedStyle(elesToUpdate);
  23916. elesToUpdate = cy.collection();
  23917. }
  23918. };
  23919. r.flushRenderedStyleQueue = function () {
  23920. updateEleCalcs(true);
  23921. };
  23922. r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);
  23923. };
  23924. BRp$7.onUpdateEleCalcs = function (fn) {
  23925. var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];
  23926. fns.push(fn);
  23927. };
  23928. BRp$7.recalculateRenderedStyle = function (eles, useCache) {
  23929. var isCleanConnected = function isCleanConnected(ele) {
  23930. return ele._private.rstyle.cleanConnected;
  23931. };
  23932. if (eles.length === 0) {
  23933. return;
  23934. }
  23935. var edges = [];
  23936. var nodes = [];
  23937. // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()
  23938. if (this.destroyed) {
  23939. return;
  23940. }
  23941. // use cache by default for perf
  23942. if (useCache === undefined) {
  23943. useCache = true;
  23944. }
  23945. for (var i = 0; i < eles.length; i++) {
  23946. var ele = eles[i];
  23947. var _p = ele._private;
  23948. var rstyle = _p.rstyle;
  23949. // an edge may be implicitly dirty b/c of one of its connected nodes
  23950. // (and a request for recalc may come in between frames)
  23951. if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {
  23952. rstyle.clean = false;
  23953. }
  23954. if (ele.isEdge() && ele.isBundledBezier()) {
  23955. if (ele.parallelEdges().some(function (ele) {
  23956. return !ele._private.rstyle.clean && ele.isBundledBezier();
  23957. })) {
  23958. rstyle.clean = false;
  23959. }
  23960. }
  23961. // only update if dirty and in graph
  23962. if (useCache && rstyle.clean || ele.removed()) {
  23963. continue;
  23964. }
  23965. // only update if not display: none
  23966. if (ele.pstyle('display').value === 'none') {
  23967. continue;
  23968. }
  23969. if (_p.group === 'nodes') {
  23970. nodes.push(ele);
  23971. } else {
  23972. // edges
  23973. edges.push(ele);
  23974. }
  23975. rstyle.clean = true;
  23976. }
  23977. // update node data from projections
  23978. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  23979. var _ele = nodes[_i2];
  23980. var _p2 = _ele._private;
  23981. var _rstyle = _p2.rstyle;
  23982. var pos = _ele.position();
  23983. this.recalculateNodeLabelProjection(_ele);
  23984. _rstyle.nodeX = pos.x;
  23985. _rstyle.nodeY = pos.y;
  23986. _rstyle.nodeW = _ele.pstyle('width').pfValue;
  23987. _rstyle.nodeH = _ele.pstyle('height').pfValue;
  23988. }
  23989. this.recalculateEdgeProjections(edges);
  23990. // update edge data from projections
  23991. for (var _i3 = 0; _i3 < edges.length; _i3++) {
  23992. var _ele2 = edges[_i3];
  23993. var _p3 = _ele2._private;
  23994. var _rstyle2 = _p3.rstyle;
  23995. var rs = _p3.rscratch;
  23996. // update rstyle positions
  23997. _rstyle2.srcX = rs.arrowStartX;
  23998. _rstyle2.srcY = rs.arrowStartY;
  23999. _rstyle2.tgtX = rs.arrowEndX;
  24000. _rstyle2.tgtY = rs.arrowEndY;
  24001. _rstyle2.midX = rs.midX;
  24002. _rstyle2.midY = rs.midY;
  24003. _rstyle2.labelAngle = rs.labelAngle;
  24004. _rstyle2.sourceLabelAngle = rs.sourceLabelAngle;
  24005. _rstyle2.targetLabelAngle = rs.targetLabelAngle;
  24006. }
  24007. };
  24008. var BRp$6 = {};
  24009. BRp$6.updateCachedGrabbedEles = function () {
  24010. var eles = this.cachedZSortedEles;
  24011. if (!eles) {
  24012. // just let this be recalculated on the next z sort tick
  24013. return;
  24014. }
  24015. eles.drag = [];
  24016. eles.nondrag = [];
  24017. var grabTargets = [];
  24018. for (var i = 0; i < eles.length; i++) {
  24019. var ele = eles[i];
  24020. var rs = ele._private.rscratch;
  24021. if (ele.grabbed() && !ele.isParent()) {
  24022. grabTargets.push(ele);
  24023. } else if (rs.inDragLayer) {
  24024. eles.drag.push(ele);
  24025. } else {
  24026. eles.nondrag.push(ele);
  24027. }
  24028. }
  24029. // put the grab target nodes last so it's on top of its neighbourhood
  24030. for (var i = 0; i < grabTargets.length; i++) {
  24031. var ele = grabTargets[i];
  24032. eles.drag.push(ele);
  24033. }
  24034. };
  24035. BRp$6.invalidateCachedZSortedEles = function () {
  24036. this.cachedZSortedEles = null;
  24037. };
  24038. BRp$6.getCachedZSortedEles = function (forceRecalc) {
  24039. if (forceRecalc || !this.cachedZSortedEles) {
  24040. var eles = this.cy.mutableElements().toArray();
  24041. eles.sort(zIndexSort);
  24042. eles.interactive = eles.filter(function (ele) {
  24043. return ele.interactive();
  24044. });
  24045. this.cachedZSortedEles = eles;
  24046. this.updateCachedGrabbedEles();
  24047. } else {
  24048. eles = this.cachedZSortedEles;
  24049. }
  24050. return eles;
  24051. };
  24052. var BRp$5 = {};
  24053. [BRp$e, BRp$d, BRp$c, BRp$b, BRp$a, BRp$9, BRp$8, BRp$7, BRp$6].forEach(function (props) {
  24054. extend(BRp$5, props);
  24055. });
  24056. var BRp$4 = {};
  24057. BRp$4.getCachedImage = function (url, crossOrigin, onLoad) {
  24058. var r = this;
  24059. var imageCache = r.imageCache = r.imageCache || {};
  24060. var cache = imageCache[url];
  24061. if (cache) {
  24062. if (!cache.image.complete) {
  24063. cache.image.addEventListener('load', onLoad);
  24064. }
  24065. return cache.image;
  24066. } else {
  24067. cache = imageCache[url] = imageCache[url] || {};
  24068. var image = cache.image = new Image(); // eslint-disable-line no-undef
  24069. image.addEventListener('load', onLoad);
  24070. image.addEventListener('error', function () {
  24071. image.error = true;
  24072. });
  24073. // #1582 safari doesn't load data uris with crossOrigin properly
  24074. // https://bugs.webkit.org/show_bug.cgi?id=123978
  24075. var dataUriPrefix = 'data:';
  24076. var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;
  24077. if (!isDataUri) {
  24078. // if crossorigin is 'null'(stringified), then manually set it to null
  24079. crossOrigin = crossOrigin === 'null' ? null : crossOrigin;
  24080. image.crossOrigin = crossOrigin; // prevent tainted canvas
  24081. }
  24082. image.src = url;
  24083. return image;
  24084. }
  24085. };
  24086. var BRp$3 = {};
  24087. /* global document, ResizeObserver, MutationObserver */
  24088. BRp$3.registerBinding = function (target, event, handler, useCapture) {
  24089. // eslint-disable-line no-unused-vars
  24090. var args = Array.prototype.slice.apply(arguments, [1]); // copy
  24091. if (Array.isArray(target)) {
  24092. var res = [];
  24093. for (var i = 0; i < target.length; i++) {
  24094. var t = target[i];
  24095. if (t !== undefined) {
  24096. var b = this.binder(t);
  24097. res.push(b.on.apply(b, args));
  24098. }
  24099. }
  24100. return res;
  24101. }
  24102. var b = this.binder(target);
  24103. return b.on.apply(b, args);
  24104. };
  24105. BRp$3.binder = function (tgt) {
  24106. var r = this;
  24107. var containerWindow = r.cy.window();
  24108. var tgtIsDom = tgt === containerWindow || tgt === containerWindow.document || tgt === containerWindow.document.body || domElement(tgt);
  24109. if (r.supportsPassiveEvents == null) {
  24110. // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  24111. var supportsPassive = false;
  24112. try {
  24113. var opts = Object.defineProperty({}, 'passive', {
  24114. get: function get() {
  24115. supportsPassive = true;
  24116. return true;
  24117. }
  24118. });
  24119. containerWindow.addEventListener('test', null, opts);
  24120. } catch (err) {
  24121. // not supported
  24122. }
  24123. r.supportsPassiveEvents = supportsPassive;
  24124. }
  24125. var on = function on(event, handler, useCapture) {
  24126. var args = Array.prototype.slice.call(arguments);
  24127. if (tgtIsDom && r.supportsPassiveEvents) {
  24128. // replace useCapture w/ opts obj
  24129. args[2] = {
  24130. capture: useCapture != null ? useCapture : false,
  24131. passive: false,
  24132. once: false
  24133. };
  24134. }
  24135. r.bindings.push({
  24136. target: tgt,
  24137. args: args
  24138. });
  24139. (tgt.addEventListener || tgt.on).apply(tgt, args);
  24140. return this;
  24141. };
  24142. return {
  24143. on: on,
  24144. addEventListener: on,
  24145. addListener: on,
  24146. bind: on
  24147. };
  24148. };
  24149. BRp$3.nodeIsDraggable = function (node) {
  24150. return node && node.isNode() && !node.locked() && node.grabbable();
  24151. };
  24152. BRp$3.nodeIsGrabbable = function (node) {
  24153. return this.nodeIsDraggable(node) && node.interactive();
  24154. };
  24155. BRp$3.load = function () {
  24156. var r = this;
  24157. var containerWindow = r.cy.window();
  24158. var isSelected = function isSelected(ele) {
  24159. return ele.selected();
  24160. };
  24161. var getShadowRoot = function getShadowRoot(element) {
  24162. var rootNode = element.getRootNode();
  24163. // Check if the root node is a shadow root
  24164. if (rootNode && rootNode.nodeType === 11 && rootNode.host !== undefined) {
  24165. return rootNode;
  24166. }
  24167. };
  24168. var triggerEvents = function triggerEvents(target, names, e, position) {
  24169. if (target == null) {
  24170. target = r.cy;
  24171. }
  24172. for (var i = 0; i < names.length; i++) {
  24173. var name = names[i];
  24174. target.emit({
  24175. originalEvent: e,
  24176. type: name,
  24177. position: position
  24178. });
  24179. }
  24180. };
  24181. var isMultSelKeyDown = function isMultSelKeyDown(e) {
  24182. return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey
  24183. };
  24184. var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {
  24185. var allowPassthrough = true;
  24186. if (r.cy.hasCompoundNodes() && down && down.pannable()) {
  24187. // a grabbable compound node below the ele => no passthrough panning
  24188. for (var i = 0; downs && i < downs.length; i++) {
  24189. var down = downs[i];
  24190. //if any parent node in event hierarchy isn't pannable, reject passthrough
  24191. if (down.isNode() && down.isParent() && !down.pannable()) {
  24192. allowPassthrough = false;
  24193. break;
  24194. }
  24195. }
  24196. } else {
  24197. allowPassthrough = true;
  24198. }
  24199. return allowPassthrough;
  24200. };
  24201. var setGrabbed = function setGrabbed(ele) {
  24202. ele[0]._private.grabbed = true;
  24203. };
  24204. var setFreed = function setFreed(ele) {
  24205. ele[0]._private.grabbed = false;
  24206. };
  24207. var setInDragLayer = function setInDragLayer(ele) {
  24208. ele[0]._private.rscratch.inDragLayer = true;
  24209. };
  24210. var setOutDragLayer = function setOutDragLayer(ele) {
  24211. ele[0]._private.rscratch.inDragLayer = false;
  24212. };
  24213. var setGrabTarget = function setGrabTarget(ele) {
  24214. ele[0]._private.rscratch.isGrabTarget = true;
  24215. };
  24216. var removeGrabTarget = function removeGrabTarget(ele) {
  24217. ele[0]._private.rscratch.isGrabTarget = false;
  24218. };
  24219. var addToDragList = function addToDragList(ele, opts) {
  24220. var list = opts.addToList;
  24221. var listHasEle = list.has(ele);
  24222. if (!listHasEle && ele.grabbable() && !ele.locked()) {
  24223. list.merge(ele);
  24224. setGrabbed(ele);
  24225. }
  24226. };
  24227. // helper function to determine which child nodes and inner edges
  24228. // of a compound node to be dragged as well as the grabbed and selected nodes
  24229. var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {
  24230. if (!node.cy().hasCompoundNodes()) {
  24231. return;
  24232. }
  24233. if (opts.inDragLayer == null && opts.addToList == null) {
  24234. return;
  24235. } // nothing to do
  24236. var innerNodes = node.descendants();
  24237. if (opts.inDragLayer) {
  24238. innerNodes.forEach(setInDragLayer);
  24239. innerNodes.connectedEdges().forEach(setInDragLayer);
  24240. }
  24241. if (opts.addToList) {
  24242. addToDragList(innerNodes, opts);
  24243. }
  24244. };
  24245. // adds the given nodes and its neighbourhood to the drag layer
  24246. var addNodesToDrag = function addNodesToDrag(nodes, opts) {
  24247. opts = opts || {};
  24248. var hasCompoundNodes = nodes.cy().hasCompoundNodes();
  24249. if (opts.inDragLayer) {
  24250. nodes.forEach(setInDragLayer);
  24251. nodes.neighborhood().stdFilter(function (ele) {
  24252. return !hasCompoundNodes || ele.isEdge();
  24253. }).forEach(setInDragLayer);
  24254. }
  24255. if (opts.addToList) {
  24256. nodes.forEach(function (ele) {
  24257. addToDragList(ele, opts);
  24258. });
  24259. }
  24260. addDescendantsToDrag(nodes, opts); // always add to drag
  24261. // also add nodes and edges related to the topmost ancestor
  24262. updateAncestorsInDragLayer(nodes, {
  24263. inDragLayer: opts.inDragLayer
  24264. });
  24265. r.updateCachedGrabbedEles();
  24266. };
  24267. var addNodeToDrag = addNodesToDrag;
  24268. var freeDraggedElements = function freeDraggedElements(grabbedEles) {
  24269. if (!grabbedEles) {
  24270. return;
  24271. }
  24272. // just go over all elements rather than doing a bunch of (possibly expensive) traversals
  24273. r.getCachedZSortedEles().forEach(function (ele) {
  24274. setFreed(ele);
  24275. setOutDragLayer(ele);
  24276. removeGrabTarget(ele);
  24277. });
  24278. r.updateCachedGrabbedEles();
  24279. };
  24280. // helper function to determine which ancestor nodes and edges should go
  24281. // to the drag layer (or should be removed from drag layer).
  24282. var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {
  24283. if (opts.inDragLayer == null && opts.addToList == null) {
  24284. return;
  24285. } // nothing to do
  24286. if (!node.cy().hasCompoundNodes()) {
  24287. return;
  24288. }
  24289. // find top-level parent
  24290. var parent = node.ancestors().orphans();
  24291. // no parent node: no nodes to add to the drag layer
  24292. if (parent.same(node)) {
  24293. return;
  24294. }
  24295. var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());
  24296. var edges = nodes.connectedEdges();
  24297. if (opts.inDragLayer) {
  24298. edges.forEach(setInDragLayer);
  24299. nodes.forEach(setInDragLayer);
  24300. }
  24301. if (opts.addToList) {
  24302. nodes.forEach(function (ele) {
  24303. addToDragList(ele, opts);
  24304. });
  24305. }
  24306. };
  24307. var blurActiveDomElement = function blurActiveDomElement() {
  24308. if (document.activeElement != null && document.activeElement.blur != null) {
  24309. document.activeElement.blur();
  24310. }
  24311. };
  24312. var haveMutationsApi = typeof MutationObserver !== 'undefined';
  24313. var haveResizeObserverApi = typeof ResizeObserver !== 'undefined';
  24314. // watch for when the cy container is removed from the dom
  24315. if (haveMutationsApi) {
  24316. r.removeObserver = new MutationObserver(function (mutns) {
  24317. // eslint-disable-line no-undef
  24318. for (var i = 0; i < mutns.length; i++) {
  24319. var mutn = mutns[i];
  24320. var rNodes = mutn.removedNodes;
  24321. if (rNodes) {
  24322. for (var j = 0; j < rNodes.length; j++) {
  24323. var rNode = rNodes[j];
  24324. if (rNode === r.container) {
  24325. r.destroy();
  24326. break;
  24327. }
  24328. }
  24329. }
  24330. }
  24331. });
  24332. if (r.container.parentNode) {
  24333. r.removeObserver.observe(r.container.parentNode, {
  24334. childList: true
  24335. });
  24336. }
  24337. } else {
  24338. r.registerBinding(r.container, 'DOMNodeRemoved', function (e) {
  24339. // eslint-disable-line no-unused-vars
  24340. r.destroy();
  24341. });
  24342. }
  24343. var onResize = debounce(function () {
  24344. r.cy.resize();
  24345. }, 100);
  24346. if (haveMutationsApi) {
  24347. r.styleObserver = new MutationObserver(onResize); // eslint-disable-line no-undef
  24348. r.styleObserver.observe(r.container, {
  24349. attributes: true
  24350. });
  24351. }
  24352. // auto resize
  24353. r.registerBinding(containerWindow, 'resize', onResize); // eslint-disable-line no-undef
  24354. if (haveResizeObserverApi) {
  24355. r.resizeObserver = new ResizeObserver(onResize); // eslint-disable-line no-undef
  24356. r.resizeObserver.observe(r.container);
  24357. }
  24358. var forEachUp = function forEachUp(domEle, fn) {
  24359. while (domEle != null) {
  24360. fn(domEle);
  24361. domEle = domEle.parentNode;
  24362. }
  24363. };
  24364. var invalidateCoords = function invalidateCoords() {
  24365. r.invalidateContainerClientCoordsCache();
  24366. };
  24367. forEachUp(r.container, function (domEle) {
  24368. r.registerBinding(domEle, 'transitionend', invalidateCoords);
  24369. r.registerBinding(domEle, 'animationend', invalidateCoords);
  24370. r.registerBinding(domEle, 'scroll', invalidateCoords);
  24371. });
  24372. // stop right click menu from appearing on cy
  24373. r.registerBinding(r.container, 'contextmenu', function (e) {
  24374. e.preventDefault();
  24375. });
  24376. var inBoxSelection = function inBoxSelection() {
  24377. return r.selection[4] !== 0;
  24378. };
  24379. var eventInContainer = function eventInContainer(e) {
  24380. // save cycles if mouse events aren't to be captured
  24381. var containerPageCoords = r.findContainerClientCoords();
  24382. var x = containerPageCoords[0];
  24383. var y = containerPageCoords[1];
  24384. var width = containerPageCoords[2];
  24385. var height = containerPageCoords[3];
  24386. var positions = e.touches ? e.touches : [e];
  24387. var atLeastOnePosInside = false;
  24388. for (var i = 0; i < positions.length; i++) {
  24389. var p = positions[i];
  24390. if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {
  24391. atLeastOnePosInside = true;
  24392. break;
  24393. }
  24394. }
  24395. if (!atLeastOnePosInside) {
  24396. return false;
  24397. }
  24398. var container = r.container;
  24399. var target = e.target;
  24400. var tParent = target.parentNode;
  24401. var containerIsTarget = false;
  24402. while (tParent) {
  24403. if (tParent === container) {
  24404. containerIsTarget = true;
  24405. break;
  24406. }
  24407. tParent = tParent.parentNode;
  24408. }
  24409. if (!containerIsTarget) {
  24410. return false;
  24411. } // if target is outisde cy container, then this event is not for us
  24412. return true;
  24413. };
  24414. // Primary key
  24415. r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {
  24416. if (!eventInContainer(e)) {
  24417. return;
  24418. }
  24419. // during left mouse button gestures, ignore other buttons
  24420. if (r.hoverData.which === 1 && e.which !== 1) {
  24421. return;
  24422. }
  24423. e.preventDefault();
  24424. blurActiveDomElement();
  24425. r.hoverData.capture = true;
  24426. r.hoverData.which = e.which;
  24427. var cy = r.cy;
  24428. var gpos = [e.clientX, e.clientY];
  24429. var pos = r.projectIntoViewport(gpos[0], gpos[1]);
  24430. var select = r.selection;
  24431. var nears = r.findNearestElements(pos[0], pos[1], true, false);
  24432. var near = nears[0];
  24433. var draggedElements = r.dragData.possibleDragElements;
  24434. r.hoverData.mdownPos = pos;
  24435. r.hoverData.mdownGPos = gpos;
  24436. var makeEvent = function makeEvent(type) {
  24437. return {
  24438. originalEvent: e,
  24439. type: type,
  24440. position: {
  24441. x: pos[0],
  24442. y: pos[1]
  24443. }
  24444. };
  24445. };
  24446. var checkForTaphold = function checkForTaphold() {
  24447. r.hoverData.tapholdCancelled = false;
  24448. clearTimeout(r.hoverData.tapholdTimeout);
  24449. r.hoverData.tapholdTimeout = setTimeout(function () {
  24450. if (r.hoverData.tapholdCancelled) {
  24451. return;
  24452. } else {
  24453. var ele = r.hoverData.down;
  24454. if (ele) {
  24455. ele.emit(makeEvent('taphold'));
  24456. } else {
  24457. cy.emit(makeEvent('taphold'));
  24458. }
  24459. }
  24460. }, r.tapholdDuration);
  24461. };
  24462. // Right click button
  24463. if (e.which == 3) {
  24464. r.hoverData.cxtStarted = true;
  24465. var cxtEvt = {
  24466. originalEvent: e,
  24467. type: 'cxttapstart',
  24468. position: {
  24469. x: pos[0],
  24470. y: pos[1]
  24471. }
  24472. };
  24473. if (near) {
  24474. near.activate();
  24475. near.emit(cxtEvt);
  24476. r.hoverData.down = near;
  24477. } else {
  24478. cy.emit(cxtEvt);
  24479. }
  24480. r.hoverData.downTime = new Date().getTime();
  24481. r.hoverData.cxtDragged = false;
  24482. // Primary button
  24483. } else if (e.which == 1) {
  24484. if (near) {
  24485. near.activate();
  24486. }
  24487. // Element dragging
  24488. {
  24489. // If something is under the cursor and it is draggable, prepare to grab it
  24490. if (near != null) {
  24491. if (r.nodeIsGrabbable(near)) {
  24492. var triggerGrab = function triggerGrab(ele) {
  24493. ele.emit(makeEvent('grab'));
  24494. };
  24495. setGrabTarget(near);
  24496. if (!near.selected()) {
  24497. draggedElements = r.dragData.possibleDragElements = cy.collection();
  24498. addNodeToDrag(near, {
  24499. addToList: draggedElements
  24500. });
  24501. near.emit(makeEvent('grabon')).emit(makeEvent('grab'));
  24502. } else {
  24503. draggedElements = r.dragData.possibleDragElements = cy.collection();
  24504. var selectedNodes = cy.$(function (ele) {
  24505. return ele.isNode() && ele.selected() && r.nodeIsGrabbable(ele);
  24506. });
  24507. addNodesToDrag(selectedNodes, {
  24508. addToList: draggedElements
  24509. });
  24510. near.emit(makeEvent('grabon'));
  24511. selectedNodes.forEach(triggerGrab);
  24512. }
  24513. r.redrawHint('eles', true);
  24514. r.redrawHint('drag', true);
  24515. }
  24516. }
  24517. r.hoverData.down = near;
  24518. r.hoverData.downs = nears;
  24519. r.hoverData.downTime = new Date().getTime();
  24520. }
  24521. triggerEvents(near, ['mousedown', 'tapstart', 'vmousedown'], e, {
  24522. x: pos[0],
  24523. y: pos[1]
  24524. });
  24525. if (near == null) {
  24526. select[4] = 1;
  24527. r.data.bgActivePosistion = {
  24528. x: pos[0],
  24529. y: pos[1]
  24530. };
  24531. r.redrawHint('select', true);
  24532. r.redraw();
  24533. } else if (near.pannable()) {
  24534. select[4] = 1; // for future pan
  24535. }
  24536. checkForTaphold();
  24537. }
  24538. // Initialize selection box coordinates
  24539. select[0] = select[2] = pos[0];
  24540. select[1] = select[3] = pos[1];
  24541. }, false);
  24542. var shadowRoot = getShadowRoot(r.container);
  24543. r.registerBinding([containerWindow, shadowRoot], 'mousemove', function mousemoveHandler(e) {
  24544. // eslint-disable-line no-undef
  24545. var capture = r.hoverData.capture;
  24546. if (!capture && !eventInContainer(e)) {
  24547. return;
  24548. }
  24549. var preventDefault = false;
  24550. var cy = r.cy;
  24551. var zoom = cy.zoom();
  24552. var gpos = [e.clientX, e.clientY];
  24553. var pos = r.projectIntoViewport(gpos[0], gpos[1]);
  24554. var mdownPos = r.hoverData.mdownPos;
  24555. var mdownGPos = r.hoverData.mdownGPos;
  24556. var select = r.selection;
  24557. var near = null;
  24558. if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {
  24559. near = r.findNearestElement(pos[0], pos[1], true, false);
  24560. }
  24561. var last = r.hoverData.last;
  24562. var down = r.hoverData.down;
  24563. var disp = [pos[0] - select[2], pos[1] - select[3]];
  24564. var draggedElements = r.dragData.possibleDragElements;
  24565. var isOverThresholdDrag;
  24566. if (mdownGPos) {
  24567. var dx = gpos[0] - mdownGPos[0];
  24568. var dx2 = dx * dx;
  24569. var dy = gpos[1] - mdownGPos[1];
  24570. var dy2 = dy * dy;
  24571. var dist2 = dx2 + dy2;
  24572. r.hoverData.isOverThresholdDrag = isOverThresholdDrag = dist2 >= r.desktopTapThreshold2;
  24573. }
  24574. var multSelKeyDown = isMultSelKeyDown(e);
  24575. if (isOverThresholdDrag) {
  24576. r.hoverData.tapholdCancelled = true;
  24577. }
  24578. var updateDragDelta = function updateDragDelta() {
  24579. var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];
  24580. if (dragDelta.length === 0) {
  24581. dragDelta.push(disp[0]);
  24582. dragDelta.push(disp[1]);
  24583. } else {
  24584. dragDelta[0] += disp[0];
  24585. dragDelta[1] += disp[1];
  24586. }
  24587. };
  24588. preventDefault = true;
  24589. triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {
  24590. x: pos[0],
  24591. y: pos[1]
  24592. });
  24593. var makeEvent = function makeEvent(type) {
  24594. return {
  24595. originalEvent: e,
  24596. type: type,
  24597. position: {
  24598. x: pos[0],
  24599. y: pos[1]
  24600. }
  24601. };
  24602. };
  24603. var goIntoBoxMode = function goIntoBoxMode() {
  24604. r.data.bgActivePosistion = undefined;
  24605. if (!r.hoverData.selecting) {
  24606. cy.emit(makeEvent('boxstart'));
  24607. }
  24608. select[4] = 1;
  24609. r.hoverData.selecting = true;
  24610. r.redrawHint('select', true);
  24611. r.redraw();
  24612. };
  24613. // trigger context drag if rmouse down
  24614. if (r.hoverData.which === 3) {
  24615. // but only if over threshold
  24616. if (isOverThresholdDrag) {
  24617. var cxtEvt = makeEvent('cxtdrag');
  24618. if (down) {
  24619. down.emit(cxtEvt);
  24620. } else {
  24621. cy.emit(cxtEvt);
  24622. }
  24623. r.hoverData.cxtDragged = true;
  24624. if (!r.hoverData.cxtOver || near !== r.hoverData.cxtOver) {
  24625. if (r.hoverData.cxtOver) {
  24626. r.hoverData.cxtOver.emit(makeEvent('cxtdragout'));
  24627. }
  24628. r.hoverData.cxtOver = near;
  24629. if (near) {
  24630. near.emit(makeEvent('cxtdragover'));
  24631. }
  24632. }
  24633. }
  24634. // Check if we are drag panning the entire graph
  24635. } else if (r.hoverData.dragging) {
  24636. preventDefault = true;
  24637. if (cy.panningEnabled() && cy.userPanningEnabled()) {
  24638. var deltaP;
  24639. if (r.hoverData.justStartedPan) {
  24640. var mdPos = r.hoverData.mdownPos;
  24641. deltaP = {
  24642. x: (pos[0] - mdPos[0]) * zoom,
  24643. y: (pos[1] - mdPos[1]) * zoom
  24644. };
  24645. r.hoverData.justStartedPan = false;
  24646. } else {
  24647. deltaP = {
  24648. x: disp[0] * zoom,
  24649. y: disp[1] * zoom
  24650. };
  24651. }
  24652. cy.panBy(deltaP);
  24653. cy.emit(makeEvent('dragpan'));
  24654. r.hoverData.dragged = true;
  24655. }
  24656. // Needs reproject due to pan changing viewport
  24657. pos = r.projectIntoViewport(e.clientX, e.clientY);
  24658. // Checks primary button down & out of time & mouse not moved much
  24659. } else if (select[4] == 1 && (down == null || down.pannable())) {
  24660. if (isOverThresholdDrag) {
  24661. if (!r.hoverData.dragging && cy.boxSelectionEnabled() && (multSelKeyDown || !cy.panningEnabled() || !cy.userPanningEnabled())) {
  24662. goIntoBoxMode();
  24663. } else if (!r.hoverData.selecting && cy.panningEnabled() && cy.userPanningEnabled()) {
  24664. var allowPassthrough = allowPanningPassthrough(down, r.hoverData.downs);
  24665. if (allowPassthrough) {
  24666. r.hoverData.dragging = true;
  24667. r.hoverData.justStartedPan = true;
  24668. select[4] = 0;
  24669. r.data.bgActivePosistion = array2point(mdownPos);
  24670. r.redrawHint('select', true);
  24671. r.redraw();
  24672. }
  24673. }
  24674. if (down && down.pannable() && down.active()) {
  24675. down.unactivate();
  24676. }
  24677. }
  24678. } else {
  24679. if (down && down.pannable() && down.active()) {
  24680. down.unactivate();
  24681. }
  24682. if ((!down || !down.grabbed()) && near != last) {
  24683. if (last) {
  24684. triggerEvents(last, ['mouseout', 'tapdragout'], e, {
  24685. x: pos[0],
  24686. y: pos[1]
  24687. });
  24688. }
  24689. if (near) {
  24690. triggerEvents(near, ['mouseover', 'tapdragover'], e, {
  24691. x: pos[0],
  24692. y: pos[1]
  24693. });
  24694. }
  24695. r.hoverData.last = near;
  24696. }
  24697. if (down) {
  24698. if (isOverThresholdDrag) {
  24699. // then we can take action
  24700. if (cy.boxSelectionEnabled() && multSelKeyDown) {
  24701. // then selection overrides
  24702. if (down && down.grabbed()) {
  24703. freeDraggedElements(draggedElements);
  24704. down.emit(makeEvent('freeon'));
  24705. draggedElements.emit(makeEvent('free'));
  24706. if (r.dragData.didDrag) {
  24707. down.emit(makeEvent('dragfreeon'));
  24708. draggedElements.emit(makeEvent('dragfree'));
  24709. }
  24710. }
  24711. goIntoBoxMode();
  24712. } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {
  24713. // drag node
  24714. var justStartedDrag = !r.dragData.didDrag;
  24715. if (justStartedDrag) {
  24716. r.redrawHint('eles', true);
  24717. }
  24718. r.dragData.didDrag = true; // indicate that we actually did drag the node
  24719. // now, add the elements to the drag layer if not done already
  24720. if (!r.hoverData.draggingEles) {
  24721. addNodesToDrag(draggedElements, {
  24722. inDragLayer: true
  24723. });
  24724. }
  24725. var totalShift = {
  24726. x: 0,
  24727. y: 0
  24728. };
  24729. if (number$1(disp[0]) && number$1(disp[1])) {
  24730. totalShift.x += disp[0];
  24731. totalShift.y += disp[1];
  24732. if (justStartedDrag) {
  24733. var dragDelta = r.hoverData.dragDelta;
  24734. if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
  24735. totalShift.x += dragDelta[0];
  24736. totalShift.y += dragDelta[1];
  24737. }
  24738. }
  24739. }
  24740. r.hoverData.draggingEles = true;
  24741. draggedElements.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
  24742. r.redrawHint('drag', true);
  24743. r.redraw();
  24744. }
  24745. } else {
  24746. // otherwise save drag delta for when we actually start dragging so the relative grab pos is constant
  24747. updateDragDelta();
  24748. }
  24749. }
  24750. // prevent the dragging from triggering text selection on the page
  24751. preventDefault = true;
  24752. }
  24753. select[2] = pos[0];
  24754. select[3] = pos[1];
  24755. if (preventDefault) {
  24756. if (e.stopPropagation) e.stopPropagation();
  24757. if (e.preventDefault) e.preventDefault();
  24758. return false;
  24759. }
  24760. }, false);
  24761. var clickTimeout, didDoubleClick, prevClickTimeStamp;
  24762. r.registerBinding(containerWindow, 'mouseup', function mouseupHandler(e) {
  24763. // eslint-disable-line no-undef
  24764. // during left mouse button gestures, ignore other buttons
  24765. if (r.hoverData.which === 1 && e.which !== 1 && r.hoverData.capture) {
  24766. return;
  24767. }
  24768. var capture = r.hoverData.capture;
  24769. if (!capture) {
  24770. return;
  24771. }
  24772. r.hoverData.capture = false;
  24773. var cy = r.cy;
  24774. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  24775. var select = r.selection;
  24776. var near = r.findNearestElement(pos[0], pos[1], true, false);
  24777. var draggedElements = r.dragData.possibleDragElements;
  24778. var down = r.hoverData.down;
  24779. var multSelKeyDown = isMultSelKeyDown(e);
  24780. if (r.data.bgActivePosistion) {
  24781. r.redrawHint('select', true);
  24782. r.redraw();
  24783. }
  24784. r.hoverData.tapholdCancelled = true;
  24785. r.data.bgActivePosistion = undefined; // not active bg now
  24786. if (down) {
  24787. down.unactivate();
  24788. }
  24789. var makeEvent = function makeEvent(type) {
  24790. return {
  24791. originalEvent: e,
  24792. type: type,
  24793. position: {
  24794. x: pos[0],
  24795. y: pos[1]
  24796. }
  24797. };
  24798. };
  24799. if (r.hoverData.which === 3) {
  24800. var cxtEvt = makeEvent('cxttapend');
  24801. if (down) {
  24802. down.emit(cxtEvt);
  24803. } else {
  24804. cy.emit(cxtEvt);
  24805. }
  24806. if (!r.hoverData.cxtDragged) {
  24807. var cxtTap = makeEvent('cxttap');
  24808. if (down) {
  24809. down.emit(cxtTap);
  24810. } else {
  24811. cy.emit(cxtTap);
  24812. }
  24813. }
  24814. r.hoverData.cxtDragged = false;
  24815. r.hoverData.which = null;
  24816. } else if (r.hoverData.which === 1) {
  24817. triggerEvents(near, ['mouseup', 'tapend', 'vmouseup'], e, {
  24818. x: pos[0],
  24819. y: pos[1]
  24820. });
  24821. if (!r.dragData.didDrag &&
  24822. // didn't move a node around
  24823. !r.hoverData.dragged &&
  24824. // didn't pan
  24825. !r.hoverData.selecting &&
  24826. // not box selection
  24827. !r.hoverData.isOverThresholdDrag // didn't move too much
  24828. ) {
  24829. triggerEvents(down, ["click", "tap", "vclick"], e, {
  24830. x: pos[0],
  24831. y: pos[1]
  24832. });
  24833. didDoubleClick = false;
  24834. if (e.timeStamp - prevClickTimeStamp <= cy.multiClickDebounceTime()) {
  24835. clickTimeout && clearTimeout(clickTimeout);
  24836. didDoubleClick = true;
  24837. prevClickTimeStamp = null;
  24838. triggerEvents(down, ["dblclick", "dbltap", "vdblclick"], e, {
  24839. x: pos[0],
  24840. y: pos[1]
  24841. });
  24842. } else {
  24843. clickTimeout = setTimeout(function () {
  24844. if (didDoubleClick) return;
  24845. triggerEvents(down, ["oneclick", "onetap", "voneclick"], e, {
  24846. x: pos[0],
  24847. y: pos[1]
  24848. });
  24849. }, cy.multiClickDebounceTime());
  24850. prevClickTimeStamp = e.timeStamp;
  24851. }
  24852. }
  24853. // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something
  24854. if (down == null // not mousedown on node
  24855. && !r.dragData.didDrag // didn't move the node around
  24856. && !r.hoverData.selecting // not box selection
  24857. && !r.hoverData.dragged // didn't pan
  24858. && !isMultSelKeyDown(e)) {
  24859. cy.$(isSelected).unselect(['tapunselect']);
  24860. if (draggedElements.length > 0) {
  24861. r.redrawHint('eles', true);
  24862. }
  24863. r.dragData.possibleDragElements = draggedElements = cy.collection();
  24864. }
  24865. // Single selection
  24866. if (near == down && !r.dragData.didDrag && !r.hoverData.selecting) {
  24867. if (near != null && near._private.selectable) {
  24868. if (r.hoverData.dragging) ; else if (cy.selectionType() === 'additive' || multSelKeyDown) {
  24869. if (near.selected()) {
  24870. near.unselect(['tapunselect']);
  24871. } else {
  24872. near.select(['tapselect']);
  24873. }
  24874. } else {
  24875. if (!multSelKeyDown) {
  24876. cy.$(isSelected).unmerge(near).unselect(['tapunselect']);
  24877. near.select(['tapselect']);
  24878. }
  24879. }
  24880. r.redrawHint('eles', true);
  24881. }
  24882. }
  24883. if (r.hoverData.selecting) {
  24884. var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
  24885. r.redrawHint('select', true);
  24886. if (box.length > 0) {
  24887. r.redrawHint('eles', true);
  24888. }
  24889. cy.emit(makeEvent('boxend'));
  24890. var eleWouldBeSelected = function eleWouldBeSelected(ele) {
  24891. return ele.selectable() && !ele.selected();
  24892. };
  24893. if (cy.selectionType() === 'additive') {
  24894. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  24895. } else {
  24896. if (!multSelKeyDown) {
  24897. cy.$(isSelected).unmerge(box).unselect();
  24898. }
  24899. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  24900. }
  24901. // always need redraw in case eles unselectable
  24902. r.redraw();
  24903. }
  24904. // Cancel drag pan
  24905. if (r.hoverData.dragging) {
  24906. r.hoverData.dragging = false;
  24907. r.redrawHint('select', true);
  24908. r.redrawHint('eles', true);
  24909. r.redraw();
  24910. }
  24911. if (!select[4]) {
  24912. r.redrawHint('drag', true);
  24913. r.redrawHint('eles', true);
  24914. var downWasGrabbed = down && down.grabbed();
  24915. freeDraggedElements(draggedElements);
  24916. if (downWasGrabbed) {
  24917. down.emit(makeEvent('freeon'));
  24918. draggedElements.emit(makeEvent('free'));
  24919. if (r.dragData.didDrag) {
  24920. down.emit(makeEvent('dragfreeon'));
  24921. draggedElements.emit(makeEvent('dragfree'));
  24922. }
  24923. }
  24924. }
  24925. } // else not right mouse
  24926. select[4] = 0;
  24927. r.hoverData.down = null;
  24928. r.hoverData.cxtStarted = false;
  24929. r.hoverData.draggingEles = false;
  24930. r.hoverData.selecting = false;
  24931. r.hoverData.isOverThresholdDrag = false;
  24932. r.dragData.didDrag = false;
  24933. r.hoverData.dragged = false;
  24934. r.hoverData.dragDelta = [];
  24935. r.hoverData.mdownPos = null;
  24936. r.hoverData.mdownGPos = null;
  24937. r.hoverData.which = null;
  24938. }, false);
  24939. var wheelDeltas = []; // log of first N wheel deltas
  24940. var wheelDeltaN = 4; // how many events to log
  24941. var inaccurateScrollDevice;
  24942. var inaccurateScrollFactor = 100000; // base of inaccurate wheel deltas (e.g. base 5 could yield wheels of 10, 25, 50, etc.)
  24943. var allAreDivisibleBy = function allAreDivisibleBy(list, factor) {
  24944. for (var i = 0; i < list.length; i++) {
  24945. if (list[i] % factor !== 0) {
  24946. return false;
  24947. }
  24948. }
  24949. return true;
  24950. };
  24951. var allAreSameMagnitude = function allAreSameMagnitude(list) {
  24952. var firstMag = Math.abs(list[0]);
  24953. for (var i = 1; i < list.length; i++) {
  24954. if (Math.abs(list[i]) !== firstMag) {
  24955. return false;
  24956. }
  24957. }
  24958. return true;
  24959. };
  24960. var wheelHandler = function wheelHandler(e) {
  24961. var clamp = false;
  24962. var delta = e.deltaY;
  24963. if (delta == null) {
  24964. // compatibility with old browsers
  24965. if (e.wheelDeltaY != null) {
  24966. delta = e.wheelDeltaY / 4;
  24967. } else if (e.wheelDelta != null) {
  24968. delta = e.wheelDelta / 4;
  24969. }
  24970. }
  24971. if (delta === 0) {
  24972. return; // no change in zoom (Bug: Zoom becomes erratic on rapid scroll due to deltaY: 0 event #3394)
  24973. }
  24974. if (inaccurateScrollDevice == null) {
  24975. if (wheelDeltas.length >= wheelDeltaN) {
  24976. // use log to determine if inaccurate
  24977. var wds = wheelDeltas;
  24978. inaccurateScrollDevice = allAreDivisibleBy(wds, 5);
  24979. if (!inaccurateScrollDevice) {
  24980. // check for all large values of exact same magnitude
  24981. var firstMag = Math.abs(wds[0]);
  24982. inaccurateScrollDevice = allAreSameMagnitude(wds) && firstMag > 5;
  24983. }
  24984. if (inaccurateScrollDevice) {
  24985. for (var i = 0; i < wds.length; i++) {
  24986. inaccurateScrollFactor = Math.min(Math.abs(wds[i]), inaccurateScrollFactor);
  24987. }
  24988. }
  24989. // console.log('Sampled wheel deltas:', wds);
  24990. // console.log('inaccurateScrollDevice:', inaccurateScrollDevice);
  24991. // console.log('inaccurateScrollFactor:', inaccurateScrollFactor);
  24992. } else {
  24993. // clamp and log until we reach N
  24994. wheelDeltas.push(delta);
  24995. clamp = true;
  24996. // console.log('Clamping initial wheel events until we get a good sample');
  24997. }
  24998. } else if (inaccurateScrollDevice) {
  24999. // keep updating
  25000. inaccurateScrollFactor = Math.min(Math.abs(delta), inaccurateScrollFactor);
  25001. // console.log('Keep updating inaccurateScrollFactor beyond sample in case we did not get the smallest possible val:', inaccurateScrollFactor);
  25002. }
  25003. if (r.scrollingPage) {
  25004. return;
  25005. } // while scrolling, ignore wheel-to-zoom
  25006. var cy = r.cy;
  25007. var zoom = cy.zoom();
  25008. var pan = cy.pan();
  25009. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25010. var rpos = [pos[0] * zoom + pan.x, pos[1] * zoom + pan.y];
  25011. if (r.hoverData.draggingEles || r.hoverData.dragging || r.hoverData.cxtStarted || inBoxSelection()) {
  25012. // if pan dragging or cxt dragging, wheel movements make no zoom
  25013. e.preventDefault();
  25014. return;
  25015. }
  25016. if (cy.panningEnabled() && cy.userPanningEnabled() && cy.zoomingEnabled() && cy.userZoomingEnabled()) {
  25017. e.preventDefault();
  25018. r.data.wheelZooming = true;
  25019. clearTimeout(r.data.wheelTimeout);
  25020. r.data.wheelTimeout = setTimeout(function () {
  25021. r.data.wheelZooming = false;
  25022. r.redrawHint('eles', true);
  25023. r.redraw();
  25024. }, 150);
  25025. var diff;
  25026. if (clamp && Math.abs(delta) > 5) {
  25027. delta = signum(delta) * 5;
  25028. }
  25029. diff = delta / -250;
  25030. if (inaccurateScrollDevice) {
  25031. diff /= inaccurateScrollFactor;
  25032. diff *= 3;
  25033. }
  25034. diff = diff * r.wheelSensitivity;
  25035. // console.log(`delta = ${delta}, diff = ${diff}, mode = ${e.deltaMode}`)
  25036. var needsWheelFix = e.deltaMode === 1;
  25037. if (needsWheelFix) {
  25038. // fixes slow wheel events on ff/linux and ff/windows
  25039. diff *= 33;
  25040. }
  25041. var newZoom = cy.zoom() * Math.pow(10, diff);
  25042. if (e.type === 'gesturechange') {
  25043. newZoom = r.gestureStartZoom * e.scale;
  25044. }
  25045. cy.zoom({
  25046. level: newZoom,
  25047. renderedPosition: {
  25048. x: rpos[0],
  25049. y: rpos[1]
  25050. }
  25051. });
  25052. cy.emit({
  25053. type: e.type === 'gesturechange' ? 'pinchzoom' : 'scrollzoom',
  25054. originalEvent: e,
  25055. position: {
  25056. x: pos[0],
  25057. y: pos[1]
  25058. }
  25059. });
  25060. }
  25061. };
  25062. // Functions to help with whether mouse wheel should trigger zooming
  25063. // --
  25064. r.registerBinding(r.container, 'wheel', wheelHandler, true);
  25065. // disable nonstandard wheel events
  25066. // r.registerBinding(r.container, 'mousewheel', wheelHandler, true);
  25067. // r.registerBinding(r.container, 'DOMMouseScroll', wheelHandler, true);
  25068. // r.registerBinding(r.container, 'MozMousePixelScroll', wheelHandler, true); // older firefox
  25069. r.registerBinding(containerWindow, 'scroll', function scrollHandler(e) {
  25070. // eslint-disable-line no-unused-vars
  25071. r.scrollingPage = true;
  25072. clearTimeout(r.scrollingPageTimeout);
  25073. r.scrollingPageTimeout = setTimeout(function () {
  25074. r.scrollingPage = false;
  25075. }, 250);
  25076. }, true);
  25077. // desktop safari pinch to zoom start
  25078. r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {
  25079. r.gestureStartZoom = r.cy.zoom();
  25080. if (!r.hasTouchStarted) {
  25081. // don't affect touch devices like iphone
  25082. e.preventDefault();
  25083. }
  25084. }, true);
  25085. r.registerBinding(r.container, 'gesturechange', function (e) {
  25086. if (!r.hasTouchStarted) {
  25087. // don't affect touch devices like iphone
  25088. wheelHandler(e);
  25089. }
  25090. }, true);
  25091. // Functions to help with handling mouseout/mouseover on the Cytoscape container
  25092. // Handle mouseout on Cytoscape container
  25093. r.registerBinding(r.container, 'mouseout', function mouseOutHandler(e) {
  25094. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25095. r.cy.emit({
  25096. originalEvent: e,
  25097. type: 'mouseout',
  25098. position: {
  25099. x: pos[0],
  25100. y: pos[1]
  25101. }
  25102. });
  25103. }, false);
  25104. r.registerBinding(r.container, 'mouseover', function mouseOverHandler(e) {
  25105. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25106. r.cy.emit({
  25107. originalEvent: e,
  25108. type: 'mouseover',
  25109. position: {
  25110. x: pos[0],
  25111. y: pos[1]
  25112. }
  25113. });
  25114. }, false);
  25115. var f1x1, f1y1, f2x1, f2y1; // starting points for pinch-to-zoom
  25116. var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom
  25117. var center1, modelCenter1; // center point on start pinch to zoom
  25118. var offsetLeft, offsetTop;
  25119. var containerWidth, containerHeight;
  25120. var twoFingersStartInside;
  25121. var distance = function distance(x1, y1, x2, y2) {
  25122. return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  25123. };
  25124. var distanceSq = function distanceSq(x1, y1, x2, y2) {
  25125. return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
  25126. };
  25127. var touchstartHandler;
  25128. r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {
  25129. r.hasTouchStarted = true;
  25130. if (!eventInContainer(e)) {
  25131. return;
  25132. }
  25133. blurActiveDomElement();
  25134. r.touchData.capture = true;
  25135. r.data.bgActivePosistion = undefined;
  25136. var cy = r.cy;
  25137. var now = r.touchData.now;
  25138. var earlier = r.touchData.earlier;
  25139. if (e.touches[0]) {
  25140. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25141. now[0] = pos[0];
  25142. now[1] = pos[1];
  25143. }
  25144. if (e.touches[1]) {
  25145. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25146. now[2] = pos[0];
  25147. now[3] = pos[1];
  25148. }
  25149. if (e.touches[2]) {
  25150. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25151. now[4] = pos[0];
  25152. now[5] = pos[1];
  25153. }
  25154. var makeEvent = function makeEvent(type) {
  25155. return {
  25156. originalEvent: e,
  25157. type: type,
  25158. position: {
  25159. x: now[0],
  25160. y: now[1]
  25161. }
  25162. };
  25163. };
  25164. // record starting points for pinch-to-zoom
  25165. if (e.touches[1]) {
  25166. r.touchData.singleTouchMoved = true;
  25167. freeDraggedElements(r.dragData.touchDragEles);
  25168. var offsets = r.findContainerClientCoords();
  25169. offsetLeft = offsets[0];
  25170. offsetTop = offsets[1];
  25171. containerWidth = offsets[2];
  25172. containerHeight = offsets[3];
  25173. f1x1 = e.touches[0].clientX - offsetLeft;
  25174. f1y1 = e.touches[0].clientY - offsetTop;
  25175. f2x1 = e.touches[1].clientX - offsetLeft;
  25176. f2y1 = e.touches[1].clientY - offsetTop;
  25177. twoFingersStartInside = 0 <= f1x1 && f1x1 <= containerWidth && 0 <= f2x1 && f2x1 <= containerWidth && 0 <= f1y1 && f1y1 <= containerHeight && 0 <= f2y1 && f2y1 <= containerHeight;
  25178. var pan = cy.pan();
  25179. var zoom = cy.zoom();
  25180. distance1 = distance(f1x1, f1y1, f2x1, f2y1);
  25181. distance1Sq = distanceSq(f1x1, f1y1, f2x1, f2y1);
  25182. center1 = [(f1x1 + f2x1) / 2, (f1y1 + f2y1) / 2];
  25183. modelCenter1 = [(center1[0] - pan.x) / zoom, (center1[1] - pan.y) / zoom];
  25184. // consider context tap
  25185. var cxtDistThreshold = 200;
  25186. var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;
  25187. if (distance1Sq < cxtDistThresholdSq && !e.touches[2]) {
  25188. var near1 = r.findNearestElement(now[0], now[1], true, true);
  25189. var near2 = r.findNearestElement(now[2], now[3], true, true);
  25190. if (near1 && near1.isNode()) {
  25191. near1.activate().emit(makeEvent('cxttapstart'));
  25192. r.touchData.start = near1;
  25193. } else if (near2 && near2.isNode()) {
  25194. near2.activate().emit(makeEvent('cxttapstart'));
  25195. r.touchData.start = near2;
  25196. } else {
  25197. cy.emit(makeEvent('cxttapstart'));
  25198. }
  25199. if (r.touchData.start) {
  25200. r.touchData.start._private.grabbed = false;
  25201. }
  25202. r.touchData.cxt = true;
  25203. r.touchData.cxtDragged = false;
  25204. r.data.bgActivePosistion = undefined;
  25205. r.redraw();
  25206. return;
  25207. }
  25208. }
  25209. if (e.touches[2]) {
  25210. // ignore
  25211. // safari on ios pans the page otherwise (normally you should be able to preventdefault on touchmove...)
  25212. if (cy.boxSelectionEnabled()) {
  25213. e.preventDefault();
  25214. }
  25215. } else if (e.touches[1]) ; else if (e.touches[0]) {
  25216. var nears = r.findNearestElements(now[0], now[1], true, true);
  25217. var near = nears[0];
  25218. if (near != null) {
  25219. near.activate();
  25220. r.touchData.start = near;
  25221. r.touchData.starts = nears;
  25222. if (r.nodeIsGrabbable(near)) {
  25223. var draggedEles = r.dragData.touchDragEles = cy.collection();
  25224. var selectedNodes = null;
  25225. r.redrawHint('eles', true);
  25226. r.redrawHint('drag', true);
  25227. if (near.selected()) {
  25228. // reset drag elements, since near will be added again
  25229. selectedNodes = cy.$(function (ele) {
  25230. return ele.selected() && r.nodeIsGrabbable(ele);
  25231. });
  25232. addNodesToDrag(selectedNodes, {
  25233. addToList: draggedEles
  25234. });
  25235. } else {
  25236. addNodeToDrag(near, {
  25237. addToList: draggedEles
  25238. });
  25239. }
  25240. setGrabTarget(near);
  25241. near.emit(makeEvent('grabon'));
  25242. if (selectedNodes) {
  25243. selectedNodes.forEach(function (n) {
  25244. n.emit(makeEvent('grab'));
  25245. });
  25246. } else {
  25247. near.emit(makeEvent('grab'));
  25248. }
  25249. }
  25250. }
  25251. triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {
  25252. x: now[0],
  25253. y: now[1]
  25254. });
  25255. if (near == null) {
  25256. r.data.bgActivePosistion = {
  25257. x: pos[0],
  25258. y: pos[1]
  25259. };
  25260. r.redrawHint('select', true);
  25261. r.redraw();
  25262. }
  25263. // Tap, taphold
  25264. // -----
  25265. r.touchData.singleTouchMoved = false;
  25266. r.touchData.singleTouchStartTime = +new Date();
  25267. clearTimeout(r.touchData.tapholdTimeout);
  25268. r.touchData.tapholdTimeout = setTimeout(function () {
  25269. if (r.touchData.singleTouchMoved === false && !r.pinching // if pinching, then taphold unselect shouldn't take effect
  25270. && !r.touchData.selecting // box selection shouldn't allow taphold through
  25271. ) {
  25272. triggerEvents(r.touchData.start, ['taphold'], e, {
  25273. x: now[0],
  25274. y: now[1]
  25275. });
  25276. }
  25277. }, r.tapholdDuration);
  25278. }
  25279. if (e.touches.length >= 1) {
  25280. var sPos = r.touchData.startPosition = [null, null, null, null, null, null];
  25281. for (var i = 0; i < now.length; i++) {
  25282. sPos[i] = earlier[i] = now[i];
  25283. }
  25284. var touch0 = e.touches[0];
  25285. r.touchData.startGPosition = [touch0.clientX, touch0.clientY];
  25286. }
  25287. }, false);
  25288. var touchmoveHandler;
  25289. r.registerBinding(containerWindow, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {
  25290. // eslint-disable-line no-undef
  25291. var capture = r.touchData.capture;
  25292. if (!capture && !eventInContainer(e)) {
  25293. return;
  25294. }
  25295. var select = r.selection;
  25296. var cy = r.cy;
  25297. var now = r.touchData.now;
  25298. var earlier = r.touchData.earlier;
  25299. var zoom = cy.zoom();
  25300. if (e.touches[0]) {
  25301. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25302. now[0] = pos[0];
  25303. now[1] = pos[1];
  25304. }
  25305. if (e.touches[1]) {
  25306. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25307. now[2] = pos[0];
  25308. now[3] = pos[1];
  25309. }
  25310. if (e.touches[2]) {
  25311. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25312. now[4] = pos[0];
  25313. now[5] = pos[1];
  25314. }
  25315. var makeEvent = function makeEvent(type) {
  25316. return {
  25317. originalEvent: e,
  25318. type: type,
  25319. position: {
  25320. x: now[0],
  25321. y: now[1]
  25322. }
  25323. };
  25324. };
  25325. var startGPos = r.touchData.startGPosition;
  25326. var isOverThresholdDrag;
  25327. if (capture && e.touches[0] && startGPos) {
  25328. var disp = [];
  25329. for (var j = 0; j < now.length; j++) {
  25330. disp[j] = now[j] - earlier[j];
  25331. }
  25332. var dx = e.touches[0].clientX - startGPos[0];
  25333. var dx2 = dx * dx;
  25334. var dy = e.touches[0].clientY - startGPos[1];
  25335. var dy2 = dy * dy;
  25336. var dist2 = dx2 + dy2;
  25337. isOverThresholdDrag = dist2 >= r.touchTapThreshold2;
  25338. }
  25339. // context swipe cancelling
  25340. if (capture && r.touchData.cxt) {
  25341. e.preventDefault();
  25342. var f1x2 = e.touches[0].clientX - offsetLeft,
  25343. f1y2 = e.touches[0].clientY - offsetTop;
  25344. var f2x2 = e.touches[1].clientX - offsetLeft,
  25345. f2y2 = e.touches[1].clientY - offsetTop;
  25346. // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );
  25347. var distance2Sq = distanceSq(f1x2, f1y2, f2x2, f2y2);
  25348. var factorSq = distance2Sq / distance1Sq;
  25349. var distThreshold = 150;
  25350. var distThresholdSq = distThreshold * distThreshold;
  25351. var factorThreshold = 1.5;
  25352. var factorThresholdSq = factorThreshold * factorThreshold;
  25353. // cancel ctx gestures if the distance b/t the fingers increases
  25354. if (factorSq >= factorThresholdSq || distance2Sq >= distThresholdSq) {
  25355. r.touchData.cxt = false;
  25356. r.data.bgActivePosistion = undefined;
  25357. r.redrawHint('select', true);
  25358. var cxtEvt = makeEvent('cxttapend');
  25359. if (r.touchData.start) {
  25360. r.touchData.start.unactivate().emit(cxtEvt);
  25361. r.touchData.start = null;
  25362. } else {
  25363. cy.emit(cxtEvt);
  25364. }
  25365. }
  25366. }
  25367. // context swipe
  25368. if (capture && r.touchData.cxt) {
  25369. var cxtEvt = makeEvent('cxtdrag');
  25370. r.data.bgActivePosistion = undefined;
  25371. r.redrawHint('select', true);
  25372. if (r.touchData.start) {
  25373. r.touchData.start.emit(cxtEvt);
  25374. } else {
  25375. cy.emit(cxtEvt);
  25376. }
  25377. if (r.touchData.start) {
  25378. r.touchData.start._private.grabbed = false;
  25379. }
  25380. r.touchData.cxtDragged = true;
  25381. var near = r.findNearestElement(now[0], now[1], true, true);
  25382. if (!r.touchData.cxtOver || near !== r.touchData.cxtOver) {
  25383. if (r.touchData.cxtOver) {
  25384. r.touchData.cxtOver.emit(makeEvent('cxtdragout'));
  25385. }
  25386. r.touchData.cxtOver = near;
  25387. if (near) {
  25388. near.emit(makeEvent('cxtdragover'));
  25389. }
  25390. }
  25391. // box selection
  25392. } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {
  25393. e.preventDefault();
  25394. r.data.bgActivePosistion = undefined;
  25395. this.lastThreeTouch = +new Date();
  25396. if (!r.touchData.selecting) {
  25397. cy.emit(makeEvent('boxstart'));
  25398. }
  25399. r.touchData.selecting = true;
  25400. r.touchData.didSelect = true;
  25401. select[4] = 1;
  25402. if (!select || select.length === 0 || select[0] === undefined) {
  25403. select[0] = (now[0] + now[2] + now[4]) / 3;
  25404. select[1] = (now[1] + now[3] + now[5]) / 3;
  25405. select[2] = (now[0] + now[2] + now[4]) / 3 + 1;
  25406. select[3] = (now[1] + now[3] + now[5]) / 3 + 1;
  25407. } else {
  25408. select[2] = (now[0] + now[2] + now[4]) / 3;
  25409. select[3] = (now[1] + now[3] + now[5]) / 3;
  25410. }
  25411. r.redrawHint('select', true);
  25412. r.redraw();
  25413. // pinch to zoom
  25414. } else if (capture && e.touches[1] && !r.touchData.didSelect // don't allow box selection to degrade to pinch-to-zoom
  25415. && cy.zoomingEnabled() && cy.panningEnabled() && cy.userZoomingEnabled() && cy.userPanningEnabled()) {
  25416. // two fingers => pinch to zoom
  25417. e.preventDefault();
  25418. r.data.bgActivePosistion = undefined;
  25419. r.redrawHint('select', true);
  25420. var draggedEles = r.dragData.touchDragEles;
  25421. if (draggedEles) {
  25422. r.redrawHint('drag', true);
  25423. for (var i = 0; i < draggedEles.length; i++) {
  25424. var de_p = draggedEles[i]._private;
  25425. de_p.grabbed = false;
  25426. de_p.rscratch.inDragLayer = false;
  25427. }
  25428. }
  25429. var _start = r.touchData.start;
  25430. // (x2, y2) for fingers 1 and 2
  25431. var f1x2 = e.touches[0].clientX - offsetLeft,
  25432. f1y2 = e.touches[0].clientY - offsetTop;
  25433. var f2x2 = e.touches[1].clientX - offsetLeft,
  25434. f2y2 = e.touches[1].clientY - offsetTop;
  25435. var distance2 = distance(f1x2, f1y2, f2x2, f2y2);
  25436. // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );
  25437. // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );
  25438. var factor = distance2 / distance1;
  25439. if (twoFingersStartInside) {
  25440. // delta finger1
  25441. var df1x = f1x2 - f1x1;
  25442. var df1y = f1y2 - f1y1;
  25443. // delta finger 2
  25444. var df2x = f2x2 - f2x1;
  25445. var df2y = f2y2 - f2y1;
  25446. // translation is the normalised vector of the two fingers movement
  25447. // i.e. so pinching cancels out and moving together pans
  25448. var tx = (df1x + df2x) / 2;
  25449. var ty = (df1y + df2y) / 2;
  25450. // now calculate the zoom
  25451. var zoom1 = cy.zoom();
  25452. var zoom2 = zoom1 * factor;
  25453. var pan1 = cy.pan();
  25454. // the model center point converted to the current rendered pos
  25455. var ctrx = modelCenter1[0] * zoom1 + pan1.x;
  25456. var ctry = modelCenter1[1] * zoom1 + pan1.y;
  25457. var pan2 = {
  25458. x: -zoom2 / zoom1 * (ctrx - pan1.x - tx) + ctrx,
  25459. y: -zoom2 / zoom1 * (ctry - pan1.y - ty) + ctry
  25460. };
  25461. // remove dragged eles
  25462. if (_start && _start.active()) {
  25463. var draggedEles = r.dragData.touchDragEles;
  25464. freeDraggedElements(draggedEles);
  25465. r.redrawHint('drag', true);
  25466. r.redrawHint('eles', true);
  25467. _start.unactivate().emit(makeEvent('freeon'));
  25468. draggedEles.emit(makeEvent('free'));
  25469. if (r.dragData.didDrag) {
  25470. _start.emit(makeEvent('dragfreeon'));
  25471. draggedEles.emit(makeEvent('dragfree'));
  25472. }
  25473. }
  25474. cy.viewport({
  25475. zoom: zoom2,
  25476. pan: pan2,
  25477. cancelOnFailedZoom: true
  25478. });
  25479. cy.emit(makeEvent('pinchzoom'));
  25480. distance1 = distance2;
  25481. f1x1 = f1x2;
  25482. f1y1 = f1y2;
  25483. f2x1 = f2x2;
  25484. f2y1 = f2y2;
  25485. r.pinching = true;
  25486. }
  25487. // Re-project
  25488. if (e.touches[0]) {
  25489. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25490. now[0] = pos[0];
  25491. now[1] = pos[1];
  25492. }
  25493. if (e.touches[1]) {
  25494. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25495. now[2] = pos[0];
  25496. now[3] = pos[1];
  25497. }
  25498. if (e.touches[2]) {
  25499. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25500. now[4] = pos[0];
  25501. now[5] = pos[1];
  25502. }
  25503. } else if (e.touches[0] && !r.touchData.didSelect // don't allow box selection to degrade to single finger events like panning
  25504. ) {
  25505. var start = r.touchData.start;
  25506. var last = r.touchData.last;
  25507. var near;
  25508. if (!r.hoverData.draggingEles && !r.swipePanning) {
  25509. near = r.findNearestElement(now[0], now[1], true, true);
  25510. }
  25511. if (capture && start != null) {
  25512. e.preventDefault();
  25513. }
  25514. // dragging nodes
  25515. if (capture && start != null && r.nodeIsDraggable(start)) {
  25516. if (isOverThresholdDrag) {
  25517. // then dragging can happen
  25518. var draggedEles = r.dragData.touchDragEles;
  25519. var justStartedDrag = !r.dragData.didDrag;
  25520. if (justStartedDrag) {
  25521. addNodesToDrag(draggedEles, {
  25522. inDragLayer: true
  25523. });
  25524. }
  25525. r.dragData.didDrag = true;
  25526. var totalShift = {
  25527. x: 0,
  25528. y: 0
  25529. };
  25530. if (number$1(disp[0]) && number$1(disp[1])) {
  25531. totalShift.x += disp[0];
  25532. totalShift.y += disp[1];
  25533. if (justStartedDrag) {
  25534. r.redrawHint('eles', true);
  25535. var dragDelta = r.touchData.dragDelta;
  25536. if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
  25537. totalShift.x += dragDelta[0];
  25538. totalShift.y += dragDelta[1];
  25539. }
  25540. }
  25541. }
  25542. r.hoverData.draggingEles = true;
  25543. draggedEles.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
  25544. r.redrawHint('drag', true);
  25545. if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {
  25546. r.redrawHint('eles', true);
  25547. }
  25548. r.redraw();
  25549. } else {
  25550. // otherwise keep track of drag delta for later
  25551. var dragDelta = r.touchData.dragDelta = r.touchData.dragDelta || [];
  25552. if (dragDelta.length === 0) {
  25553. dragDelta.push(disp[0]);
  25554. dragDelta.push(disp[1]);
  25555. } else {
  25556. dragDelta[0] += disp[0];
  25557. dragDelta[1] += disp[1];
  25558. }
  25559. }
  25560. }
  25561. // touchmove
  25562. {
  25563. triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {
  25564. x: now[0],
  25565. y: now[1]
  25566. });
  25567. if ((!start || !start.grabbed()) && near != last) {
  25568. if (last) {
  25569. last.emit(makeEvent('tapdragout'));
  25570. }
  25571. if (near) {
  25572. near.emit(makeEvent('tapdragover'));
  25573. }
  25574. }
  25575. r.touchData.last = near;
  25576. }
  25577. // check to cancel taphold
  25578. if (capture) {
  25579. for (var i = 0; i < now.length; i++) {
  25580. if (now[i] && r.touchData.startPosition[i] && isOverThresholdDrag) {
  25581. r.touchData.singleTouchMoved = true;
  25582. }
  25583. }
  25584. }
  25585. // panning
  25586. if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {
  25587. var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);
  25588. if (allowPassthrough) {
  25589. e.preventDefault();
  25590. if (!r.data.bgActivePosistion) {
  25591. r.data.bgActivePosistion = array2point(r.touchData.startPosition);
  25592. }
  25593. if (r.swipePanning) {
  25594. cy.panBy({
  25595. x: disp[0] * zoom,
  25596. y: disp[1] * zoom
  25597. });
  25598. cy.emit(makeEvent('dragpan'));
  25599. } else if (isOverThresholdDrag) {
  25600. r.swipePanning = true;
  25601. cy.panBy({
  25602. x: dx * zoom,
  25603. y: dy * zoom
  25604. });
  25605. cy.emit(makeEvent('dragpan'));
  25606. if (start) {
  25607. start.unactivate();
  25608. r.redrawHint('select', true);
  25609. r.touchData.start = null;
  25610. }
  25611. }
  25612. }
  25613. // Re-project
  25614. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25615. now[0] = pos[0];
  25616. now[1] = pos[1];
  25617. }
  25618. }
  25619. for (var j = 0; j < now.length; j++) {
  25620. earlier[j] = now[j];
  25621. }
  25622. // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning
  25623. if (capture && e.touches.length > 0 && !r.hoverData.draggingEles && !r.swipePanning && r.data.bgActivePosistion != null) {
  25624. r.data.bgActivePosistion = undefined;
  25625. r.redrawHint('select', true);
  25626. r.redraw();
  25627. }
  25628. }, false);
  25629. var touchcancelHandler;
  25630. r.registerBinding(containerWindow, 'touchcancel', touchcancelHandler = function touchcancelHandler(e) {
  25631. // eslint-disable-line no-unused-vars
  25632. var start = r.touchData.start;
  25633. r.touchData.capture = false;
  25634. if (start) {
  25635. start.unactivate();
  25636. }
  25637. });
  25638. var touchendHandler, didDoubleTouch, touchTimeout, prevTouchTimeStamp;
  25639. r.registerBinding(containerWindow, 'touchend', touchendHandler = function touchendHandler(e) {
  25640. // eslint-disable-line no-unused-vars
  25641. var start = r.touchData.start;
  25642. var capture = r.touchData.capture;
  25643. if (capture) {
  25644. if (e.touches.length === 0) {
  25645. r.touchData.capture = false;
  25646. }
  25647. e.preventDefault();
  25648. } else {
  25649. return;
  25650. }
  25651. var select = r.selection;
  25652. r.swipePanning = false;
  25653. r.hoverData.draggingEles = false;
  25654. var cy = r.cy;
  25655. var zoom = cy.zoom();
  25656. var now = r.touchData.now;
  25657. var earlier = r.touchData.earlier;
  25658. if (e.touches[0]) {
  25659. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25660. now[0] = pos[0];
  25661. now[1] = pos[1];
  25662. }
  25663. if (e.touches[1]) {
  25664. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25665. now[2] = pos[0];
  25666. now[3] = pos[1];
  25667. }
  25668. if (e.touches[2]) {
  25669. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25670. now[4] = pos[0];
  25671. now[5] = pos[1];
  25672. }
  25673. var makeEvent = function makeEvent(type) {
  25674. return {
  25675. originalEvent: e,
  25676. type: type,
  25677. position: {
  25678. x: now[0],
  25679. y: now[1]
  25680. }
  25681. };
  25682. };
  25683. if (start) {
  25684. start.unactivate();
  25685. }
  25686. var ctxTapend;
  25687. if (r.touchData.cxt) {
  25688. ctxTapend = makeEvent('cxttapend');
  25689. if (start) {
  25690. start.emit(ctxTapend);
  25691. } else {
  25692. cy.emit(ctxTapend);
  25693. }
  25694. if (!r.touchData.cxtDragged) {
  25695. var ctxTap = makeEvent('cxttap');
  25696. if (start) {
  25697. start.emit(ctxTap);
  25698. } else {
  25699. cy.emit(ctxTap);
  25700. }
  25701. }
  25702. if (r.touchData.start) {
  25703. r.touchData.start._private.grabbed = false;
  25704. }
  25705. r.touchData.cxt = false;
  25706. r.touchData.start = null;
  25707. r.redraw();
  25708. return;
  25709. }
  25710. // no more box selection if we don't have three fingers
  25711. if (!e.touches[2] && cy.boxSelectionEnabled() && r.touchData.selecting) {
  25712. r.touchData.selecting = false;
  25713. var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
  25714. select[0] = undefined;
  25715. select[1] = undefined;
  25716. select[2] = undefined;
  25717. select[3] = undefined;
  25718. select[4] = 0;
  25719. r.redrawHint('select', true);
  25720. cy.emit(makeEvent('boxend'));
  25721. var eleWouldBeSelected = function eleWouldBeSelected(ele) {
  25722. return ele.selectable() && !ele.selected();
  25723. };
  25724. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  25725. if (box.nonempty()) {
  25726. r.redrawHint('eles', true);
  25727. }
  25728. r.redraw();
  25729. }
  25730. if (start != null) {
  25731. start.unactivate();
  25732. }
  25733. if (e.touches[2]) {
  25734. r.data.bgActivePosistion = undefined;
  25735. r.redrawHint('select', true);
  25736. } else if (e.touches[1]) ; else if (e.touches[0]) ; else if (!e.touches[0]) {
  25737. r.data.bgActivePosistion = undefined;
  25738. r.redrawHint('select', true);
  25739. var draggedEles = r.dragData.touchDragEles;
  25740. if (start != null) {
  25741. var startWasGrabbed = start._private.grabbed;
  25742. freeDraggedElements(draggedEles);
  25743. r.redrawHint('drag', true);
  25744. r.redrawHint('eles', true);
  25745. if (startWasGrabbed) {
  25746. start.emit(makeEvent('freeon'));
  25747. draggedEles.emit(makeEvent('free'));
  25748. if (r.dragData.didDrag) {
  25749. start.emit(makeEvent('dragfreeon'));
  25750. draggedEles.emit(makeEvent('dragfree'));
  25751. }
  25752. }
  25753. triggerEvents(start, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
  25754. x: now[0],
  25755. y: now[1]
  25756. });
  25757. start.unactivate();
  25758. r.touchData.start = null;
  25759. } else {
  25760. var near = r.findNearestElement(now[0], now[1], true, true);
  25761. triggerEvents(near, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
  25762. x: now[0],
  25763. y: now[1]
  25764. });
  25765. }
  25766. var dx = r.touchData.startPosition[0] - now[0];
  25767. var dx2 = dx * dx;
  25768. var dy = r.touchData.startPosition[1] - now[1];
  25769. var dy2 = dy * dy;
  25770. var dist2 = dx2 + dy2;
  25771. var rdist2 = dist2 * zoom * zoom;
  25772. // Tap event, roughly same as mouse click event for touch
  25773. if (!r.touchData.singleTouchMoved) {
  25774. if (!start) {
  25775. cy.$(':selected').unselect(['tapunselect']);
  25776. }
  25777. triggerEvents(start, ['tap', 'vclick'], e, {
  25778. x: now[0],
  25779. y: now[1]
  25780. });
  25781. didDoubleTouch = false;
  25782. if (e.timeStamp - prevTouchTimeStamp <= cy.multiClickDebounceTime()) {
  25783. touchTimeout && clearTimeout(touchTimeout);
  25784. didDoubleTouch = true;
  25785. prevTouchTimeStamp = null;
  25786. triggerEvents(start, ['dbltap', 'vdblclick'], e, {
  25787. x: now[0],
  25788. y: now[1]
  25789. });
  25790. } else {
  25791. touchTimeout = setTimeout(function () {
  25792. if (didDoubleTouch) return;
  25793. triggerEvents(start, ['onetap', 'voneclick'], e, {
  25794. x: now[0],
  25795. y: now[1]
  25796. });
  25797. }, cy.multiClickDebounceTime());
  25798. prevTouchTimeStamp = e.timeStamp;
  25799. }
  25800. }
  25801. // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance
  25802. if (start != null && !r.dragData.didDrag // didn't drag nodes around
  25803. && start._private.selectable && rdist2 < r.touchTapThreshold2 && !r.pinching // pinch to zoom should not affect selection
  25804. ) {
  25805. if (cy.selectionType() === 'single') {
  25806. cy.$(isSelected).unmerge(start).unselect(['tapunselect']);
  25807. start.select(['tapselect']);
  25808. } else {
  25809. if (start.selected()) {
  25810. start.unselect(['tapunselect']);
  25811. } else {
  25812. start.select(['tapselect']);
  25813. }
  25814. }
  25815. r.redrawHint('eles', true);
  25816. }
  25817. r.touchData.singleTouchMoved = true;
  25818. }
  25819. for (var j = 0; j < now.length; j++) {
  25820. earlier[j] = now[j];
  25821. }
  25822. r.dragData.didDrag = false; // reset for next touchstart
  25823. if (e.touches.length === 0) {
  25824. r.touchData.dragDelta = [];
  25825. r.touchData.startPosition = [null, null, null, null, null, null];
  25826. r.touchData.startGPosition = null;
  25827. r.touchData.didSelect = false;
  25828. }
  25829. if (e.touches.length < 2) {
  25830. if (e.touches.length === 1) {
  25831. // the old start global pos'n may not be the same finger that remains
  25832. r.touchData.startGPosition = [e.touches[0].clientX, e.touches[0].clientY];
  25833. }
  25834. r.pinching = false;
  25835. r.redrawHint('eles', true);
  25836. r.redraw();
  25837. }
  25838. //r.redraw();
  25839. }, false);
  25840. // fallback compatibility layer for ms pointer events
  25841. if (typeof TouchEvent === 'undefined') {
  25842. var pointers = [];
  25843. var makeTouch = function makeTouch(e) {
  25844. return {
  25845. clientX: e.clientX,
  25846. clientY: e.clientY,
  25847. force: 1,
  25848. identifier: e.pointerId,
  25849. pageX: e.pageX,
  25850. pageY: e.pageY,
  25851. radiusX: e.width / 2,
  25852. radiusY: e.height / 2,
  25853. screenX: e.screenX,
  25854. screenY: e.screenY,
  25855. target: e.target
  25856. };
  25857. };
  25858. var makePointer = function makePointer(e) {
  25859. return {
  25860. event: e,
  25861. touch: makeTouch(e)
  25862. };
  25863. };
  25864. var addPointer = function addPointer(e) {
  25865. pointers.push(makePointer(e));
  25866. };
  25867. var removePointer = function removePointer(e) {
  25868. for (var i = 0; i < pointers.length; i++) {
  25869. var p = pointers[i];
  25870. if (p.event.pointerId === e.pointerId) {
  25871. pointers.splice(i, 1);
  25872. return;
  25873. }
  25874. }
  25875. };
  25876. var updatePointer = function updatePointer(e) {
  25877. var p = pointers.filter(function (p) {
  25878. return p.event.pointerId === e.pointerId;
  25879. })[0];
  25880. p.event = e;
  25881. p.touch = makeTouch(e);
  25882. };
  25883. var addTouchesToEvent = function addTouchesToEvent(e) {
  25884. e.touches = pointers.map(function (p) {
  25885. return p.touch;
  25886. });
  25887. };
  25888. var pointerIsMouse = function pointerIsMouse(e) {
  25889. return e.pointerType === 'mouse' || e.pointerType === 4;
  25890. };
  25891. r.registerBinding(r.container, 'pointerdown', function (e) {
  25892. if (pointerIsMouse(e)) {
  25893. return;
  25894. } // mouse already handled
  25895. e.preventDefault();
  25896. addPointer(e);
  25897. addTouchesToEvent(e);
  25898. touchstartHandler(e);
  25899. });
  25900. r.registerBinding(r.container, 'pointerup', function (e) {
  25901. if (pointerIsMouse(e)) {
  25902. return;
  25903. } // mouse already handled
  25904. removePointer(e);
  25905. addTouchesToEvent(e);
  25906. touchendHandler(e);
  25907. });
  25908. r.registerBinding(r.container, 'pointercancel', function (e) {
  25909. if (pointerIsMouse(e)) {
  25910. return;
  25911. } // mouse already handled
  25912. removePointer(e);
  25913. addTouchesToEvent(e);
  25914. touchcancelHandler(e);
  25915. });
  25916. r.registerBinding(r.container, 'pointermove', function (e) {
  25917. if (pointerIsMouse(e)) {
  25918. return;
  25919. } // mouse already handled
  25920. e.preventDefault();
  25921. updatePointer(e);
  25922. addTouchesToEvent(e);
  25923. touchmoveHandler(e);
  25924. });
  25925. }
  25926. };
  25927. var BRp$2 = {};
  25928. BRp$2.generatePolygon = function (name, points) {
  25929. return this.nodeShapes[name] = {
  25930. renderer: this,
  25931. name: name,
  25932. points: points,
  25933. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  25934. this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);
  25935. },
  25936. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  25937. return polygonIntersectLine(x, y, this.points, nodeX, nodeY, width / 2, height / 2, padding);
  25938. },
  25939. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  25940. return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);
  25941. },
  25942. hasMiterBounds: name !== 'rectangle',
  25943. miterBounds: function miterBounds(centerX, centerY, width, height, strokeWidth, strokePosition) {
  25944. return miterBox(this.points, centerX, centerY, width, height, strokeWidth);
  25945. }
  25946. };
  25947. };
  25948. BRp$2.generateEllipse = function () {
  25949. return this.nodeShapes['ellipse'] = {
  25950. renderer: this,
  25951. name: 'ellipse',
  25952. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  25953. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
  25954. },
  25955. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  25956. return intersectLineEllipse(x, y, nodeX, nodeY, width / 2 + padding, height / 2 + padding);
  25957. },
  25958. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  25959. return checkInEllipse(x, y, width, height, centerX, centerY, padding);
  25960. }
  25961. };
  25962. };
  25963. BRp$2.generateRoundPolygon = function (name, points) {
  25964. return this.nodeShapes[name] = {
  25965. renderer: this,
  25966. name: name,
  25967. points: points,
  25968. getOrCreateCorners: function getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, field) {
  25969. if (rs[field] !== undefined && rs[field + '-cx'] === centerX && rs[field + '-cy'] === centerY) {
  25970. return rs[field];
  25971. }
  25972. rs[field] = new Array(points.length / 2);
  25973. rs[field + '-cx'] = centerX;
  25974. rs[field + '-cy'] = centerY;
  25975. var halfW = width / 2;
  25976. var halfH = height / 2;
  25977. cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(width, height) : cornerRadius;
  25978. var p = new Array(points.length / 2);
  25979. for (var _i = 0; _i < points.length / 2; _i++) {
  25980. p[_i] = {
  25981. x: centerX + halfW * points[_i * 2],
  25982. y: centerY + halfH * points[_i * 2 + 1]
  25983. };
  25984. }
  25985. var i,
  25986. p1,
  25987. p2,
  25988. p3,
  25989. len = p.length;
  25990. p1 = p[len - 1];
  25991. // for each point
  25992. for (i = 0; i < len; i++) {
  25993. p2 = p[i % len];
  25994. p3 = p[(i + 1) % len];
  25995. rs[field][i] = getRoundCorner(p1, p2, p3, cornerRadius);
  25996. p1 = p2;
  25997. p2 = p3;
  25998. }
  25999. return rs[field];
  26000. },
  26001. draw: function draw(context, centerX, centerY, width, height, cornerRadius, rs) {
  26002. this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'drawCorners'));
  26003. },
  26004. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius, rs) {
  26005. return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height, padding, this.getOrCreateCorners(nodeX, nodeY, width, height, cornerRadius, rs, 'corners'));
  26006. },
  26007. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius, rs) {
  26008. return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'corners'));
  26009. }
  26010. };
  26011. };
  26012. BRp$2.generateRoundRectangle = function () {
  26013. return this.nodeShapes['round-rectangle'] = this.nodeShapes['roundrectangle'] = {
  26014. renderer: this,
  26015. name: 'round-rectangle',
  26016. points: generateUnitNgonPointsFitToSquare(4, 0),
  26017. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26018. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
  26019. },
  26020. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26021. return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
  26022. },
  26023. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26024. var halfWidth = width / 2;
  26025. var halfHeight = height / 2;
  26026. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
  26027. cornerRadius = Math.min(halfWidth, halfHeight, cornerRadius);
  26028. var diam = cornerRadius * 2;
  26029. // Check hBox
  26030. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
  26031. return true;
  26032. }
  26033. // Check vBox
  26034. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
  26035. return true;
  26036. }
  26037. // Check top left quarter circle
  26038. if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
  26039. return true;
  26040. }
  26041. // Check top right quarter circle
  26042. if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
  26043. return true;
  26044. }
  26045. // Check bottom right quarter circle
  26046. if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
  26047. return true;
  26048. }
  26049. // Check bottom left quarter circle
  26050. if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
  26051. return true;
  26052. }
  26053. return false;
  26054. }
  26055. };
  26056. };
  26057. BRp$2.generateCutRectangle = function () {
  26058. return this.nodeShapes['cut-rectangle'] = this.nodeShapes['cutrectangle'] = {
  26059. renderer: this,
  26060. name: 'cut-rectangle',
  26061. cornerLength: getCutRectangleCornerLength(),
  26062. points: generateUnitNgonPointsFitToSquare(4, 0),
  26063. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26064. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, null, cornerRadius);
  26065. },
  26066. generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY, cornerRadius) {
  26067. var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
  26068. var hh = height / 2;
  26069. var hw = width / 2;
  26070. var xBegin = centerX - hw;
  26071. var xEnd = centerX + hw;
  26072. var yBegin = centerY - hh;
  26073. var yEnd = centerY + hh;
  26074. // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]
  26075. return {
  26076. topLeft: [xBegin, yBegin + cl, xBegin + cl, yBegin, xBegin + cl, yBegin + cl],
  26077. topRight: [xEnd - cl, yBegin, xEnd, yBegin + cl, xEnd - cl, yBegin + cl],
  26078. bottomRight: [xEnd, yEnd - cl, xEnd - cl, yEnd, xEnd - cl, yEnd - cl],
  26079. bottomLeft: [xBegin + cl, yEnd, xBegin, yEnd - cl, xBegin + cl, yEnd - cl]
  26080. };
  26081. },
  26082. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26083. var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY, cornerRadius);
  26084. var pts = [].concat.apply([], [cPts.topLeft.splice(0, 4), cPts.topRight.splice(0, 4), cPts.bottomRight.splice(0, 4), cPts.bottomLeft.splice(0, 4)]);
  26085. return polygonIntersectLine(x, y, pts, nodeX, nodeY);
  26086. },
  26087. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26088. var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
  26089. // Check hBox
  26090. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * cl, [0, -1], padding)) {
  26091. return true;
  26092. }
  26093. // Check vBox
  26094. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * cl, height, [0, -1], padding)) {
  26095. return true;
  26096. }
  26097. var cutTrianglePts = this.generateCutTrianglePts(width, height, centerX, centerY);
  26098. return pointInsidePolygonPoints(x, y, cutTrianglePts.topLeft) || pointInsidePolygonPoints(x, y, cutTrianglePts.topRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomLeft);
  26099. }
  26100. };
  26101. };
  26102. BRp$2.generateBarrel = function () {
  26103. return this.nodeShapes['barrel'] = {
  26104. renderer: this,
  26105. name: 'barrel',
  26106. points: generateUnitNgonPointsFitToSquare(4, 0),
  26107. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26108. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
  26109. },
  26110. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26111. // use two fixed t values for the bezier curve approximation
  26112. var t0 = 0.15;
  26113. var t1 = 0.5;
  26114. var t2 = 0.85;
  26115. var bPts = this.generateBarrelBezierPts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);
  26116. var approximateBarrelCurvePts = function approximateBarrelCurvePts(pts) {
  26117. // approximate curve pts based on the two t values
  26118. var m0 = qbezierPtAt({
  26119. x: pts[0],
  26120. y: pts[1]
  26121. }, {
  26122. x: pts[2],
  26123. y: pts[3]
  26124. }, {
  26125. x: pts[4],
  26126. y: pts[5]
  26127. }, t0);
  26128. var m1 = qbezierPtAt({
  26129. x: pts[0],
  26130. y: pts[1]
  26131. }, {
  26132. x: pts[2],
  26133. y: pts[3]
  26134. }, {
  26135. x: pts[4],
  26136. y: pts[5]
  26137. }, t1);
  26138. var m2 = qbezierPtAt({
  26139. x: pts[0],
  26140. y: pts[1]
  26141. }, {
  26142. x: pts[2],
  26143. y: pts[3]
  26144. }, {
  26145. x: pts[4],
  26146. y: pts[5]
  26147. }, t2);
  26148. return [pts[0], pts[1], m0.x, m0.y, m1.x, m1.y, m2.x, m2.y, pts[4], pts[5]];
  26149. };
  26150. var pts = [].concat(approximateBarrelCurvePts(bPts.topLeft), approximateBarrelCurvePts(bPts.topRight), approximateBarrelCurvePts(bPts.bottomRight), approximateBarrelCurvePts(bPts.bottomLeft));
  26151. return polygonIntersectLine(x, y, pts, nodeX, nodeY);
  26152. },
  26153. generateBarrelBezierPts: function generateBarrelBezierPts(width, height, centerX, centerY) {
  26154. var hh = height / 2;
  26155. var hw = width / 2;
  26156. var xBegin = centerX - hw;
  26157. var xEnd = centerX + hw;
  26158. var yBegin = centerY - hh;
  26159. var yEnd = centerY + hh;
  26160. var curveConstants = getBarrelCurveConstants(width, height);
  26161. var hOffset = curveConstants.heightOffset;
  26162. var wOffset = curveConstants.widthOffset;
  26163. var ctrlPtXOffset = curveConstants.ctrlPtOffsetPct * width;
  26164. // points are in clockwise order, inner (imaginary) control pt on [4, 5]
  26165. var pts = {
  26166. topLeft: [xBegin, yBegin + hOffset, xBegin + ctrlPtXOffset, yBegin, xBegin + wOffset, yBegin],
  26167. topRight: [xEnd - wOffset, yBegin, xEnd - ctrlPtXOffset, yBegin, xEnd, yBegin + hOffset],
  26168. bottomRight: [xEnd, yEnd - hOffset, xEnd - ctrlPtXOffset, yEnd, xEnd - wOffset, yEnd],
  26169. bottomLeft: [xBegin + wOffset, yEnd, xBegin + ctrlPtXOffset, yEnd, xBegin, yEnd - hOffset]
  26170. };
  26171. pts.topLeft.isTop = true;
  26172. pts.topRight.isTop = true;
  26173. pts.bottomLeft.isBottom = true;
  26174. pts.bottomRight.isBottom = true;
  26175. return pts;
  26176. },
  26177. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26178. var curveConstants = getBarrelCurveConstants(width, height);
  26179. var hOffset = curveConstants.heightOffset;
  26180. var wOffset = curveConstants.widthOffset;
  26181. // Check hBox
  26182. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {
  26183. return true;
  26184. }
  26185. // Check vBox
  26186. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {
  26187. return true;
  26188. }
  26189. var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);
  26190. var getCurveT = function getCurveT(x, y, curvePts) {
  26191. var x0 = curvePts[4];
  26192. var x1 = curvePts[2];
  26193. var x2 = curvePts[0];
  26194. var y0 = curvePts[5];
  26195. // var y1 = curvePts[ 3 ];
  26196. var y2 = curvePts[1];
  26197. var xMin = Math.min(x0, x2);
  26198. var xMax = Math.max(x0, x2);
  26199. var yMin = Math.min(y0, y2);
  26200. var yMax = Math.max(y0, y2);
  26201. if (xMin <= x && x <= xMax && yMin <= y && y <= yMax) {
  26202. var coeff = bezierPtsToQuadCoeff(x0, x1, x2);
  26203. var roots = solveQuadratic(coeff[0], coeff[1], coeff[2], x);
  26204. var validRoots = roots.filter(function (r) {
  26205. return 0 <= r && r <= 1;
  26206. });
  26207. if (validRoots.length > 0) {
  26208. return validRoots[0];
  26209. }
  26210. }
  26211. return null;
  26212. };
  26213. var curveRegions = Object.keys(barrelCurvePts);
  26214. for (var i = 0; i < curveRegions.length; i++) {
  26215. var corner = curveRegions[i];
  26216. var cornerPts = barrelCurvePts[corner];
  26217. var t = getCurveT(x, y, cornerPts);
  26218. if (t == null) {
  26219. continue;
  26220. }
  26221. var y0 = cornerPts[5];
  26222. var y1 = cornerPts[3];
  26223. var y2 = cornerPts[1];
  26224. var bezY = qbezierAt(y0, y1, y2, t);
  26225. if (cornerPts.isTop && bezY <= y) {
  26226. return true;
  26227. }
  26228. if (cornerPts.isBottom && y <= bezY) {
  26229. return true;
  26230. }
  26231. }
  26232. return false;
  26233. }
  26234. };
  26235. };
  26236. BRp$2.generateBottomRoundrectangle = function () {
  26237. return this.nodeShapes['bottom-round-rectangle'] = this.nodeShapes['bottomroundrectangle'] = {
  26238. renderer: this,
  26239. name: 'bottom-round-rectangle',
  26240. points: generateUnitNgonPointsFitToSquare(4, 0),
  26241. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26242. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
  26243. },
  26244. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26245. var topStartX = nodeX - (width / 2 + padding);
  26246. var topStartY = nodeY - (height / 2 + padding);
  26247. var topEndY = topStartY;
  26248. var topEndX = nodeX + (width / 2 + padding);
  26249. var topIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
  26250. if (topIntersections.length > 0) {
  26251. return topIntersections;
  26252. }
  26253. return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
  26254. },
  26255. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26256. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
  26257. var diam = 2 * cornerRadius;
  26258. // Check hBox
  26259. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
  26260. return true;
  26261. }
  26262. // Check vBox
  26263. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
  26264. return true;
  26265. }
  26266. // check non-rounded top side
  26267. var outerWidth = width / 2 + 2 * padding;
  26268. var outerHeight = height / 2 + 2 * padding;
  26269. var points = [centerX - outerWidth, centerY - outerHeight, centerX - outerWidth, centerY, centerX + outerWidth, centerY, centerX + outerWidth, centerY - outerHeight];
  26270. if (pointInsidePolygonPoints(x, y, points)) {
  26271. return true;
  26272. }
  26273. // Check bottom right quarter circle
  26274. if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
  26275. return true;
  26276. }
  26277. // Check bottom left quarter circle
  26278. if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
  26279. return true;
  26280. }
  26281. return false;
  26282. }
  26283. };
  26284. };
  26285. BRp$2.registerNodeShapes = function () {
  26286. var nodeShapes = this.nodeShapes = {};
  26287. var renderer = this;
  26288. this.generateEllipse();
  26289. this.generatePolygon('triangle', generateUnitNgonPointsFitToSquare(3, 0));
  26290. this.generateRoundPolygon('round-triangle', generateUnitNgonPointsFitToSquare(3, 0));
  26291. this.generatePolygon('rectangle', generateUnitNgonPointsFitToSquare(4, 0));
  26292. nodeShapes['square'] = nodeShapes['rectangle'];
  26293. this.generateRoundRectangle();
  26294. this.generateCutRectangle();
  26295. this.generateBarrel();
  26296. this.generateBottomRoundrectangle();
  26297. {
  26298. var diamondPoints = [0, 1, 1, 0, 0, -1, -1, 0];
  26299. this.generatePolygon('diamond', diamondPoints);
  26300. this.generateRoundPolygon('round-diamond', diamondPoints);
  26301. }
  26302. this.generatePolygon('pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  26303. this.generateRoundPolygon('round-pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  26304. this.generatePolygon('hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  26305. this.generateRoundPolygon('round-hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  26306. this.generatePolygon('heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  26307. this.generateRoundPolygon('round-heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  26308. this.generatePolygon('octagon', generateUnitNgonPointsFitToSquare(8, 0));
  26309. this.generateRoundPolygon('round-octagon', generateUnitNgonPointsFitToSquare(8, 0));
  26310. var star5Points = new Array(20);
  26311. {
  26312. var outerPoints = generateUnitNgonPoints(5, 0);
  26313. var innerPoints = generateUnitNgonPoints(5, Math.PI / 5);
  26314. // Outer radius is 1; inner radius of star is smaller
  26315. var innerRadius = 0.5 * (3 - Math.sqrt(5));
  26316. innerRadius *= 1.57;
  26317. for (var i = 0; i < innerPoints.length / 2; i++) {
  26318. innerPoints[i * 2] *= innerRadius;
  26319. innerPoints[i * 2 + 1] *= innerRadius;
  26320. }
  26321. for (var i = 0; i < 20 / 4; i++) {
  26322. star5Points[i * 4] = outerPoints[i * 2];
  26323. star5Points[i * 4 + 1] = outerPoints[i * 2 + 1];
  26324. star5Points[i * 4 + 2] = innerPoints[i * 2];
  26325. star5Points[i * 4 + 3] = innerPoints[i * 2 + 1];
  26326. }
  26327. }
  26328. star5Points = fitPolygonToSquare(star5Points);
  26329. this.generatePolygon('star', star5Points);
  26330. this.generatePolygon('vee', [-1, -1, 0, -0.333, 1, -1, 0, 1]);
  26331. this.generatePolygon('rhomboid', [-1, -1, 0.333, -1, 1, 1, -0.333, 1]);
  26332. this.generatePolygon('right-rhomboid', [-0.333, -1, 1, -1, 0.333, 1, -1, 1]);
  26333. this.nodeShapes['concavehexagon'] = this.generatePolygon('concave-hexagon', [-1, -0.95, -0.75, 0, -1, 0.95, 1, 0.95, 0.75, 0, 1, -0.95]);
  26334. {
  26335. var tagPoints = [-1, -1, 0.25, -1, 1, 0, 0.25, 1, -1, 1];
  26336. this.generatePolygon('tag', tagPoints);
  26337. this.generateRoundPolygon('round-tag', tagPoints);
  26338. }
  26339. nodeShapes.makePolygon = function (points) {
  26340. // use caching on user-specified polygons so they are as fast as native shapes
  26341. var key = points.join('$');
  26342. var name = 'polygon-' + key;
  26343. var shape;
  26344. if (shape = this[name]) {
  26345. // got cached shape
  26346. return shape;
  26347. }
  26348. // create and cache new shape
  26349. return renderer.generatePolygon(name, points);
  26350. };
  26351. };
  26352. var BRp$1 = {};
  26353. BRp$1.timeToRender = function () {
  26354. return this.redrawTotalTime / this.redrawCount;
  26355. };
  26356. BRp$1.redraw = function (options) {
  26357. options = options || staticEmptyObject();
  26358. var r = this;
  26359. if (r.averageRedrawTime === undefined) {
  26360. r.averageRedrawTime = 0;
  26361. }
  26362. if (r.lastRedrawTime === undefined) {
  26363. r.lastRedrawTime = 0;
  26364. }
  26365. if (r.lastDrawTime === undefined) {
  26366. r.lastDrawTime = 0;
  26367. }
  26368. r.requestedFrame = true;
  26369. r.renderOptions = options;
  26370. };
  26371. BRp$1.beforeRender = function (fn, priority) {
  26372. // the renderer can't add tick callbacks when destroyed
  26373. if (this.destroyed) {
  26374. return;
  26375. }
  26376. if (priority == null) {
  26377. error('Priority is not optional for beforeRender');
  26378. }
  26379. var cbs = this.beforeRenderCallbacks;
  26380. cbs.push({
  26381. fn: fn,
  26382. priority: priority
  26383. });
  26384. // higher priority callbacks executed first
  26385. cbs.sort(function (a, b) {
  26386. return b.priority - a.priority;
  26387. });
  26388. };
  26389. var beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {
  26390. var cbs = r.beforeRenderCallbacks;
  26391. for (var i = 0; i < cbs.length; i++) {
  26392. cbs[i].fn(willDraw, startTime);
  26393. }
  26394. };
  26395. BRp$1.startRenderLoop = function () {
  26396. var r = this;
  26397. var cy = r.cy;
  26398. if (r.renderLoopStarted) {
  26399. return;
  26400. } else {
  26401. r.renderLoopStarted = true;
  26402. }
  26403. var _renderFn = function renderFn(requestTime) {
  26404. if (r.destroyed) {
  26405. return;
  26406. }
  26407. if (cy.batching()) ; else if (r.requestedFrame && !r.skipFrame) {
  26408. beforeRenderCallbacks(r, true, requestTime);
  26409. var startTime = performanceNow();
  26410. r.render(r.renderOptions);
  26411. var endTime = r.lastDrawTime = performanceNow();
  26412. if (r.averageRedrawTime === undefined) {
  26413. r.averageRedrawTime = endTime - startTime;
  26414. }
  26415. if (r.redrawCount === undefined) {
  26416. r.redrawCount = 0;
  26417. }
  26418. r.redrawCount++;
  26419. if (r.redrawTotalTime === undefined) {
  26420. r.redrawTotalTime = 0;
  26421. }
  26422. var duration = endTime - startTime;
  26423. r.redrawTotalTime += duration;
  26424. r.lastRedrawTime = duration;
  26425. // use a weighted average with a bias from the previous average so we don't spike so easily
  26426. r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;
  26427. r.requestedFrame = false;
  26428. } else {
  26429. beforeRenderCallbacks(r, false, requestTime);
  26430. }
  26431. r.skipFrame = false;
  26432. requestAnimationFrame(_renderFn);
  26433. };
  26434. requestAnimationFrame(_renderFn);
  26435. };
  26436. var BaseRenderer = function BaseRenderer(options) {
  26437. this.init(options);
  26438. };
  26439. var BR = BaseRenderer;
  26440. var BRp = BR.prototype;
  26441. BRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];
  26442. BRp.init = function (options) {
  26443. var r = this;
  26444. r.options = options;
  26445. r.cy = options.cy;
  26446. var ctr = r.container = options.cy.container();
  26447. var containerWindow = r.cy.window();
  26448. // prepend a stylesheet in the head such that
  26449. if (containerWindow) {
  26450. var document = containerWindow.document;
  26451. var head = document.head;
  26452. var stylesheetId = '__________cytoscape_stylesheet';
  26453. var className = '__________cytoscape_container';
  26454. var stylesheetAlreadyExists = document.getElementById(stylesheetId) != null;
  26455. if (ctr.className.indexOf(className) < 0) {
  26456. ctr.className = (ctr.className || '') + ' ' + className;
  26457. }
  26458. if (!stylesheetAlreadyExists) {
  26459. var stylesheet = document.createElement('style');
  26460. stylesheet.id = stylesheetId;
  26461. stylesheet.textContent = '.' + className + ' { position: relative; }';
  26462. head.insertBefore(stylesheet, head.children[0]); // first so lowest priority
  26463. }
  26464. var computedStyle = containerWindow.getComputedStyle(ctr);
  26465. var position = computedStyle.getPropertyValue('position');
  26466. if (position === 'static') {
  26467. warn('A Cytoscape container has style position:static and so can not use UI extensions properly');
  26468. }
  26469. }
  26470. r.selection = [undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag
  26471. r.bezierProjPcts = [0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95];
  26472. //--Pointer-related data
  26473. r.hoverData = {
  26474. down: null,
  26475. last: null,
  26476. downTime: null,
  26477. triggerMode: null,
  26478. dragging: false,
  26479. initialPan: [null, null],
  26480. capture: false
  26481. };
  26482. r.dragData = {
  26483. possibleDragElements: []
  26484. };
  26485. r.touchData = {
  26486. start: null,
  26487. capture: false,
  26488. // These 3 fields related to tap, taphold events
  26489. startPosition: [null, null, null, null, null, null],
  26490. singleTouchStartTime: null,
  26491. singleTouchMoved: true,
  26492. now: [null, null, null, null, null, null],
  26493. earlier: [null, null, null, null, null, null]
  26494. };
  26495. r.redraws = 0;
  26496. r.showFps = options.showFps;
  26497. r.debug = options.debug;
  26498. r.webgl = options.webgl;
  26499. r.hideEdgesOnViewport = options.hideEdgesOnViewport;
  26500. r.textureOnViewport = options.textureOnViewport;
  26501. r.wheelSensitivity = options.wheelSensitivity;
  26502. r.motionBlurEnabled = options.motionBlur; // on by default
  26503. r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;
  26504. r.motionBlur = options.motionBlur; // for initial kick off
  26505. r.motionBlurOpacity = options.motionBlurOpacity;
  26506. r.motionBlurTransparency = 1 - r.motionBlurOpacity;
  26507. r.motionBlurPxRatio = 1;
  26508. r.mbPxRBlurry = 1; //0.8;
  26509. r.minMbLowQualFrames = 4;
  26510. r.fullQualityMb = false;
  26511. r.clearedForMotionBlur = [];
  26512. r.desktopTapThreshold = options.desktopTapThreshold;
  26513. r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;
  26514. r.touchTapThreshold = options.touchTapThreshold;
  26515. r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;
  26516. r.tapholdDuration = 500;
  26517. r.bindings = [];
  26518. r.beforeRenderCallbacks = [];
  26519. r.beforeRenderPriorities = {
  26520. // higher priority execs before lower one
  26521. animations: 400,
  26522. eleCalcs: 300,
  26523. eleTxrDeq: 200,
  26524. lyrTxrDeq: 150,
  26525. lyrTxrSkip: 100
  26526. };
  26527. r.registerNodeShapes();
  26528. r.registerArrowShapes();
  26529. r.registerCalculationListeners();
  26530. };
  26531. BRp.notify = function (eventName, eles) {
  26532. var r = this;
  26533. var cy = r.cy;
  26534. // the renderer can't be notified after it's destroyed
  26535. if (this.destroyed) {
  26536. return;
  26537. }
  26538. if (eventName === 'init') {
  26539. r.load();
  26540. return;
  26541. }
  26542. if (eventName === 'destroy') {
  26543. r.destroy();
  26544. return;
  26545. }
  26546. if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {
  26547. r.invalidateCachedZSortedEles();
  26548. }
  26549. if (eventName === 'viewport') {
  26550. r.redrawHint('select', true);
  26551. }
  26552. if (eventName === 'gc') {
  26553. r.redrawHint('gc', true);
  26554. }
  26555. if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {
  26556. r.invalidateContainerClientCoordsCache();
  26557. r.matchCanvasSize(r.container);
  26558. }
  26559. r.redrawHint('eles', true);
  26560. r.redrawHint('drag', true);
  26561. this.startRenderLoop();
  26562. this.redraw();
  26563. };
  26564. BRp.destroy = function () {
  26565. var r = this;
  26566. r.destroyed = true;
  26567. r.cy.stopAnimationLoop();
  26568. for (var i = 0; i < r.bindings.length; i++) {
  26569. var binding = r.bindings[i];
  26570. var b = binding;
  26571. var tgt = b.target;
  26572. (tgt.off || tgt.removeEventListener).apply(tgt, b.args);
  26573. }
  26574. r.bindings = [];
  26575. r.beforeRenderCallbacks = [];
  26576. r.onUpdateEleCalcsFns = [];
  26577. if (r.removeObserver) {
  26578. r.removeObserver.disconnect();
  26579. }
  26580. if (r.styleObserver) {
  26581. r.styleObserver.disconnect();
  26582. }
  26583. if (r.resizeObserver) {
  26584. r.resizeObserver.disconnect();
  26585. }
  26586. if (r.labelCalcDiv) {
  26587. try {
  26588. document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef
  26589. } catch (e) {
  26590. // ie10 issue #1014
  26591. }
  26592. }
  26593. };
  26594. BRp.isHeadless = function () {
  26595. return false;
  26596. };
  26597. [BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {
  26598. extend(BRp, props);
  26599. });
  26600. var fullFpsTime = 1000 / 60; // assume 60 frames per second
  26601. var defs = {
  26602. setupDequeueing: function setupDequeueing(opts) {
  26603. return function setupDequeueingImpl() {
  26604. var self = this;
  26605. var r = this.renderer;
  26606. if (self.dequeueingSetup) {
  26607. return;
  26608. } else {
  26609. self.dequeueingSetup = true;
  26610. }
  26611. var queueRedraw = debounce(function () {
  26612. r.redrawHint('eles', true);
  26613. r.redrawHint('drag', true);
  26614. r.redraw();
  26615. }, opts.deqRedrawThreshold);
  26616. var dequeue = function dequeue(willDraw, frameStartTime) {
  26617. var startTime = performanceNow();
  26618. var avgRenderTime = r.averageRedrawTime;
  26619. var renderTime = r.lastRedrawTime;
  26620. var deqd = [];
  26621. var extent = r.cy.extent();
  26622. var pixelRatio = r.getPixelRatio();
  26623. // if we aren't in a tick that causes a draw, then the rendered style
  26624. // queue won't automatically be flushed before dequeueing starts
  26625. if (!willDraw) {
  26626. r.flushRenderedStyleQueue();
  26627. }
  26628. while (true) {
  26629. // eslint-disable-line no-constant-condition
  26630. var now = performanceNow();
  26631. var duration = now - startTime;
  26632. var frameDuration = now - frameStartTime;
  26633. if (renderTime < fullFpsTime) {
  26634. // if we're rendering faster than the ideal fps, then do dequeueing
  26635. // during all of the remaining frame time
  26636. var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);
  26637. if (frameDuration >= opts.deqFastCost * timeAvailable) {
  26638. break;
  26639. }
  26640. } else {
  26641. if (willDraw) {
  26642. if (duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime) {
  26643. break;
  26644. }
  26645. } else if (frameDuration >= opts.deqNoDrawCost * fullFpsTime) {
  26646. break;
  26647. }
  26648. }
  26649. var thisDeqd = opts.deq(self, pixelRatio, extent);
  26650. if (thisDeqd.length > 0) {
  26651. for (var i = 0; i < thisDeqd.length; i++) {
  26652. deqd.push(thisDeqd[i]);
  26653. }
  26654. } else {
  26655. break;
  26656. }
  26657. }
  26658. // callbacks on dequeue
  26659. if (deqd.length > 0) {
  26660. opts.onDeqd(self, deqd);
  26661. if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {
  26662. queueRedraw();
  26663. }
  26664. }
  26665. };
  26666. var priority = opts.priority || noop$1;
  26667. r.beforeRender(dequeue, priority(self));
  26668. };
  26669. }
  26670. };
  26671. // Allows lookups for (ele, lvl) => cache.
  26672. // Uses keys so elements may share the same cache.
  26673. var ElementTextureCacheLookup = /*#__PURE__*/function () {
  26674. function ElementTextureCacheLookup(getKey) {
  26675. var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;
  26676. _classCallCheck(this, ElementTextureCacheLookup);
  26677. this.idsByKey = new Map$1();
  26678. this.keyForId = new Map$1();
  26679. this.cachesByLvl = new Map$1();
  26680. this.lvls = [];
  26681. this.getKey = getKey;
  26682. this.doesEleInvalidateKey = doesEleInvalidateKey;
  26683. }
  26684. return _createClass(ElementTextureCacheLookup, [{
  26685. key: "getIdsFor",
  26686. value: function getIdsFor(key) {
  26687. if (key == null) {
  26688. error("Can not get id list for null key");
  26689. }
  26690. var idsByKey = this.idsByKey;
  26691. var ids = this.idsByKey.get(key);
  26692. if (!ids) {
  26693. ids = new Set$1();
  26694. idsByKey.set(key, ids);
  26695. }
  26696. return ids;
  26697. }
  26698. }, {
  26699. key: "addIdForKey",
  26700. value: function addIdForKey(key, id) {
  26701. if (key != null) {
  26702. this.getIdsFor(key).add(id);
  26703. }
  26704. }
  26705. }, {
  26706. key: "deleteIdForKey",
  26707. value: function deleteIdForKey(key, id) {
  26708. if (key != null) {
  26709. this.getIdsFor(key)["delete"](id);
  26710. }
  26711. }
  26712. }, {
  26713. key: "getNumberOfIdsForKey",
  26714. value: function getNumberOfIdsForKey(key) {
  26715. if (key == null) {
  26716. return 0;
  26717. } else {
  26718. return this.getIdsFor(key).size;
  26719. }
  26720. }
  26721. }, {
  26722. key: "updateKeyMappingFor",
  26723. value: function updateKeyMappingFor(ele) {
  26724. var id = ele.id();
  26725. var prevKey = this.keyForId.get(id);
  26726. var currKey = this.getKey(ele);
  26727. this.deleteIdForKey(prevKey, id);
  26728. this.addIdForKey(currKey, id);
  26729. this.keyForId.set(id, currKey);
  26730. }
  26731. }, {
  26732. key: "deleteKeyMappingFor",
  26733. value: function deleteKeyMappingFor(ele) {
  26734. var id = ele.id();
  26735. var prevKey = this.keyForId.get(id);
  26736. this.deleteIdForKey(prevKey, id);
  26737. this.keyForId["delete"](id);
  26738. }
  26739. }, {
  26740. key: "keyHasChangedFor",
  26741. value: function keyHasChangedFor(ele) {
  26742. var id = ele.id();
  26743. var prevKey = this.keyForId.get(id);
  26744. var newKey = this.getKey(ele);
  26745. return prevKey !== newKey;
  26746. }
  26747. }, {
  26748. key: "isInvalid",
  26749. value: function isInvalid(ele) {
  26750. return this.keyHasChangedFor(ele) || this.doesEleInvalidateKey(ele);
  26751. }
  26752. }, {
  26753. key: "getCachesAt",
  26754. value: function getCachesAt(lvl) {
  26755. var cachesByLvl = this.cachesByLvl,
  26756. lvls = this.lvls;
  26757. var caches = cachesByLvl.get(lvl);
  26758. if (!caches) {
  26759. caches = new Map$1();
  26760. cachesByLvl.set(lvl, caches);
  26761. lvls.push(lvl);
  26762. }
  26763. return caches;
  26764. }
  26765. }, {
  26766. key: "getCache",
  26767. value: function getCache(key, lvl) {
  26768. return this.getCachesAt(lvl).get(key);
  26769. }
  26770. }, {
  26771. key: "get",
  26772. value: function get(ele, lvl) {
  26773. var key = this.getKey(ele);
  26774. var cache = this.getCache(key, lvl);
  26775. // getting for an element may need to add to the id list b/c eles can share keys
  26776. if (cache != null) {
  26777. this.updateKeyMappingFor(ele);
  26778. }
  26779. return cache;
  26780. }
  26781. }, {
  26782. key: "getForCachedKey",
  26783. value: function getForCachedKey(ele, lvl) {
  26784. var key = this.keyForId.get(ele.id()); // n.b. use cached key, not newly computed key
  26785. var cache = this.getCache(key, lvl);
  26786. return cache;
  26787. }
  26788. }, {
  26789. key: "hasCache",
  26790. value: function hasCache(key, lvl) {
  26791. return this.getCachesAt(lvl).has(key);
  26792. }
  26793. }, {
  26794. key: "has",
  26795. value: function has(ele, lvl) {
  26796. var key = this.getKey(ele);
  26797. return this.hasCache(key, lvl);
  26798. }
  26799. }, {
  26800. key: "setCache",
  26801. value: function setCache(key, lvl, cache) {
  26802. cache.key = key;
  26803. this.getCachesAt(lvl).set(key, cache);
  26804. }
  26805. }, {
  26806. key: "set",
  26807. value: function set(ele, lvl, cache) {
  26808. var key = this.getKey(ele);
  26809. this.setCache(key, lvl, cache);
  26810. this.updateKeyMappingFor(ele);
  26811. }
  26812. }, {
  26813. key: "deleteCache",
  26814. value: function deleteCache(key, lvl) {
  26815. this.getCachesAt(lvl)["delete"](key);
  26816. }
  26817. }, {
  26818. key: "delete",
  26819. value: function _delete(ele, lvl) {
  26820. var key = this.getKey(ele);
  26821. this.deleteCache(key, lvl);
  26822. }
  26823. }, {
  26824. key: "invalidateKey",
  26825. value: function invalidateKey(key) {
  26826. var _this = this;
  26827. this.lvls.forEach(function (lvl) {
  26828. return _this.deleteCache(key, lvl);
  26829. });
  26830. }
  26831. // returns true if no other eles reference the invalidated cache (n.b. other eles may need the cache with the same key)
  26832. }, {
  26833. key: "invalidate",
  26834. value: function invalidate(ele) {
  26835. var id = ele.id();
  26836. var key = this.keyForId.get(id); // n.b. use stored key rather than current (potential key)
  26837. this.deleteKeyMappingFor(ele);
  26838. var entireKeyInvalidated = this.doesEleInvalidateKey(ele);
  26839. if (entireKeyInvalidated) {
  26840. // clear mapping for current key
  26841. this.invalidateKey(key);
  26842. }
  26843. return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;
  26844. }
  26845. }]);
  26846. }();
  26847. var minTxrH = 25; // the size of the texture cache for small height eles (special case)
  26848. var txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up
  26849. var minLvl$1 = -4; // when scaling smaller than that we don't need to re-render
  26850. var maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)
  26851. var maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used
  26852. var eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps
  26853. var defTxrWidth = 1024; // default/minimum texture width
  26854. var maxTxrW = 1024; // the maximum width of a texture
  26855. var maxTxrH = 1024; // the maximum height of a texture
  26856. var minUtility = 0.2; // if usage of texture is less than this, it is retired
  26857. var maxFullness = 0.8; // fullness of texture after which queue removal is checked
  26858. var maxFullnessChecks = 10; // dequeued after this many checks
  26859. var deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
  26860. var deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time
  26861. var deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
  26862. var deqFastCost$1 = 0.9; // % of frame time to be used when >60fps
  26863. var deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
  26864. var maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch
  26865. var getTxrReasons = {
  26866. dequeue: 'dequeue',
  26867. downscale: 'downscale',
  26868. highQuality: 'highQuality'
  26869. };
  26870. var initDefaults = defaults$g({
  26871. getKey: null,
  26872. doesEleInvalidateKey: falsify,
  26873. drawElement: null,
  26874. getBoundingBox: null,
  26875. getRotationPoint: null,
  26876. getRotationOffset: null,
  26877. isVisible: trueify,
  26878. allowEdgeTxrCaching: true,
  26879. allowParentTxrCaching: true
  26880. });
  26881. var ElementTextureCache = function ElementTextureCache(renderer, initOptions) {
  26882. var self = this;
  26883. self.renderer = renderer;
  26884. self.onDequeues = [];
  26885. var opts = initDefaults(initOptions);
  26886. extend(self, opts);
  26887. self.lookup = new ElementTextureCacheLookup(opts.getKey, opts.doesEleInvalidateKey);
  26888. self.setupDequeueing();
  26889. };
  26890. var ETCp = ElementTextureCache.prototype;
  26891. ETCp.reasons = getTxrReasons;
  26892. // the list of textures in which new subtextures for elements can be placed
  26893. ETCp.getTextureQueue = function (txrH) {
  26894. var self = this;
  26895. self.eleImgCaches = self.eleImgCaches || {};
  26896. return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];
  26897. };
  26898. // the list of usused textures which can be recycled (in use in texture queue)
  26899. ETCp.getRetiredTextureQueue = function (txrH) {
  26900. var self = this;
  26901. var rtxtrQs = self.eleImgCaches.retired = self.eleImgCaches.retired || {};
  26902. var rtxtrQ = rtxtrQs[txrH] = rtxtrQs[txrH] || [];
  26903. return rtxtrQ;
  26904. };
  26905. // queue of element draw requests at different scale levels
  26906. ETCp.getElementQueue = function () {
  26907. var self = this;
  26908. var q = self.eleCacheQueue = self.eleCacheQueue || new Heap(function (a, b) {
  26909. return b.reqs - a.reqs;
  26910. });
  26911. return q;
  26912. };
  26913. // queue of element draw requests at different scale levels (element id lookup)
  26914. ETCp.getElementKeyToQueue = function () {
  26915. var self = this;
  26916. var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};
  26917. return k2q;
  26918. };
  26919. ETCp.getElement = function (ele, bb, pxRatio, lvl, reason) {
  26920. var self = this;
  26921. var r = this.renderer;
  26922. var zoom = r.cy.zoom();
  26923. var lookup = this.lookup;
  26924. if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {
  26925. return null;
  26926. }
  26927. if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {
  26928. return null;
  26929. }
  26930. if (lvl == null) {
  26931. lvl = Math.ceil(log2(zoom * pxRatio));
  26932. }
  26933. if (lvl < minLvl$1) {
  26934. lvl = minLvl$1;
  26935. } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {
  26936. return null;
  26937. }
  26938. var scale = Math.pow(2, lvl);
  26939. var eleScaledH = bb.h * scale;
  26940. var eleScaledW = bb.w * scale;
  26941. var scaledLabelShown = r.eleTextBiggerThanMin(ele, scale);
  26942. if (!this.isVisible(ele, scaledLabelShown)) {
  26943. return null;
  26944. }
  26945. var eleCache = lookup.get(ele, lvl);
  26946. // if this get was on an unused/invalidated cache, then restore the texture usage metric
  26947. if (eleCache && eleCache.invalidated) {
  26948. eleCache.invalidated = false;
  26949. eleCache.texture.invalidatedWidth -= eleCache.width;
  26950. }
  26951. if (eleCache) {
  26952. return eleCache;
  26953. }
  26954. var txrH; // which texture height this ele belongs to
  26955. if (eleScaledH <= minTxrH) {
  26956. txrH = minTxrH;
  26957. } else if (eleScaledH <= txrStepH) {
  26958. txrH = txrStepH;
  26959. } else {
  26960. txrH = Math.ceil(eleScaledH / txrStepH) * txrStepH;
  26961. }
  26962. if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {
  26963. return null; // caching large elements is not efficient
  26964. }
  26965. var txrQ = self.getTextureQueue(txrH);
  26966. // first try the second last one in case it has space at the end
  26967. var txr = txrQ[txrQ.length - 2];
  26968. var addNewTxr = function addNewTxr() {
  26969. return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);
  26970. };
  26971. // try the last one if there is no second last one
  26972. if (!txr) {
  26973. txr = txrQ[txrQ.length - 1];
  26974. }
  26975. // if the last one doesn't exist, we need a first one
  26976. if (!txr) {
  26977. txr = addNewTxr();
  26978. }
  26979. // if there's no room in the current texture, we need a new one
  26980. if (txr.width - txr.usedWidth < eleScaledW) {
  26981. txr = addNewTxr();
  26982. }
  26983. var scalableFrom = function scalableFrom(otherCache) {
  26984. return otherCache && otherCache.scaledLabelShown === scaledLabelShown;
  26985. };
  26986. var deqing = reason && reason === getTxrReasons.dequeue;
  26987. var highQualityReq = reason && reason === getTxrReasons.highQuality;
  26988. var downscaleReq = reason && reason === getTxrReasons.downscale;
  26989. var higherCache; // the nearest cache with a higher level
  26990. for (var l = lvl + 1; l <= maxLvl$1; l++) {
  26991. var c = lookup.get(ele, l);
  26992. if (c) {
  26993. higherCache = c;
  26994. break;
  26995. }
  26996. }
  26997. var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;
  26998. var downscale = function downscale() {
  26999. txr.context.drawImage(oneUpCache.texture.canvas, oneUpCache.x, 0, oneUpCache.width, oneUpCache.height, txr.usedWidth, 0, eleScaledW, eleScaledH);
  27000. };
  27001. // reset ele area in texture
  27002. txr.context.setTransform(1, 0, 0, 1, 0, 0);
  27003. txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);
  27004. if (scalableFrom(oneUpCache)) {
  27005. // then we can relatively cheaply rescale the existing image w/o rerendering
  27006. downscale();
  27007. } else if (scalableFrom(higherCache)) {
  27008. // then use the higher cache for now and queue the next level down
  27009. // to cheaply scale towards the smaller level
  27010. if (highQualityReq) {
  27011. for (var _l = higherCache.level; _l > lvl; _l--) {
  27012. oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);
  27013. }
  27014. downscale();
  27015. } else {
  27016. self.queueElement(ele, higherCache.level - 1);
  27017. return higherCache;
  27018. }
  27019. } else {
  27020. var lowerCache; // the nearest cache with a lower level
  27021. if (!deqing && !highQualityReq && !downscaleReq) {
  27022. for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {
  27023. var _c = lookup.get(ele, _l2);
  27024. if (_c) {
  27025. lowerCache = _c;
  27026. break;
  27027. }
  27028. }
  27029. }
  27030. if (scalableFrom(lowerCache)) {
  27031. // then use the lower quality cache for now and queue the better one for later
  27032. self.queueElement(ele, lvl);
  27033. return lowerCache;
  27034. }
  27035. txr.context.translate(txr.usedWidth, 0);
  27036. txr.context.scale(scale, scale);
  27037. this.drawElement(txr.context, ele, bb, scaledLabelShown, false);
  27038. txr.context.scale(1 / scale, 1 / scale);
  27039. txr.context.translate(-txr.usedWidth, 0);
  27040. }
  27041. eleCache = {
  27042. x: txr.usedWidth,
  27043. texture: txr,
  27044. level: lvl,
  27045. scale: scale,
  27046. width: eleScaledW,
  27047. height: eleScaledH,
  27048. scaledLabelShown: scaledLabelShown
  27049. };
  27050. txr.usedWidth += Math.ceil(eleScaledW + eleTxrSpacing);
  27051. txr.eleCaches.push(eleCache);
  27052. lookup.set(ele, lvl, eleCache);
  27053. self.checkTextureFullness(txr);
  27054. return eleCache;
  27055. };
  27056. ETCp.invalidateElements = function (eles) {
  27057. for (var i = 0; i < eles.length; i++) {
  27058. this.invalidateElement(eles[i]);
  27059. }
  27060. };
  27061. ETCp.invalidateElement = function (ele) {
  27062. var self = this;
  27063. var lookup = self.lookup;
  27064. var caches = [];
  27065. var invalid = lookup.isInvalid(ele);
  27066. if (!invalid) {
  27067. return; // override the invalidation request if the element key has not changed
  27068. }
  27069. for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {
  27070. var cache = lookup.getForCachedKey(ele, lvl);
  27071. if (cache) {
  27072. caches.push(cache);
  27073. }
  27074. }
  27075. var noOtherElesUseCache = lookup.invalidate(ele);
  27076. if (noOtherElesUseCache) {
  27077. for (var i = 0; i < caches.length; i++) {
  27078. var _cache = caches[i];
  27079. var txr = _cache.texture;
  27080. // remove space from the texture it belongs to
  27081. txr.invalidatedWidth += _cache.width;
  27082. // mark the cache as invalidated
  27083. _cache.invalidated = true;
  27084. // retire the texture if its utility is low
  27085. self.checkTextureUtility(txr);
  27086. }
  27087. }
  27088. // remove from queue since the old req was for the old state
  27089. self.removeFromQueue(ele);
  27090. };
  27091. ETCp.checkTextureUtility = function (txr) {
  27092. // invalidate all entries in the cache if the cache size is small
  27093. if (txr.invalidatedWidth >= minUtility * txr.width) {
  27094. this.retireTexture(txr);
  27095. }
  27096. };
  27097. ETCp.checkTextureFullness = function (txr) {
  27098. // if texture has been mostly filled and passed over several times, remove
  27099. // it from the queue so we don't need to waste time looking at it to put new things
  27100. var self = this;
  27101. var txrQ = self.getTextureQueue(txr.height);
  27102. if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {
  27103. removeFromArray(txrQ, txr);
  27104. } else {
  27105. txr.fullnessChecks++;
  27106. }
  27107. };
  27108. ETCp.retireTexture = function (txr) {
  27109. var self = this;
  27110. var txrH = txr.height;
  27111. var txrQ = self.getTextureQueue(txrH);
  27112. var lookup = this.lookup;
  27113. // retire the texture from the active / searchable queue:
  27114. removeFromArray(txrQ, txr);
  27115. txr.retired = true;
  27116. // remove the refs from the eles to the caches:
  27117. var eleCaches = txr.eleCaches;
  27118. for (var i = 0; i < eleCaches.length; i++) {
  27119. var eleCache = eleCaches[i];
  27120. lookup.deleteCache(eleCache.key, eleCache.level);
  27121. }
  27122. clearArray(eleCaches);
  27123. // add the texture to a retired queue so it can be recycled in future:
  27124. var rtxtrQ = self.getRetiredTextureQueue(txrH);
  27125. rtxtrQ.push(txr);
  27126. };
  27127. ETCp.addTexture = function (txrH, minW) {
  27128. var self = this;
  27129. var txrQ = self.getTextureQueue(txrH);
  27130. var txr = {};
  27131. txrQ.push(txr);
  27132. txr.eleCaches = [];
  27133. txr.height = txrH;
  27134. txr.width = Math.max(defTxrWidth, minW);
  27135. txr.usedWidth = 0;
  27136. txr.invalidatedWidth = 0;
  27137. txr.fullnessChecks = 0;
  27138. txr.canvas = self.renderer.makeOffscreenCanvas(txr.width, txr.height);
  27139. txr.context = txr.canvas.getContext('2d');
  27140. return txr;
  27141. };
  27142. ETCp.recycleTexture = function (txrH, minW) {
  27143. var self = this;
  27144. var txrQ = self.getTextureQueue(txrH);
  27145. var rtxtrQ = self.getRetiredTextureQueue(txrH);
  27146. for (var i = 0; i < rtxtrQ.length; i++) {
  27147. var txr = rtxtrQ[i];
  27148. if (txr.width >= minW) {
  27149. txr.retired = false;
  27150. txr.usedWidth = 0;
  27151. txr.invalidatedWidth = 0;
  27152. txr.fullnessChecks = 0;
  27153. clearArray(txr.eleCaches);
  27154. txr.context.setTransform(1, 0, 0, 1, 0, 0);
  27155. txr.context.clearRect(0, 0, txr.width, txr.height);
  27156. removeFromArray(rtxtrQ, txr);
  27157. txrQ.push(txr);
  27158. return txr;
  27159. }
  27160. }
  27161. };
  27162. ETCp.queueElement = function (ele, lvl) {
  27163. var self = this;
  27164. var q = self.getElementQueue();
  27165. var k2q = self.getElementKeyToQueue();
  27166. var key = this.getKey(ele);
  27167. var existingReq = k2q[key];
  27168. if (existingReq) {
  27169. // use the max lvl b/c in between lvls are cheap to make
  27170. existingReq.level = Math.max(existingReq.level, lvl);
  27171. existingReq.eles.merge(ele);
  27172. existingReq.reqs++;
  27173. q.updateItem(existingReq);
  27174. } else {
  27175. var req = {
  27176. eles: ele.spawn().merge(ele),
  27177. level: lvl,
  27178. reqs: 1,
  27179. key: key
  27180. };
  27181. q.push(req);
  27182. k2q[key] = req;
  27183. }
  27184. };
  27185. ETCp.dequeue = function (pxRatio /*, extent*/) {
  27186. var self = this;
  27187. var q = self.getElementQueue();
  27188. var k2q = self.getElementKeyToQueue();
  27189. var dequeued = [];
  27190. var lookup = self.lookup;
  27191. for (var i = 0; i < maxDeqSize$1; i++) {
  27192. if (q.size() > 0) {
  27193. var req = q.pop();
  27194. var key = req.key;
  27195. var ele = req.eles[0]; // all eles have the same key
  27196. var cacheExists = lookup.hasCache(ele, req.level);
  27197. // clear out the key to req lookup
  27198. k2q[key] = null;
  27199. // dequeueing isn't necessary with an existing cache
  27200. if (cacheExists) {
  27201. continue;
  27202. }
  27203. dequeued.push(req);
  27204. var bb = self.getBoundingBox(ele);
  27205. self.getElement(ele, bb, pxRatio, req.level, getTxrReasons.dequeue);
  27206. } else {
  27207. break;
  27208. }
  27209. }
  27210. return dequeued;
  27211. };
  27212. ETCp.removeFromQueue = function (ele) {
  27213. var self = this;
  27214. var q = self.getElementQueue();
  27215. var k2q = self.getElementKeyToQueue();
  27216. var key = this.getKey(ele);
  27217. var req = k2q[key];
  27218. if (req != null) {
  27219. if (req.eles.length === 1) {
  27220. // remove if last ele in the req
  27221. // bring to front of queue
  27222. req.reqs = MAX_INT$1;
  27223. q.updateItem(req);
  27224. q.pop(); // remove from queue
  27225. k2q[key] = null; // remove from lookup map
  27226. } else {
  27227. // otherwise just remove ele from req
  27228. req.eles.unmerge(ele);
  27229. }
  27230. }
  27231. };
  27232. ETCp.onDequeue = function (fn) {
  27233. this.onDequeues.push(fn);
  27234. };
  27235. ETCp.offDequeue = function (fn) {
  27236. removeFromArray(this.onDequeues, fn);
  27237. };
  27238. ETCp.setupDequeueing = defs.setupDequeueing({
  27239. deqRedrawThreshold: deqRedrawThreshold$1,
  27240. deqCost: deqCost$1,
  27241. deqAvgCost: deqAvgCost$1,
  27242. deqNoDrawCost: deqNoDrawCost$1,
  27243. deqFastCost: deqFastCost$1,
  27244. deq: function deq(self, pxRatio, extent) {
  27245. return self.dequeue(pxRatio, extent);
  27246. },
  27247. onDeqd: function onDeqd(self, deqd) {
  27248. for (var i = 0; i < self.onDequeues.length; i++) {
  27249. var fn = self.onDequeues[i];
  27250. fn(deqd);
  27251. }
  27252. },
  27253. shouldRedraw: function shouldRedraw(self, deqd, pxRatio, extent) {
  27254. for (var i = 0; i < deqd.length; i++) {
  27255. var eles = deqd[i].eles;
  27256. for (var j = 0; j < eles.length; j++) {
  27257. var bb = eles[j].boundingBox();
  27258. if (boundingBoxesIntersect(bb, extent)) {
  27259. return true;
  27260. }
  27261. }
  27262. }
  27263. return false;
  27264. },
  27265. priority: function priority(self) {
  27266. return self.renderer.beforeRenderPriorities.eleTxrDeq;
  27267. }
  27268. });
  27269. var defNumLayers = 1; // default number of layers to use
  27270. var minLvl = -4; // when scaling smaller than that we don't need to re-render
  27271. var maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)
  27272. var maxZoom = 3.99; // beyond this zoom level, layered textures are not used
  27273. var deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
  27274. var refineEleDebounceTime = 50; // time to debounce sharper ele texture updates
  27275. var deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
  27276. var deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time
  27277. var deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
  27278. var deqFastCost = 0.9; // % of frame time to be used when >60fps
  27279. var maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch
  27280. var invalidThreshold = 250; // time threshold for disabling b/c of invalidations
  27281. var maxLayerArea = 4000 * 4000; // layers can't be bigger than this
  27282. var maxLayerDim = 32767; // maximum size for the width/height of layer canvases
  27283. var useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)
  27284. // var log = function(){ console.log.apply( console, arguments ); };
  27285. var LayeredTextureCache = function LayeredTextureCache(renderer) {
  27286. var self = this;
  27287. var r = self.renderer = renderer;
  27288. var cy = r.cy;
  27289. self.layersByLevel = {}; // e.g. 2 => [ layer1, layer2, ..., layerN ]
  27290. self.firstGet = true;
  27291. self.lastInvalidationTime = performanceNow() - 2 * invalidThreshold;
  27292. self.skipping = false;
  27293. self.eleTxrDeqs = cy.collection();
  27294. self.scheduleElementRefinement = debounce(function () {
  27295. self.refineElementTextures(self.eleTxrDeqs);
  27296. self.eleTxrDeqs.unmerge(self.eleTxrDeqs);
  27297. }, refineEleDebounceTime);
  27298. r.beforeRender(function (willDraw, now) {
  27299. if (now - self.lastInvalidationTime <= invalidThreshold) {
  27300. self.skipping = true;
  27301. } else {
  27302. self.skipping = false;
  27303. }
  27304. }, r.beforeRenderPriorities.lyrTxrSkip);
  27305. var qSort = function qSort(a, b) {
  27306. return b.reqs - a.reqs;
  27307. };
  27308. self.layersQueue = new Heap(qSort);
  27309. self.setupDequeueing();
  27310. };
  27311. var LTCp = LayeredTextureCache.prototype;
  27312. var layerIdPool = 0;
  27313. var MAX_INT = Math.pow(2, 53) - 1;
  27314. LTCp.makeLayer = function (bb, lvl) {
  27315. var scale = Math.pow(2, lvl);
  27316. var w = Math.ceil(bb.w * scale);
  27317. var h = Math.ceil(bb.h * scale);
  27318. var canvas = this.renderer.makeOffscreenCanvas(w, h);
  27319. var layer = {
  27320. id: layerIdPool = ++layerIdPool % MAX_INT,
  27321. bb: bb,
  27322. level: lvl,
  27323. width: w,
  27324. height: h,
  27325. canvas: canvas,
  27326. context: canvas.getContext('2d'),
  27327. eles: [],
  27328. elesQueue: [],
  27329. reqs: 0
  27330. };
  27331. // log('make layer %s with w %s and h %s and lvl %s', layer.id, layer.width, layer.height, layer.level);
  27332. var cxt = layer.context;
  27333. var dx = -layer.bb.x1;
  27334. var dy = -layer.bb.y1;
  27335. // do the transform on creation to save cycles (it's the same for all eles)
  27336. cxt.scale(scale, scale);
  27337. cxt.translate(dx, dy);
  27338. return layer;
  27339. };
  27340. LTCp.getLayers = function (eles, pxRatio, lvl) {
  27341. var self = this;
  27342. var r = self.renderer;
  27343. var cy = r.cy;
  27344. var zoom = cy.zoom();
  27345. var firstGet = self.firstGet;
  27346. self.firstGet = false;
  27347. // log('--\nget layers with %s eles', eles.length);
  27348. //log eles.map(function(ele){ return ele.id() }) );
  27349. if (lvl == null) {
  27350. lvl = Math.ceil(log2(zoom * pxRatio));
  27351. if (lvl < minLvl) {
  27352. lvl = minLvl;
  27353. } else if (zoom >= maxZoom || lvl > maxLvl) {
  27354. return null;
  27355. }
  27356. }
  27357. self.validateLayersElesOrdering(lvl, eles);
  27358. var layersByLvl = self.layersByLevel;
  27359. var scale = Math.pow(2, lvl);
  27360. var layers = layersByLvl[lvl] = layersByLvl[lvl] || [];
  27361. var bb;
  27362. var lvlComplete = self.levelIsComplete(lvl, eles);
  27363. var tmpLayers;
  27364. var checkTempLevels = function checkTempLevels() {
  27365. var canUseAsTmpLvl = function canUseAsTmpLvl(l) {
  27366. self.validateLayersElesOrdering(l, eles);
  27367. if (self.levelIsComplete(l, eles)) {
  27368. tmpLayers = layersByLvl[l];
  27369. return true;
  27370. }
  27371. };
  27372. var checkLvls = function checkLvls(dir) {
  27373. if (tmpLayers) {
  27374. return;
  27375. }
  27376. for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {
  27377. if (canUseAsTmpLvl(l)) {
  27378. break;
  27379. }
  27380. }
  27381. };
  27382. checkLvls(1);
  27383. checkLvls(-1);
  27384. // remove the invalid layers; they will be replaced as needed later in this function
  27385. for (var i = layers.length - 1; i >= 0; i--) {
  27386. var layer = layers[i];
  27387. if (layer.invalid) {
  27388. removeFromArray(layers, layer);
  27389. }
  27390. }
  27391. };
  27392. if (!lvlComplete) {
  27393. // if the current level is incomplete, then use the closest, best quality layerset temporarily
  27394. // and later queue the current layerset so we can get the proper quality level soon
  27395. checkTempLevels();
  27396. } else {
  27397. // log('level complete, using existing layers\n--');
  27398. return layers;
  27399. }
  27400. var getBb = function getBb() {
  27401. if (!bb) {
  27402. bb = makeBoundingBox();
  27403. for (var i = 0; i < eles.length; i++) {
  27404. updateBoundingBox(bb, eles[i].boundingBox());
  27405. }
  27406. }
  27407. return bb;
  27408. };
  27409. var makeLayer = function makeLayer(opts) {
  27410. opts = opts || {};
  27411. var after = opts.after;
  27412. getBb();
  27413. var w = Math.ceil(bb.w * scale);
  27414. var h = Math.ceil(bb.h * scale);
  27415. if (w > maxLayerDim || h > maxLayerDim) {
  27416. return null;
  27417. }
  27418. var area = w * h;
  27419. if (area > maxLayerArea) {
  27420. return null;
  27421. }
  27422. var layer = self.makeLayer(bb, lvl);
  27423. if (after != null) {
  27424. var index = layers.indexOf(after) + 1;
  27425. layers.splice(index, 0, layer);
  27426. } else if (opts.insert === undefined || opts.insert) {
  27427. // no after specified => first layer made so put at start
  27428. layers.unshift(layer);
  27429. }
  27430. // if( tmpLayers ){
  27431. //self.queueLayer( layer );
  27432. // }
  27433. return layer;
  27434. };
  27435. if (self.skipping && !firstGet) {
  27436. // log('skip layers');
  27437. return null;
  27438. }
  27439. // log('do layers');
  27440. var layer = null;
  27441. var maxElesPerLayer = eles.length / defNumLayers;
  27442. var allowLazyQueueing = !firstGet;
  27443. for (var i = 0; i < eles.length; i++) {
  27444. var ele = eles[i];
  27445. var rs = ele._private.rscratch;
  27446. var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
  27447. // log('look at ele', ele.id());
  27448. var existingLayer = caches[lvl];
  27449. if (existingLayer) {
  27450. // reuse layer for later eles
  27451. // log('reuse layer for', ele.id());
  27452. layer = existingLayer;
  27453. continue;
  27454. }
  27455. if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {
  27456. // log('make new layer for ele %s', ele.id());
  27457. layer = makeLayer({
  27458. insert: true,
  27459. after: layer
  27460. });
  27461. // if now layer can be built then we can't use layers at this level
  27462. if (!layer) {
  27463. return null;
  27464. }
  27465. // log('new layer with id %s', layer.id);
  27466. }
  27467. if (tmpLayers || allowLazyQueueing) {
  27468. // log('queue ele %s in layer %s', ele.id(), layer.id);
  27469. self.queueLayer(layer, ele);
  27470. } else {
  27471. // log('draw ele %s in layer %s', ele.id(), layer.id);
  27472. self.drawEleInLayer(layer, ele, lvl, pxRatio);
  27473. }
  27474. layer.eles.push(ele);
  27475. caches[lvl] = layer;
  27476. }
  27477. // log('--');
  27478. if (tmpLayers) {
  27479. // then we only queued the current layerset and can't draw it yet
  27480. return tmpLayers;
  27481. }
  27482. if (allowLazyQueueing) {
  27483. // log('lazy queue level', lvl);
  27484. return null;
  27485. }
  27486. return layers;
  27487. };
  27488. // a layer may want to use an ele cache of a higher level to avoid blurriness
  27489. // so the layer level might not equal the ele level
  27490. LTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {
  27491. return lvl;
  27492. };
  27493. LTCp.drawEleInLayer = function (layer, ele, lvl, pxRatio) {
  27494. var self = this;
  27495. var r = this.renderer;
  27496. var context = layer.context;
  27497. var bb = ele.boundingBox();
  27498. if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
  27499. return;
  27500. }
  27501. lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);
  27502. {
  27503. r.setImgSmoothing(context, false);
  27504. }
  27505. {
  27506. r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);
  27507. }
  27508. {
  27509. r.setImgSmoothing(context, true);
  27510. }
  27511. };
  27512. LTCp.levelIsComplete = function (lvl, eles) {
  27513. var self = this;
  27514. var layers = self.layersByLevel[lvl];
  27515. if (!layers || layers.length === 0) {
  27516. return false;
  27517. }
  27518. var numElesInLayers = 0;
  27519. for (var i = 0; i < layers.length; i++) {
  27520. var layer = layers[i];
  27521. // if there are any eles needed to be drawn yet, the level is not complete
  27522. if (layer.reqs > 0) {
  27523. return false;
  27524. }
  27525. // if the layer is invalid, the level is not complete
  27526. if (layer.invalid) {
  27527. return false;
  27528. }
  27529. numElesInLayers += layer.eles.length;
  27530. }
  27531. // we should have exactly the number of eles passed in to be complete
  27532. if (numElesInLayers !== eles.length) {
  27533. return false;
  27534. }
  27535. return true;
  27536. };
  27537. LTCp.validateLayersElesOrdering = function (lvl, eles) {
  27538. var layers = this.layersByLevel[lvl];
  27539. if (!layers) {
  27540. return;
  27541. }
  27542. // if in a layer the eles are not in the same order, then the layer is invalid
  27543. // (i.e. there is an ele in between the eles in the layer)
  27544. for (var i = 0; i < layers.length; i++) {
  27545. var layer = layers[i];
  27546. var offset = -1;
  27547. // find the offset
  27548. for (var j = 0; j < eles.length; j++) {
  27549. if (layer.eles[0] === eles[j]) {
  27550. offset = j;
  27551. break;
  27552. }
  27553. }
  27554. if (offset < 0) {
  27555. // then the layer has nonexistent elements and is invalid
  27556. this.invalidateLayer(layer);
  27557. continue;
  27558. }
  27559. // the eles in the layer must be in the same continuous order, else the layer is invalid
  27560. var o = offset;
  27561. for (var j = 0; j < layer.eles.length; j++) {
  27562. if (layer.eles[j] !== eles[o + j]) {
  27563. // log('invalidate based on ordering', layer.id);
  27564. this.invalidateLayer(layer);
  27565. break;
  27566. }
  27567. }
  27568. }
  27569. };
  27570. LTCp.updateElementsInLayers = function (eles, update) {
  27571. var self = this;
  27572. var isEles = element(eles[0]);
  27573. // collect udpated elements (cascaded from the layers) and update each
  27574. // layer itself along the way
  27575. for (var i = 0; i < eles.length; i++) {
  27576. var req = isEles ? null : eles[i];
  27577. var ele = isEles ? eles[i] : eles[i].ele;
  27578. var rs = ele._private.rscratch;
  27579. var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
  27580. for (var l = minLvl; l <= maxLvl; l++) {
  27581. var layer = caches[l];
  27582. if (!layer) {
  27583. continue;
  27584. }
  27585. // if update is a request from the ele cache, then it affects only
  27586. // the matching level
  27587. if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {
  27588. continue;
  27589. }
  27590. update(layer, ele, req);
  27591. }
  27592. }
  27593. };
  27594. LTCp.haveLayers = function () {
  27595. var self = this;
  27596. var haveLayers = false;
  27597. for (var l = minLvl; l <= maxLvl; l++) {
  27598. var layers = self.layersByLevel[l];
  27599. if (layers && layers.length > 0) {
  27600. haveLayers = true;
  27601. break;
  27602. }
  27603. }
  27604. return haveLayers;
  27605. };
  27606. LTCp.invalidateElements = function (eles) {
  27607. var self = this;
  27608. if (eles.length === 0) {
  27609. return;
  27610. }
  27611. self.lastInvalidationTime = performanceNow();
  27612. // log('update invalidate layer time from eles');
  27613. if (eles.length === 0 || !self.haveLayers()) {
  27614. return;
  27615. }
  27616. self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {
  27617. self.invalidateLayer(layer);
  27618. });
  27619. };
  27620. LTCp.invalidateLayer = function (layer) {
  27621. // log('update invalidate layer time');
  27622. this.lastInvalidationTime = performanceNow();
  27623. if (layer.invalid) {
  27624. return;
  27625. } // save cycles
  27626. var lvl = layer.level;
  27627. var eles = layer.eles;
  27628. var layers = this.layersByLevel[lvl];
  27629. // log('invalidate layer', layer.id );
  27630. removeFromArray(layers, layer);
  27631. // layer.eles = [];
  27632. layer.elesQueue = [];
  27633. layer.invalid = true;
  27634. if (layer.replacement) {
  27635. layer.replacement.invalid = true;
  27636. }
  27637. for (var i = 0; i < eles.length; i++) {
  27638. var caches = eles[i]._private.rscratch.imgLayerCaches;
  27639. if (caches) {
  27640. caches[lvl] = null;
  27641. }
  27642. }
  27643. };
  27644. LTCp.refineElementTextures = function (eles) {
  27645. var self = this;
  27646. // log('refine', eles.length);
  27647. self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {
  27648. var rLyr = layer.replacement;
  27649. if (!rLyr) {
  27650. rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);
  27651. rLyr.replaces = layer;
  27652. rLyr.eles = layer.eles;
  27653. // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);
  27654. }
  27655. if (!rLyr.reqs) {
  27656. for (var i = 0; i < rLyr.eles.length; i++) {
  27657. self.queueLayer(rLyr, rLyr.eles[i]);
  27658. }
  27659. // log('queue replacement layer refinement', rLyr.id);
  27660. }
  27661. });
  27662. };
  27663. LTCp.enqueueElementRefinement = function (ele) {
  27664. this.eleTxrDeqs.merge(ele);
  27665. this.scheduleElementRefinement();
  27666. };
  27667. LTCp.queueLayer = function (layer, ele) {
  27668. var self = this;
  27669. var q = self.layersQueue;
  27670. var elesQ = layer.elesQueue;
  27671. var hasId = elesQ.hasId = elesQ.hasId || {};
  27672. // if a layer is going to be replaced, queuing is a waste of time
  27673. if (layer.replacement) {
  27674. return;
  27675. }
  27676. if (ele) {
  27677. if (hasId[ele.id()]) {
  27678. return;
  27679. }
  27680. elesQ.push(ele);
  27681. hasId[ele.id()] = true;
  27682. }
  27683. if (layer.reqs) {
  27684. layer.reqs++;
  27685. q.updateItem(layer);
  27686. } else {
  27687. layer.reqs = 1;
  27688. q.push(layer);
  27689. }
  27690. };
  27691. LTCp.dequeue = function (pxRatio) {
  27692. var self = this;
  27693. var q = self.layersQueue;
  27694. var deqd = [];
  27695. var eleDeqs = 0;
  27696. while (eleDeqs < maxDeqSize) {
  27697. if (q.size() === 0) {
  27698. break;
  27699. }
  27700. var layer = q.peek();
  27701. // if a layer has been or will be replaced, then don't waste time with it
  27702. if (layer.replacement) {
  27703. // log('layer %s in queue skipped b/c it already has a replacement', layer.id);
  27704. q.pop();
  27705. continue;
  27706. }
  27707. // if this is a replacement layer that has been superceded, then forget it
  27708. if (layer.replaces && layer !== layer.replaces.replacement) {
  27709. // log('layer is no longer the most uptodate replacement; dequeued', layer.id)
  27710. q.pop();
  27711. continue;
  27712. }
  27713. if (layer.invalid) {
  27714. // log('replacement layer %s is invalid; dequeued', layer.id);
  27715. q.pop();
  27716. continue;
  27717. }
  27718. var ele = layer.elesQueue.shift();
  27719. if (ele) {
  27720. // log('dequeue layer %s', layer.id);
  27721. self.drawEleInLayer(layer, ele, layer.level, pxRatio);
  27722. eleDeqs++;
  27723. }
  27724. if (deqd.length === 0) {
  27725. // we need only one entry in deqd to queue redrawing etc
  27726. deqd.push(true);
  27727. }
  27728. // if the layer has all its eles done, then remove from the queue
  27729. if (layer.elesQueue.length === 0) {
  27730. q.pop();
  27731. layer.reqs = 0;
  27732. // log('dequeue of layer %s complete', layer.id);
  27733. // when a replacement layer is dequeued, it replaces the old layer in the level
  27734. if (layer.replaces) {
  27735. self.applyLayerReplacement(layer);
  27736. }
  27737. self.requestRedraw();
  27738. }
  27739. }
  27740. return deqd;
  27741. };
  27742. LTCp.applyLayerReplacement = function (layer) {
  27743. var self = this;
  27744. var layersInLevel = self.layersByLevel[layer.level];
  27745. var replaced = layer.replaces;
  27746. var index = layersInLevel.indexOf(replaced);
  27747. // if the replaced layer is not in the active list for the level, then replacing
  27748. // refs would be a mistake (i.e. overwriting the true active layer)
  27749. if (index < 0 || replaced.invalid) {
  27750. // log('replacement layer would have no effect', layer.id);
  27751. return;
  27752. }
  27753. layersInLevel[index] = layer; // replace level ref
  27754. // replace refs in eles
  27755. for (var i = 0; i < layer.eles.length; i++) {
  27756. var _p = layer.eles[i]._private;
  27757. var cache = _p.imgLayerCaches = _p.imgLayerCaches || {};
  27758. if (cache) {
  27759. cache[layer.level] = layer;
  27760. }
  27761. }
  27762. // log('apply replacement layer %s over %s', layer.id, replaced.id);
  27763. self.requestRedraw();
  27764. };
  27765. LTCp.requestRedraw = debounce(function () {
  27766. var r = this.renderer;
  27767. r.redrawHint('eles', true);
  27768. r.redrawHint('drag', true);
  27769. r.redraw();
  27770. }, 100);
  27771. LTCp.setupDequeueing = defs.setupDequeueing({
  27772. deqRedrawThreshold: deqRedrawThreshold,
  27773. deqCost: deqCost,
  27774. deqAvgCost: deqAvgCost,
  27775. deqNoDrawCost: deqNoDrawCost,
  27776. deqFastCost: deqFastCost,
  27777. deq: function deq(self, pxRatio) {
  27778. return self.dequeue(pxRatio);
  27779. },
  27780. onDeqd: noop$1,
  27781. shouldRedraw: trueify,
  27782. priority: function priority(self) {
  27783. return self.renderer.beforeRenderPriorities.lyrTxrDeq;
  27784. }
  27785. });
  27786. var CRp$b = {};
  27787. var impl;
  27788. function polygon(context, points) {
  27789. for (var i = 0; i < points.length; i++) {
  27790. var pt = points[i];
  27791. context.lineTo(pt.x, pt.y);
  27792. }
  27793. }
  27794. function triangleBackcurve(context, points, controlPoint) {
  27795. var firstPt;
  27796. for (var i = 0; i < points.length; i++) {
  27797. var pt = points[i];
  27798. if (i === 0) {
  27799. firstPt = pt;
  27800. }
  27801. context.lineTo(pt.x, pt.y);
  27802. }
  27803. context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);
  27804. }
  27805. function triangleTee(context, trianglePoints, teePoints) {
  27806. if (context.beginPath) {
  27807. context.beginPath();
  27808. }
  27809. var triPts = trianglePoints;
  27810. for (var i = 0; i < triPts.length; i++) {
  27811. var pt = triPts[i];
  27812. context.lineTo(pt.x, pt.y);
  27813. }
  27814. var teePts = teePoints;
  27815. var firstTeePt = teePoints[0];
  27816. context.moveTo(firstTeePt.x, firstTeePt.y);
  27817. for (var i = 1; i < teePts.length; i++) {
  27818. var pt = teePts[i];
  27819. context.lineTo(pt.x, pt.y);
  27820. }
  27821. if (context.closePath) {
  27822. context.closePath();
  27823. }
  27824. }
  27825. function circleTriangle(context, trianglePoints, rx, ry, r) {
  27826. if (context.beginPath) {
  27827. context.beginPath();
  27828. }
  27829. context.arc(rx, ry, r, 0, Math.PI * 2, false);
  27830. var triPts = trianglePoints;
  27831. var firstTrPt = triPts[0];
  27832. context.moveTo(firstTrPt.x, firstTrPt.y);
  27833. for (var i = 0; i < triPts.length; i++) {
  27834. var pt = triPts[i];
  27835. context.lineTo(pt.x, pt.y);
  27836. }
  27837. if (context.closePath) {
  27838. context.closePath();
  27839. }
  27840. }
  27841. function circle$1(context, rx, ry, r) {
  27842. context.arc(rx, ry, r, 0, Math.PI * 2, false);
  27843. }
  27844. CRp$b.arrowShapeImpl = function (name) {
  27845. return (impl || (impl = {
  27846. 'polygon': polygon,
  27847. 'triangle-backcurve': triangleBackcurve,
  27848. 'triangle-tee': triangleTee,
  27849. 'circle-triangle': circleTriangle,
  27850. 'triangle-cross': triangleTee,
  27851. 'circle': circle$1
  27852. }))[name];
  27853. };
  27854. var CRp$a = {};
  27855. CRp$a.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {
  27856. var r = this;
  27857. if (ele.isNode()) {
  27858. r.drawNode(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  27859. } else {
  27860. r.drawEdge(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  27861. }
  27862. };
  27863. CRp$a.drawElementOverlay = function (context, ele) {
  27864. var r = this;
  27865. if (ele.isNode()) {
  27866. r.drawNodeOverlay(context, ele);
  27867. } else {
  27868. r.drawEdgeOverlay(context, ele);
  27869. }
  27870. };
  27871. CRp$a.drawElementUnderlay = function (context, ele) {
  27872. var r = this;
  27873. if (ele.isNode()) {
  27874. r.drawNodeUnderlay(context, ele);
  27875. } else {
  27876. r.drawEdgeUnderlay(context, ele);
  27877. }
  27878. };
  27879. CRp$a.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {
  27880. var r = this;
  27881. var bb = eleTxrCache.getBoundingBox(ele);
  27882. if (bb.w === 0 || bb.h === 0) {
  27883. return;
  27884. } // ignore zero size case
  27885. var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);
  27886. if (eleCache != null) {
  27887. var opacity = getOpacity(r, ele);
  27888. if (opacity === 0) {
  27889. return;
  27890. }
  27891. var theta = getRotation(r, ele);
  27892. var x1 = bb.x1,
  27893. y1 = bb.y1,
  27894. w = bb.w,
  27895. h = bb.h;
  27896. var x, y, sx, sy, smooth;
  27897. if (theta !== 0) {
  27898. var rotPt = eleTxrCache.getRotationPoint(ele);
  27899. sx = rotPt.x;
  27900. sy = rotPt.y;
  27901. context.translate(sx, sy);
  27902. context.rotate(theta);
  27903. smooth = r.getImgSmoothing(context);
  27904. if (!smooth) {
  27905. r.setImgSmoothing(context, true);
  27906. }
  27907. var off = eleTxrCache.getRotationOffset(ele);
  27908. x = off.x;
  27909. y = off.y;
  27910. } else {
  27911. x = x1;
  27912. y = y1;
  27913. }
  27914. var oldGlobalAlpha;
  27915. if (opacity !== 1) {
  27916. oldGlobalAlpha = context.globalAlpha;
  27917. context.globalAlpha = oldGlobalAlpha * opacity;
  27918. }
  27919. context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);
  27920. if (opacity !== 1) {
  27921. context.globalAlpha = oldGlobalAlpha;
  27922. }
  27923. if (theta !== 0) {
  27924. context.rotate(-theta);
  27925. context.translate(-sx, -sy);
  27926. if (!smooth) {
  27927. r.setImgSmoothing(context, false);
  27928. }
  27929. }
  27930. } else {
  27931. eleTxrCache.drawElement(context, ele); // direct draw fallback
  27932. }
  27933. };
  27934. var getZeroRotation = function getZeroRotation() {
  27935. return 0;
  27936. };
  27937. var getLabelRotation = function getLabelRotation(r, ele) {
  27938. return r.getTextAngle(ele, null);
  27939. };
  27940. var getSourceLabelRotation = function getSourceLabelRotation(r, ele) {
  27941. return r.getTextAngle(ele, 'source');
  27942. };
  27943. var getTargetLabelRotation = function getTargetLabelRotation(r, ele) {
  27944. return r.getTextAngle(ele, 'target');
  27945. };
  27946. var getOpacity = function getOpacity(r, ele) {
  27947. return ele.effectiveOpacity();
  27948. };
  27949. var getTextOpacity = function getTextOpacity(e, ele) {
  27950. return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();
  27951. };
  27952. CRp$a.drawCachedElement = function (context, ele, pxRatio, extent, lvl, requestHighQuality) {
  27953. var r = this;
  27954. var _r$data = r.data,
  27955. eleTxrCache = _r$data.eleTxrCache,
  27956. lblTxrCache = _r$data.lblTxrCache,
  27957. slbTxrCache = _r$data.slbTxrCache,
  27958. tlbTxrCache = _r$data.tlbTxrCache;
  27959. var bb = ele.boundingBox();
  27960. var reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;
  27961. if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
  27962. return;
  27963. }
  27964. if (!extent || boundingBoxesIntersect(bb, extent)) {
  27965. var isEdge = ele.isEdge();
  27966. var badLine = ele.element()._private.rscratch.badLine;
  27967. r.drawElementUnderlay(context, ele);
  27968. r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);
  27969. if (!isEdge || !badLine) {
  27970. r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);
  27971. }
  27972. if (isEdge && !badLine) {
  27973. r.drawCachedElementPortion(context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation, getTextOpacity);
  27974. r.drawCachedElementPortion(context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation, getTextOpacity);
  27975. }
  27976. r.drawElementOverlay(context, ele);
  27977. }
  27978. };
  27979. CRp$a.drawElements = function (context, eles) {
  27980. var r = this;
  27981. for (var i = 0; i < eles.length; i++) {
  27982. var ele = eles[i];
  27983. r.drawElement(context, ele);
  27984. }
  27985. };
  27986. CRp$a.drawCachedElements = function (context, eles, pxRatio, extent) {
  27987. var r = this;
  27988. for (var i = 0; i < eles.length; i++) {
  27989. var ele = eles[i];
  27990. r.drawCachedElement(context, ele, pxRatio, extent);
  27991. }
  27992. };
  27993. CRp$a.drawCachedNodes = function (context, eles, pxRatio, extent) {
  27994. var r = this;
  27995. for (var i = 0; i < eles.length; i++) {
  27996. var ele = eles[i];
  27997. if (!ele.isNode()) {
  27998. continue;
  27999. }
  28000. r.drawCachedElement(context, ele, pxRatio, extent);
  28001. }
  28002. };
  28003. CRp$a.drawLayeredElements = function (context, eles, pxRatio, extent) {
  28004. var r = this;
  28005. var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);
  28006. if (layers) {
  28007. for (var i = 0; i < layers.length; i++) {
  28008. var layer = layers[i];
  28009. var bb = layer.bb;
  28010. if (bb.w === 0 || bb.h === 0) {
  28011. continue;
  28012. }
  28013. context.drawImage(layer.canvas, bb.x1, bb.y1, bb.w, bb.h);
  28014. }
  28015. } else {
  28016. // fall back on plain caching if no layers
  28017. r.drawCachedElements(context, eles, pxRatio, extent);
  28018. }
  28019. };
  28020. var CRp$9 = {};
  28021. CRp$9.drawEdge = function (context, edge, shiftToOriginWithBb) {
  28022. var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28023. var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28024. var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28025. var r = this;
  28026. var rs = edge._private.rscratch;
  28027. if (shouldDrawOpacity && !edge.visible()) {
  28028. return;
  28029. }
  28030. // if bezier ctrl pts can not be calculated, then die
  28031. if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
  28032. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  28033. return;
  28034. }
  28035. var bb;
  28036. if (shiftToOriginWithBb) {
  28037. bb = shiftToOriginWithBb;
  28038. context.translate(-bb.x1, -bb.y1);
  28039. }
  28040. var opacity = shouldDrawOpacity ? edge.pstyle('opacity').value : 1;
  28041. var lineOpacity = shouldDrawOpacity ? edge.pstyle('line-opacity').value : 1;
  28042. var curveStyle = edge.pstyle('curve-style').value;
  28043. var lineStyle = edge.pstyle('line-style').value;
  28044. var edgeWidth = edge.pstyle('width').pfValue;
  28045. var lineCap = edge.pstyle('line-cap').value;
  28046. var lineOutlineWidth = edge.pstyle('line-outline-width').value;
  28047. var lineOutlineColor = edge.pstyle('line-outline-color').value;
  28048. var effectiveLineOpacity = opacity * lineOpacity;
  28049. // separate arrow opacity would require arrow-opacity property
  28050. var effectiveArrowOpacity = opacity * lineOpacity;
  28051. var drawLine = function drawLine() {
  28052. var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
  28053. if (curveStyle === 'straight-triangle') {
  28054. r.eleStrokeStyle(context, edge, strokeOpacity);
  28055. r.drawEdgeTrianglePath(edge, context, rs.allpts);
  28056. } else {
  28057. context.lineWidth = edgeWidth;
  28058. context.lineCap = lineCap;
  28059. r.eleStrokeStyle(context, edge, strokeOpacity);
  28060. r.drawEdgePath(edge, context, rs.allpts, lineStyle);
  28061. context.lineCap = 'butt'; // reset for other drawing functions
  28062. }
  28063. };
  28064. var drawLineOutline = function drawLineOutline() {
  28065. var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
  28066. context.lineWidth = edgeWidth + lineOutlineWidth;
  28067. context.lineCap = lineCap;
  28068. if (lineOutlineWidth > 0) {
  28069. r.colorStrokeStyle(context, lineOutlineColor[0], lineOutlineColor[1], lineOutlineColor[2], strokeOpacity);
  28070. } else {
  28071. // do not draw any lineOutline
  28072. context.lineCap = 'butt'; // reset for other drawing functions
  28073. return;
  28074. }
  28075. if (curveStyle === 'straight-triangle') {
  28076. r.drawEdgeTrianglePath(edge, context, rs.allpts);
  28077. } else {
  28078. r.drawEdgePath(edge, context, rs.allpts, lineStyle);
  28079. context.lineCap = 'butt'; // reset for other drawing functions
  28080. }
  28081. };
  28082. var drawOverlay = function drawOverlay() {
  28083. if (!shouldDrawOverlay) {
  28084. return;
  28085. }
  28086. r.drawEdgeOverlay(context, edge);
  28087. };
  28088. var drawUnderlay = function drawUnderlay() {
  28089. if (!shouldDrawOverlay) {
  28090. return;
  28091. }
  28092. r.drawEdgeUnderlay(context, edge);
  28093. };
  28094. var drawArrows = function drawArrows() {
  28095. var arrowOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveArrowOpacity;
  28096. r.drawArrowheads(context, edge, arrowOpacity);
  28097. };
  28098. var drawText = function drawText() {
  28099. r.drawElementText(context, edge, null, drawLabel);
  28100. };
  28101. context.lineJoin = 'round';
  28102. var ghost = edge.pstyle('ghost').value === 'yes';
  28103. if (ghost) {
  28104. var gx = edge.pstyle('ghost-offset-x').pfValue;
  28105. var gy = edge.pstyle('ghost-offset-y').pfValue;
  28106. var ghostOpacity = edge.pstyle('ghost-opacity').value;
  28107. var effectiveGhostOpacity = effectiveLineOpacity * ghostOpacity;
  28108. context.translate(gx, gy);
  28109. drawLine(effectiveGhostOpacity);
  28110. drawArrows(effectiveGhostOpacity);
  28111. context.translate(-gx, -gy);
  28112. } else {
  28113. drawLineOutline();
  28114. }
  28115. drawUnderlay();
  28116. drawLine();
  28117. drawArrows();
  28118. drawOverlay();
  28119. drawText();
  28120. if (shiftToOriginWithBb) {
  28121. context.translate(bb.x1, bb.y1);
  28122. }
  28123. };
  28124. var drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {
  28125. if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
  28126. throw new Error('Invalid state');
  28127. }
  28128. return function (context, edge) {
  28129. if (!edge.visible()) {
  28130. return;
  28131. }
  28132. var opacity = edge.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
  28133. if (opacity === 0) {
  28134. return;
  28135. }
  28136. var r = this;
  28137. var usePaths = r.usePaths();
  28138. var rs = edge._private.rscratch;
  28139. var padding = edge.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
  28140. var width = 2 * padding;
  28141. var color = edge.pstyle("".concat(overlayOrUnderlay, "-color")).value;
  28142. context.lineWidth = width;
  28143. if (rs.edgeType === 'self' && !usePaths) {
  28144. context.lineCap = 'butt';
  28145. } else {
  28146. context.lineCap = 'round';
  28147. }
  28148. r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  28149. r.drawEdgePath(edge, context, rs.allpts, 'solid');
  28150. };
  28151. };
  28152. CRp$9.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');
  28153. CRp$9.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');
  28154. CRp$9.drawEdgePath = function (edge, context, pts, type) {
  28155. var rs = edge._private.rscratch;
  28156. var canvasCxt = context;
  28157. var path;
  28158. var pathCacheHit = false;
  28159. var usePaths = this.usePaths();
  28160. var lineDashPattern = edge.pstyle('line-dash-pattern').pfValue;
  28161. var lineDashOffset = edge.pstyle('line-dash-offset').pfValue;
  28162. if (usePaths) {
  28163. var pathCacheKey = pts.join('$');
  28164. var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;
  28165. if (keyMatches) {
  28166. path = context = rs.pathCache;
  28167. pathCacheHit = true;
  28168. } else {
  28169. path = context = new Path2D();
  28170. rs.pathCacheKey = pathCacheKey;
  28171. rs.pathCache = path;
  28172. }
  28173. }
  28174. if (canvasCxt.setLineDash) {
  28175. // for very outofdate browsers
  28176. switch (type) {
  28177. case 'dotted':
  28178. canvasCxt.setLineDash([1, 1]);
  28179. break;
  28180. case 'dashed':
  28181. canvasCxt.setLineDash(lineDashPattern);
  28182. canvasCxt.lineDashOffset = lineDashOffset;
  28183. break;
  28184. case 'solid':
  28185. canvasCxt.setLineDash([]);
  28186. break;
  28187. }
  28188. }
  28189. if (!pathCacheHit && !rs.badLine) {
  28190. if (context.beginPath) {
  28191. context.beginPath();
  28192. }
  28193. context.moveTo(pts[0], pts[1]);
  28194. switch (rs.edgeType) {
  28195. case 'bezier':
  28196. case 'self':
  28197. case 'compound':
  28198. case 'multibezier':
  28199. for (var i = 2; i + 3 < pts.length; i += 4) {
  28200. context.quadraticCurveTo(pts[i], pts[i + 1], pts[i + 2], pts[i + 3]);
  28201. }
  28202. break;
  28203. case 'straight':
  28204. case 'haystack':
  28205. for (var _i = 2; _i + 1 < pts.length; _i += 2) {
  28206. context.lineTo(pts[_i], pts[_i + 1]);
  28207. }
  28208. break;
  28209. case 'segments':
  28210. if (rs.isRound) {
  28211. var _iterator = _createForOfIteratorHelper(rs.roundCorners),
  28212. _step;
  28213. try {
  28214. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  28215. var corner = _step.value;
  28216. drawPreparedRoundCorner(context, corner);
  28217. }
  28218. } catch (err) {
  28219. _iterator.e(err);
  28220. } finally {
  28221. _iterator.f();
  28222. }
  28223. context.lineTo(pts[pts.length - 2], pts[pts.length - 1]);
  28224. } else {
  28225. for (var _i2 = 2; _i2 + 1 < pts.length; _i2 += 2) {
  28226. context.lineTo(pts[_i2], pts[_i2 + 1]);
  28227. }
  28228. }
  28229. break;
  28230. }
  28231. }
  28232. context = canvasCxt;
  28233. if (usePaths) {
  28234. context.stroke(path);
  28235. } else {
  28236. context.stroke();
  28237. }
  28238. // reset any line dashes
  28239. if (context.setLineDash) {
  28240. // for very outofdate browsers
  28241. context.setLineDash([]);
  28242. }
  28243. };
  28244. CRp$9.drawEdgeTrianglePath = function (edge, context, pts) {
  28245. // use line stroke style for triangle fill style
  28246. context.fillStyle = context.strokeStyle;
  28247. var edgeWidth = edge.pstyle('width').pfValue;
  28248. for (var i = 0; i + 1 < pts.length; i += 2) {
  28249. var vector = [pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]];
  28250. var length = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);
  28251. var normal = [vector[1] / length, -vector[0] / length];
  28252. var triangleHead = [normal[0] * edgeWidth / 2, normal[1] * edgeWidth / 2];
  28253. context.beginPath();
  28254. context.moveTo(pts[i] - triangleHead[0], pts[i + 1] - triangleHead[1]);
  28255. context.lineTo(pts[i] + triangleHead[0], pts[i + 1] + triangleHead[1]);
  28256. context.lineTo(pts[i + 2], pts[i + 3]);
  28257. context.closePath();
  28258. context.fill();
  28259. }
  28260. };
  28261. CRp$9.drawArrowheads = function (context, edge, opacity) {
  28262. var rs = edge._private.rscratch;
  28263. var isHaystack = rs.edgeType === 'haystack';
  28264. if (!isHaystack) {
  28265. this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);
  28266. }
  28267. this.drawArrowhead(context, edge, 'mid-target', rs.midX, rs.midY, rs.midtgtArrowAngle, opacity);
  28268. this.drawArrowhead(context, edge, 'mid-source', rs.midX, rs.midY, rs.midsrcArrowAngle, opacity);
  28269. if (!isHaystack) {
  28270. this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);
  28271. }
  28272. };
  28273. CRp$9.drawArrowhead = function (context, edge, prefix, x, y, angle, opacity) {
  28274. if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
  28275. return;
  28276. }
  28277. var self = this;
  28278. var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  28279. if (arrowShape === 'none') {
  28280. return;
  28281. }
  28282. var arrowClearFill = edge.pstyle(prefix + '-arrow-fill').value === 'hollow' ? 'both' : 'filled';
  28283. var arrowFill = edge.pstyle(prefix + '-arrow-fill').value;
  28284. var edgeWidth = edge.pstyle('width').pfValue;
  28285. var pArrowWidth = edge.pstyle(prefix + '-arrow-width');
  28286. var arrowWidth = pArrowWidth.value === 'match-line' ? edgeWidth : pArrowWidth.pfValue;
  28287. if (pArrowWidth.units === '%') arrowWidth *= edgeWidth;
  28288. var edgeOpacity = edge.pstyle('opacity').value;
  28289. if (opacity === undefined) {
  28290. opacity = edgeOpacity;
  28291. }
  28292. var gco = context.globalCompositeOperation;
  28293. if (opacity !== 1 || arrowFill === 'hollow') {
  28294. // then extra clear is needed
  28295. context.globalCompositeOperation = 'destination-out';
  28296. self.colorFillStyle(context, 255, 255, 255, 1);
  28297. self.colorStrokeStyle(context, 255, 255, 255, 1);
  28298. self.drawArrowShape(edge, context, arrowClearFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
  28299. context.globalCompositeOperation = gco;
  28300. } // otherwise, the opaque arrow clears it for free :)
  28301. var color = edge.pstyle(prefix + '-arrow-color').value;
  28302. self.colorFillStyle(context, color[0], color[1], color[2], opacity);
  28303. self.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  28304. self.drawArrowShape(edge, context, arrowFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
  28305. };
  28306. CRp$9.drawArrowShape = function (edge, context, fill, edgeWidth, shape, shapeWidth, x, y, angle) {
  28307. var r = this;
  28308. var usePaths = this.usePaths() && shape !== 'triangle-cross';
  28309. var pathCacheHit = false;
  28310. var path;
  28311. var canvasContext = context;
  28312. var translation = {
  28313. x: x,
  28314. y: y
  28315. };
  28316. var scale = edge.pstyle('arrow-scale').value;
  28317. var size = this.getArrowWidth(edgeWidth, scale);
  28318. var shapeImpl = r.arrowShapes[shape];
  28319. if (usePaths) {
  28320. var cache = r.arrowPathCache = r.arrowPathCache || [];
  28321. var key = hashString(shape);
  28322. var cachedPath = cache[key];
  28323. if (cachedPath != null) {
  28324. path = context = cachedPath;
  28325. pathCacheHit = true;
  28326. } else {
  28327. path = context = new Path2D();
  28328. cache[key] = path;
  28329. }
  28330. }
  28331. if (!pathCacheHit) {
  28332. if (context.beginPath) {
  28333. context.beginPath();
  28334. }
  28335. if (usePaths) {
  28336. // store in the path cache with values easily manipulated later
  28337. shapeImpl.draw(context, 1, 0, {
  28338. x: 0,
  28339. y: 0
  28340. }, 1);
  28341. } else {
  28342. shapeImpl.draw(context, size, angle, translation, edgeWidth);
  28343. }
  28344. if (context.closePath) {
  28345. context.closePath();
  28346. }
  28347. }
  28348. context = canvasContext;
  28349. if (usePaths) {
  28350. // set transform to arrow position/orientation
  28351. context.translate(x, y);
  28352. context.rotate(angle);
  28353. context.scale(size, size);
  28354. }
  28355. if (fill === 'filled' || fill === 'both') {
  28356. if (usePaths) {
  28357. context.fill(path);
  28358. } else {
  28359. context.fill();
  28360. }
  28361. }
  28362. if (fill === 'hollow' || fill === 'both') {
  28363. context.lineWidth = shapeWidth / (usePaths ? size : 1);
  28364. context.lineJoin = 'miter';
  28365. if (usePaths) {
  28366. context.stroke(path);
  28367. } else {
  28368. context.stroke();
  28369. }
  28370. }
  28371. if (usePaths) {
  28372. // reset transform by applying inverse
  28373. context.scale(1 / size, 1 / size);
  28374. context.rotate(-angle);
  28375. context.translate(-x, -y);
  28376. }
  28377. };
  28378. var CRp$8 = {};
  28379. CRp$8.safeDrawImage = function (context, img, ix, iy, iw, ih, x, y, w, h) {
  28380. // detect problematic cases for old browsers with bad images (cheaper than try-catch)
  28381. if (iw <= 0 || ih <= 0 || w <= 0 || h <= 0) {
  28382. return;
  28383. }
  28384. try {
  28385. context.drawImage(img, ix, iy, iw, ih, x, y, w, h);
  28386. } catch (e) {
  28387. warn(e);
  28388. }
  28389. };
  28390. CRp$8.drawInscribedImage = function (context, img, node, index, nodeOpacity) {
  28391. var r = this;
  28392. var pos = node.position();
  28393. var nodeX = pos.x;
  28394. var nodeY = pos.y;
  28395. var styleObj = node.cy().style();
  28396. var getIndexedStyle = styleObj.getIndexedStyle.bind(styleObj);
  28397. var fit = getIndexedStyle(node, 'background-fit', 'value', index);
  28398. var repeat = getIndexedStyle(node, 'background-repeat', 'value', index);
  28399. var nodeW = node.width();
  28400. var nodeH = node.height();
  28401. var paddingX2 = node.padding() * 2;
  28402. var nodeTW = nodeW + (getIndexedStyle(node, 'background-width-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  28403. var nodeTH = nodeH + (getIndexedStyle(node, 'background-height-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  28404. var rs = node._private.rscratch;
  28405. var clip = getIndexedStyle(node, 'background-clip', 'value', index);
  28406. var shouldClip = clip === 'node';
  28407. var imgOpacity = getIndexedStyle(node, 'background-image-opacity', 'value', index) * nodeOpacity;
  28408. var smooth = getIndexedStyle(node, 'background-image-smoothing', 'value', index);
  28409. var cornerRadius = node.pstyle('corner-radius').value;
  28410. if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  28411. var imgW = img.width || img.cachedW;
  28412. var imgH = img.height || img.cachedH;
  28413. // workaround for broken browsers like ie
  28414. if (null == imgW || null == imgH) {
  28415. document.body.appendChild(img); // eslint-disable-line no-undef
  28416. imgW = img.cachedW = img.width || img.offsetWidth;
  28417. imgH = img.cachedH = img.height || img.offsetHeight;
  28418. document.body.removeChild(img); // eslint-disable-line no-undef
  28419. }
  28420. var w = imgW;
  28421. var h = imgH;
  28422. if (getIndexedStyle(node, 'background-width', 'value', index) !== 'auto') {
  28423. if (getIndexedStyle(node, 'background-width', 'units', index) === '%') {
  28424. w = getIndexedStyle(node, 'background-width', 'pfValue', index) * nodeTW;
  28425. } else {
  28426. w = getIndexedStyle(node, 'background-width', 'pfValue', index);
  28427. }
  28428. }
  28429. if (getIndexedStyle(node, 'background-height', 'value', index) !== 'auto') {
  28430. if (getIndexedStyle(node, 'background-height', 'units', index) === '%') {
  28431. h = getIndexedStyle(node, 'background-height', 'pfValue', index) * nodeTH;
  28432. } else {
  28433. h = getIndexedStyle(node, 'background-height', 'pfValue', index);
  28434. }
  28435. }
  28436. if (w === 0 || h === 0) {
  28437. return; // no point in drawing empty image (and chrome is broken in this case)
  28438. }
  28439. if (fit === 'contain') {
  28440. var scale = Math.min(nodeTW / w, nodeTH / h);
  28441. w *= scale;
  28442. h *= scale;
  28443. } else if (fit === 'cover') {
  28444. var scale = Math.max(nodeTW / w, nodeTH / h);
  28445. w *= scale;
  28446. h *= scale;
  28447. }
  28448. var x = nodeX - nodeTW / 2; // left
  28449. var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);
  28450. var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);
  28451. if (posXUnits === '%') {
  28452. x += (nodeTW - w) * posXPfVal;
  28453. } else {
  28454. x += posXPfVal;
  28455. }
  28456. var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);
  28457. var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);
  28458. if (offXUnits === '%') {
  28459. x += (nodeTW - w) * offXPfVal;
  28460. } else {
  28461. x += offXPfVal;
  28462. }
  28463. var y = nodeY - nodeTH / 2; // top
  28464. var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);
  28465. var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);
  28466. if (posYUnits === '%') {
  28467. y += (nodeTH - h) * posYPfVal;
  28468. } else {
  28469. y += posYPfVal;
  28470. }
  28471. var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);
  28472. var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);
  28473. if (offYUnits === '%') {
  28474. y += (nodeTH - h) * offYPfVal;
  28475. } else {
  28476. y += offYPfVal;
  28477. }
  28478. if (rs.pathCache) {
  28479. x -= nodeX;
  28480. y -= nodeY;
  28481. nodeX = 0;
  28482. nodeY = 0;
  28483. }
  28484. var gAlpha = context.globalAlpha;
  28485. context.globalAlpha = imgOpacity;
  28486. var smoothingEnabled = r.getImgSmoothing(context);
  28487. var isSmoothingSwitched = false;
  28488. if (smooth === 'no' && smoothingEnabled) {
  28489. r.setImgSmoothing(context, false);
  28490. isSmoothingSwitched = true;
  28491. } else if (smooth === 'yes' && !smoothingEnabled) {
  28492. r.setImgSmoothing(context, true);
  28493. isSmoothingSwitched = true;
  28494. }
  28495. if (repeat === 'no-repeat') {
  28496. if (shouldClip) {
  28497. context.save();
  28498. if (rs.pathCache) {
  28499. context.clip(rs.pathCache);
  28500. } else {
  28501. r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
  28502. context.clip();
  28503. }
  28504. }
  28505. r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);
  28506. if (shouldClip) {
  28507. context.restore();
  28508. }
  28509. } else {
  28510. var pattern = context.createPattern(img, repeat);
  28511. context.fillStyle = pattern;
  28512. r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
  28513. context.translate(x, y);
  28514. context.fill();
  28515. context.translate(-x, -y);
  28516. }
  28517. context.globalAlpha = gAlpha;
  28518. if (isSmoothingSwitched) {
  28519. r.setImgSmoothing(context, smoothingEnabled);
  28520. }
  28521. };
  28522. var CRp$7 = {};
  28523. CRp$7.eleTextBiggerThanMin = function (ele, scale) {
  28524. if (!scale) {
  28525. var zoom = ele.cy().zoom();
  28526. var pxRatio = this.getPixelRatio();
  28527. var lvl = Math.ceil(log2(zoom * pxRatio)); // the effective texture level
  28528. scale = Math.pow(2, lvl);
  28529. }
  28530. var computedSize = ele.pstyle('font-size').pfValue * scale;
  28531. var minSize = ele.pstyle('min-zoomed-font-size').pfValue;
  28532. if (computedSize < minSize) {
  28533. return false;
  28534. }
  28535. return true;
  28536. };
  28537. CRp$7.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {
  28538. var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28539. var r = this;
  28540. if (force == null) {
  28541. if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {
  28542. return;
  28543. }
  28544. } else if (force === false) {
  28545. return;
  28546. }
  28547. if (ele.isNode()) {
  28548. var label = ele.pstyle('label');
  28549. if (!label || !label.value) {
  28550. return;
  28551. }
  28552. var justification = r.getLabelJustification(ele);
  28553. context.textAlign = justification;
  28554. context.textBaseline = 'bottom';
  28555. } else {
  28556. var badLine = ele.element()._private.rscratch.badLine;
  28557. var _label = ele.pstyle('label');
  28558. var srcLabel = ele.pstyle('source-label');
  28559. var tgtLabel = ele.pstyle('target-label');
  28560. if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {
  28561. return;
  28562. }
  28563. context.textAlign = 'center';
  28564. context.textBaseline = 'bottom';
  28565. }
  28566. var applyRotation = !shiftToOriginWithBb;
  28567. var bb;
  28568. if (shiftToOriginWithBb) {
  28569. bb = shiftToOriginWithBb;
  28570. context.translate(-bb.x1, -bb.y1);
  28571. }
  28572. if (prefix == null) {
  28573. r.drawText(context, ele, null, applyRotation, useEleOpacity);
  28574. if (ele.isEdge()) {
  28575. r.drawText(context, ele, 'source', applyRotation, useEleOpacity);
  28576. r.drawText(context, ele, 'target', applyRotation, useEleOpacity);
  28577. }
  28578. } else {
  28579. r.drawText(context, ele, prefix, applyRotation, useEleOpacity);
  28580. }
  28581. if (shiftToOriginWithBb) {
  28582. context.translate(bb.x1, bb.y1);
  28583. }
  28584. };
  28585. CRp$7.getFontCache = function (context) {
  28586. var cache;
  28587. this.fontCaches = this.fontCaches || [];
  28588. for (var i = 0; i < this.fontCaches.length; i++) {
  28589. cache = this.fontCaches[i];
  28590. if (cache.context === context) {
  28591. return cache;
  28592. }
  28593. }
  28594. cache = {
  28595. context: context
  28596. };
  28597. this.fontCaches.push(cache);
  28598. return cache;
  28599. };
  28600. // set up canvas context with font
  28601. // returns transformed text string
  28602. CRp$7.setupTextStyle = function (context, ele) {
  28603. var useEleOpacity = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  28604. // Font style
  28605. var labelStyle = ele.pstyle('font-style').strValue;
  28606. var labelSize = ele.pstyle('font-size').pfValue + 'px';
  28607. var labelFamily = ele.pstyle('font-family').strValue;
  28608. var labelWeight = ele.pstyle('font-weight').strValue;
  28609. var opacity = useEleOpacity ? ele.effectiveOpacity() * ele.pstyle('text-opacity').value : 1;
  28610. var outlineOpacity = ele.pstyle('text-outline-opacity').value * opacity;
  28611. var color = ele.pstyle('color').value;
  28612. var outlineColor = ele.pstyle('text-outline-color').value;
  28613. context.font = labelStyle + ' ' + labelWeight + ' ' + labelSize + ' ' + labelFamily;
  28614. context.lineJoin = 'round'; // so text outlines aren't jagged
  28615. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  28616. this.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], outlineOpacity);
  28617. };
  28618. function circle(ctx, x, y, width, height) {
  28619. var diameter = Math.min(width, height);
  28620. var radius = diameter / 2;
  28621. var centerX = x + width / 2;
  28622. var centerY = y + height / 2;
  28623. ctx.beginPath();
  28624. ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  28625. ctx.closePath();
  28626. }
  28627. function roundRect(ctx, x, y, width, height) {
  28628. var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;
  28629. var r = Math.min(radius, width / 2, height / 2); // prevent overflow
  28630. ctx.beginPath();
  28631. ctx.moveTo(x + r, y);
  28632. ctx.lineTo(x + width - r, y);
  28633. ctx.quadraticCurveTo(x + width, y, x + width, y + r);
  28634. ctx.lineTo(x + width, y + height - r);
  28635. ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
  28636. ctx.lineTo(x + r, y + height);
  28637. ctx.quadraticCurveTo(x, y + height, x, y + height - r);
  28638. ctx.lineTo(x, y + r);
  28639. ctx.quadraticCurveTo(x, y, x + r, y);
  28640. ctx.closePath();
  28641. }
  28642. CRp$7.getTextAngle = function (ele, prefix) {
  28643. var theta;
  28644. var _p = ele._private;
  28645. var rscratch = _p.rscratch;
  28646. var pdash = prefix ? prefix + '-' : '';
  28647. var rotation = ele.pstyle(pdash + 'text-rotation');
  28648. if (rotation.strValue === 'autorotate') {
  28649. var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);
  28650. theta = ele.isEdge() ? textAngle : 0;
  28651. } else if (rotation.strValue === 'none') {
  28652. theta = 0;
  28653. } else {
  28654. theta = rotation.pfValue;
  28655. }
  28656. return theta;
  28657. };
  28658. CRp$7.drawText = function (context, ele, prefix) {
  28659. var applyRotation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28660. var useEleOpacity = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28661. var _p = ele._private;
  28662. var rscratch = _p.rscratch;
  28663. var parentOpacity = useEleOpacity ? ele.effectiveOpacity() : 1;
  28664. if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {
  28665. return;
  28666. }
  28667. // use 'main' as an alias for the main label (i.e. null prefix)
  28668. if (prefix === 'main') {
  28669. prefix = null;
  28670. }
  28671. var textX = getPrefixedProperty(rscratch, 'labelX', prefix);
  28672. var textY = getPrefixedProperty(rscratch, 'labelY', prefix);
  28673. var orgTextX, orgTextY; // used for rotation
  28674. var text = this.getLabelText(ele, prefix);
  28675. if (text != null && text !== '' && !isNaN(textX) && !isNaN(textY)) {
  28676. this.setupTextStyle(context, ele, useEleOpacity);
  28677. var pdash = prefix ? prefix + '-' : '';
  28678. var textW = getPrefixedProperty(rscratch, 'labelWidth', prefix);
  28679. var textH = getPrefixedProperty(rscratch, 'labelHeight', prefix);
  28680. var marginX = ele.pstyle(pdash + 'text-margin-x').pfValue;
  28681. var marginY = ele.pstyle(pdash + 'text-margin-y').pfValue;
  28682. var isEdge = ele.isEdge();
  28683. var halign = ele.pstyle('text-halign').value;
  28684. var valign = ele.pstyle('text-valign').value;
  28685. if (isEdge) {
  28686. halign = 'center';
  28687. valign = 'center';
  28688. }
  28689. textX += marginX;
  28690. textY += marginY;
  28691. var theta;
  28692. if (!applyRotation) {
  28693. theta = 0;
  28694. } else {
  28695. theta = this.getTextAngle(ele, prefix);
  28696. }
  28697. if (theta !== 0) {
  28698. orgTextX = textX;
  28699. orgTextY = textY;
  28700. context.translate(orgTextX, orgTextY);
  28701. context.rotate(theta);
  28702. textX = 0;
  28703. textY = 0;
  28704. }
  28705. switch (valign) {
  28706. case 'top':
  28707. break;
  28708. case 'center':
  28709. textY += textH / 2;
  28710. break;
  28711. case 'bottom':
  28712. textY += textH;
  28713. break;
  28714. }
  28715. var backgroundOpacity = ele.pstyle('text-background-opacity').value;
  28716. var borderOpacity = ele.pstyle('text-border-opacity').value;
  28717. var textBorderWidth = ele.pstyle('text-border-width').pfValue;
  28718. var backgroundPadding = ele.pstyle('text-background-padding').pfValue;
  28719. var styleShape = ele.pstyle('text-background-shape').strValue;
  28720. var rounded = styleShape === 'round-rectangle' || styleShape === 'roundrectangle';
  28721. var circled = styleShape === 'circle';
  28722. var roundRadius = 2;
  28723. if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {
  28724. var textFill = context.fillStyle;
  28725. var textStroke = context.strokeStyle;
  28726. var textLineWidth = context.lineWidth;
  28727. var textBackgroundColor = ele.pstyle('text-background-color').value;
  28728. var textBorderColor = ele.pstyle('text-border-color').value;
  28729. var textBorderStyle = ele.pstyle('text-border-style').value;
  28730. var doFill = backgroundOpacity > 0;
  28731. var doStroke = textBorderWidth > 0 && borderOpacity > 0;
  28732. var bgX = textX - backgroundPadding;
  28733. switch (halign) {
  28734. case 'left':
  28735. bgX -= textW;
  28736. break;
  28737. case 'center':
  28738. bgX -= textW / 2;
  28739. break;
  28740. }
  28741. var bgY = textY - textH - backgroundPadding;
  28742. var bgW = textW + 2 * backgroundPadding;
  28743. var bgH = textH + 2 * backgroundPadding;
  28744. if (doFill) {
  28745. context.fillStyle = "rgba(".concat(textBackgroundColor[0], ",").concat(textBackgroundColor[1], ",").concat(textBackgroundColor[2], ",").concat(backgroundOpacity * parentOpacity, ")");
  28746. }
  28747. if (doStroke) {
  28748. context.strokeStyle = "rgba(".concat(textBorderColor[0], ",").concat(textBorderColor[1], ",").concat(textBorderColor[2], ",").concat(borderOpacity * parentOpacity, ")");
  28749. context.lineWidth = textBorderWidth;
  28750. if (context.setLineDash) {
  28751. switch (textBorderStyle) {
  28752. case 'dotted':
  28753. context.setLineDash([1, 1]);
  28754. break;
  28755. case 'dashed':
  28756. context.setLineDash([4, 2]);
  28757. break;
  28758. case 'double':
  28759. context.lineWidth = textBorderWidth / 4;
  28760. context.setLineDash([]);
  28761. break;
  28762. case 'solid':
  28763. default:
  28764. context.setLineDash([]);
  28765. break;
  28766. }
  28767. }
  28768. }
  28769. if (rounded) {
  28770. context.beginPath();
  28771. roundRect(context, bgX, bgY, bgW, bgH, roundRadius);
  28772. } else if (circled) {
  28773. context.beginPath();
  28774. circle(context, bgX, bgY, bgW, bgH);
  28775. } else {
  28776. context.beginPath();
  28777. context.rect(bgX, bgY, bgW, bgH);
  28778. }
  28779. if (doFill) context.fill();
  28780. if (doStroke) context.stroke();
  28781. // Double border pass for 'double' style
  28782. if (doStroke && textBorderStyle === 'double') {
  28783. var whiteWidth = textBorderWidth / 2;
  28784. context.beginPath();
  28785. if (rounded) {
  28786. roundRect(context, bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth, roundRadius);
  28787. } else {
  28788. context.rect(bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth);
  28789. }
  28790. context.stroke();
  28791. }
  28792. context.fillStyle = textFill;
  28793. context.strokeStyle = textStroke;
  28794. context.lineWidth = textLineWidth;
  28795. if (context.setLineDash) context.setLineDash([]);
  28796. }
  28797. var lineWidth = 2 * ele.pstyle('text-outline-width').pfValue; // *2 b/c the stroke is drawn centred on the middle
  28798. if (lineWidth > 0) {
  28799. context.lineWidth = lineWidth;
  28800. }
  28801. if (ele.pstyle('text-wrap').value === 'wrap') {
  28802. var lines = getPrefixedProperty(rscratch, 'labelWrapCachedLines', prefix);
  28803. var lineHeight = getPrefixedProperty(rscratch, 'labelLineHeight', prefix);
  28804. var halfTextW = textW / 2;
  28805. var justification = this.getLabelJustification(ele);
  28806. if (justification === 'auto') ; else if (halign === 'left') {
  28807. // auto justification : right
  28808. if (justification === 'left') {
  28809. textX += -textW;
  28810. } else if (justification === 'center') {
  28811. textX += -halfTextW;
  28812. } // else same as auto
  28813. } else if (halign === 'center') {
  28814. // auto justfication : center
  28815. if (justification === 'left') {
  28816. textX += -halfTextW;
  28817. } else if (justification === 'right') {
  28818. textX += halfTextW;
  28819. } // else same as auto
  28820. } else if (halign === 'right') {
  28821. // auto justification : left
  28822. if (justification === 'center') {
  28823. textX += halfTextW;
  28824. } else if (justification === 'right') {
  28825. textX += textW;
  28826. } // else same as auto
  28827. }
  28828. switch (valign) {
  28829. case 'top':
  28830. textY -= (lines.length - 1) * lineHeight;
  28831. break;
  28832. case 'center':
  28833. case 'bottom':
  28834. textY -= (lines.length - 1) * lineHeight;
  28835. break;
  28836. }
  28837. for (var l = 0; l < lines.length; l++) {
  28838. if (lineWidth > 0) {
  28839. context.strokeText(lines[l], textX, textY);
  28840. }
  28841. context.fillText(lines[l], textX, textY);
  28842. textY += lineHeight;
  28843. }
  28844. } else {
  28845. if (lineWidth > 0) {
  28846. context.strokeText(text, textX, textY);
  28847. }
  28848. context.fillText(text, textX, textY);
  28849. }
  28850. if (theta !== 0) {
  28851. context.rotate(-theta);
  28852. context.translate(-orgTextX, -orgTextY);
  28853. }
  28854. }
  28855. };
  28856. /* global Path2D */
  28857. var CRp$6 = {};
  28858. CRp$6.drawNode = function (context, node, shiftToOriginWithBb) {
  28859. var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28860. var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28861. var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28862. var r = this;
  28863. var nodeWidth, nodeHeight;
  28864. var _p = node._private;
  28865. var rs = _p.rscratch;
  28866. var pos = node.position();
  28867. if (!number$1(pos.x) || !number$1(pos.y)) {
  28868. return; // can't draw node with undefined position
  28869. }
  28870. if (shouldDrawOpacity && !node.visible()) {
  28871. return;
  28872. }
  28873. var eleOpacity = shouldDrawOpacity ? node.effectiveOpacity() : 1;
  28874. var usePaths = r.usePaths();
  28875. var path;
  28876. var pathCacheHit = false;
  28877. var padding = node.padding();
  28878. nodeWidth = node.width() + 2 * padding;
  28879. nodeHeight = node.height() + 2 * padding;
  28880. //
  28881. // setup shift
  28882. var bb;
  28883. if (shiftToOriginWithBb) {
  28884. bb = shiftToOriginWithBb;
  28885. context.translate(-bb.x1, -bb.y1);
  28886. }
  28887. //
  28888. // load bg image
  28889. var bgImgProp = node.pstyle('background-image');
  28890. var urls = bgImgProp.value;
  28891. var urlDefined = new Array(urls.length);
  28892. var image = new Array(urls.length);
  28893. var numImages = 0;
  28894. for (var i = 0; i < urls.length; i++) {
  28895. var url = urls[i];
  28896. var defd = urlDefined[i] = url != null && url !== 'none';
  28897. if (defd) {
  28898. var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);
  28899. numImages++;
  28900. // get image, and if not loaded then ask to redraw when later loaded
  28901. image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {
  28902. _p.backgroundTimestamp = Date.now();
  28903. node.emitAndNotify('background');
  28904. });
  28905. }
  28906. }
  28907. //
  28908. // setup styles
  28909. var darkness = node.pstyle('background-blacken').value;
  28910. var borderWidth = node.pstyle('border-width').pfValue;
  28911. var bgOpacity = node.pstyle('background-opacity').value * eleOpacity;
  28912. var borderColor = node.pstyle('border-color').value;
  28913. var borderStyle = node.pstyle('border-style').value;
  28914. var borderJoin = node.pstyle('border-join').value;
  28915. var borderCap = node.pstyle('border-cap').value;
  28916. var borderPosition = node.pstyle('border-position').value;
  28917. var borderPattern = node.pstyle('border-dash-pattern').pfValue;
  28918. var borderOffset = node.pstyle('border-dash-offset').pfValue;
  28919. var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;
  28920. var outlineWidth = node.pstyle('outline-width').pfValue;
  28921. var outlineColor = node.pstyle('outline-color').value;
  28922. var outlineStyle = node.pstyle('outline-style').value;
  28923. var outlineOpacity = node.pstyle('outline-opacity').value * eleOpacity;
  28924. var outlineOffset = node.pstyle('outline-offset').value;
  28925. var cornerRadius = node.pstyle('corner-radius').value;
  28926. if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  28927. var setupShapeColor = function setupShapeColor() {
  28928. var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
  28929. r.eleFillStyle(context, node, bgOpy);
  28930. };
  28931. var setupBorderColor = function setupBorderColor() {
  28932. var bdrOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : borderOpacity;
  28933. r.colorStrokeStyle(context, borderColor[0], borderColor[1], borderColor[2], bdrOpy);
  28934. };
  28935. var setupOutlineColor = function setupOutlineColor() {
  28936. var otlnOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : outlineOpacity;
  28937. r.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], otlnOpy);
  28938. };
  28939. //
  28940. // setup shape
  28941. var getPath = function getPath(width, height, shape, points) {
  28942. var pathCache = r.nodePathCache = r.nodePathCache || [];
  28943. var key = hashStrings(shape === 'polygon' ? shape + ',' + points.join(',') : shape, '' + height, '' + width, '' + cornerRadius);
  28944. var cachedPath = pathCache[key];
  28945. var path;
  28946. var cacheHit = false;
  28947. if (cachedPath != null) {
  28948. path = cachedPath;
  28949. cacheHit = true;
  28950. rs.pathCache = path;
  28951. } else {
  28952. path = new Path2D();
  28953. pathCache[key] = rs.pathCache = path;
  28954. }
  28955. return {
  28956. path: path,
  28957. cacheHit: cacheHit
  28958. };
  28959. };
  28960. var styleShape = node.pstyle('shape').strValue;
  28961. var shapePts = node.pstyle('shape-polygon-points').pfValue;
  28962. if (usePaths) {
  28963. context.translate(pos.x, pos.y);
  28964. var shapePath = getPath(nodeWidth, nodeHeight, styleShape, shapePts);
  28965. path = shapePath.path;
  28966. pathCacheHit = shapePath.cacheHit;
  28967. }
  28968. var drawShape = function drawShape() {
  28969. if (!pathCacheHit) {
  28970. var npos = pos;
  28971. if (usePaths) {
  28972. npos = {
  28973. x: 0,
  28974. y: 0
  28975. };
  28976. }
  28977. r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  28978. }
  28979. if (usePaths) {
  28980. context.fill(path);
  28981. } else {
  28982. context.fill();
  28983. }
  28984. };
  28985. var drawImages = function drawImages() {
  28986. var nodeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
  28987. var inside = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  28988. var prevBging = _p.backgrounding;
  28989. var totalCompleted = 0;
  28990. for (var _i = 0; _i < image.length; _i++) {
  28991. var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);
  28992. if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {
  28993. totalCompleted++;
  28994. continue;
  28995. }
  28996. if (urlDefined[_i] && image[_i].complete && !image[_i].error) {
  28997. totalCompleted++;
  28998. r.drawInscribedImage(context, image[_i], node, _i, nodeOpacity);
  28999. }
  29000. }
  29001. _p.backgrounding = !(totalCompleted === numImages);
  29002. if (prevBging !== _p.backgrounding) {
  29003. // update style b/c :backgrounding state changed
  29004. node.updateStyle(false);
  29005. }
  29006. };
  29007. var drawPie = function drawPie() {
  29008. var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  29009. var pieOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
  29010. if (r.hasPie(node)) {
  29011. r.drawPie(context, node, pieOpacity);
  29012. // redraw/restore path if steps after pie need it
  29013. if (redrawShape) {
  29014. if (!usePaths) {
  29015. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29016. }
  29017. }
  29018. }
  29019. };
  29020. var drawStripe = function drawStripe() {
  29021. var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  29022. var stripeOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
  29023. if (r.hasStripe(node)) {
  29024. context.save();
  29025. if (usePaths) {
  29026. context.clip(rs.pathCache);
  29027. } else {
  29028. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29029. context.clip();
  29030. }
  29031. r.drawStripe(context, node, stripeOpacity);
  29032. context.restore();
  29033. // redraw/restore path if steps after stripes need it
  29034. if (redrawShape) {
  29035. if (!usePaths) {
  29036. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29037. }
  29038. }
  29039. }
  29040. };
  29041. var darken = function darken() {
  29042. var darkenOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
  29043. var opacity = (darkness > 0 ? darkness : -darkness) * darkenOpacity;
  29044. var c = darkness > 0 ? 0 : 255;
  29045. if (darkness !== 0) {
  29046. r.colorFillStyle(context, c, c, c, opacity);
  29047. if (usePaths) {
  29048. context.fill(path);
  29049. } else {
  29050. context.fill();
  29051. }
  29052. }
  29053. };
  29054. var drawBorder = function drawBorder() {
  29055. if (borderWidth > 0) {
  29056. context.lineWidth = borderWidth;
  29057. context.lineCap = borderCap;
  29058. context.lineJoin = borderJoin;
  29059. if (context.setLineDash) {
  29060. // for very outofdate browsers
  29061. switch (borderStyle) {
  29062. case 'dotted':
  29063. context.setLineDash([1, 1]);
  29064. break;
  29065. case 'dashed':
  29066. context.setLineDash(borderPattern);
  29067. context.lineDashOffset = borderOffset;
  29068. break;
  29069. case 'solid':
  29070. case 'double':
  29071. context.setLineDash([]);
  29072. break;
  29073. }
  29074. }
  29075. if (borderPosition !== 'center') {
  29076. context.save();
  29077. context.lineWidth *= 2;
  29078. if (borderPosition === 'inside') {
  29079. usePaths ? context.clip(path) : context.clip();
  29080. } else {
  29081. var region = new Path2D();
  29082. region.rect(-nodeWidth / 2 - borderWidth, -nodeHeight / 2 - borderWidth, nodeWidth + 2 * borderWidth, nodeHeight + 2 * borderWidth);
  29083. region.addPath(path);
  29084. context.clip(region, 'evenodd');
  29085. }
  29086. usePaths ? context.stroke(path) : context.stroke();
  29087. context.restore();
  29088. } else {
  29089. usePaths ? context.stroke(path) : context.stroke();
  29090. }
  29091. if (borderStyle === 'double') {
  29092. context.lineWidth = borderWidth / 3;
  29093. var gco = context.globalCompositeOperation;
  29094. context.globalCompositeOperation = 'destination-out';
  29095. if (usePaths) {
  29096. context.stroke(path);
  29097. } else {
  29098. context.stroke();
  29099. }
  29100. context.globalCompositeOperation = gco;
  29101. }
  29102. // reset in case we changed the border style
  29103. if (context.setLineDash) {
  29104. // for very outofdate browsers
  29105. context.setLineDash([]);
  29106. }
  29107. }
  29108. };
  29109. var drawOutline = function drawOutline() {
  29110. if (outlineWidth > 0) {
  29111. context.lineWidth = outlineWidth;
  29112. context.lineCap = 'butt';
  29113. if (context.setLineDash) {
  29114. // for very outofdate browsers
  29115. switch (outlineStyle) {
  29116. case 'dotted':
  29117. context.setLineDash([1, 1]);
  29118. break;
  29119. case 'dashed':
  29120. context.setLineDash([4, 2]);
  29121. break;
  29122. case 'solid':
  29123. case 'double':
  29124. context.setLineDash([]);
  29125. break;
  29126. }
  29127. }
  29128. var npos = pos;
  29129. if (usePaths) {
  29130. npos = {
  29131. x: 0,
  29132. y: 0
  29133. };
  29134. }
  29135. var shape = r.getNodeShape(node);
  29136. var bWidth = borderWidth;
  29137. if (borderPosition === 'inside') bWidth = 0;
  29138. if (borderPosition === 'outside') bWidth *= 2;
  29139. var scaleX = (nodeWidth + bWidth + (outlineWidth + outlineOffset)) / nodeWidth;
  29140. var scaleY = (nodeHeight + bWidth + (outlineWidth + outlineOffset)) / nodeHeight;
  29141. var sWidth = nodeWidth * scaleX;
  29142. var sHeight = nodeHeight * scaleY;
  29143. var points = r.nodeShapes[shape].points;
  29144. var _path;
  29145. if (usePaths) {
  29146. var outlinePath = getPath(sWidth, sHeight, shape, points);
  29147. _path = outlinePath.path;
  29148. }
  29149. // draw the outline path, either by using expanded points or by scaling
  29150. // the dimensions, depending on shape
  29151. if (shape === "ellipse") {
  29152. r.drawEllipsePath(_path || context, npos.x, npos.y, sWidth, sHeight);
  29153. } else if (['round-diamond', 'round-heptagon', 'round-hexagon', 'round-octagon', 'round-pentagon', 'round-polygon', 'round-triangle', 'round-tag'].includes(shape)) {
  29154. var sMult = 0;
  29155. var offsetX = 0;
  29156. var offsetY = 0;
  29157. if (shape === 'round-diamond') {
  29158. sMult = (bWidth + outlineOffset + outlineWidth) * 1.4;
  29159. } else if (shape === 'round-heptagon') {
  29160. sMult = (bWidth + outlineOffset + outlineWidth) * 1.075;
  29161. offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 35;
  29162. } else if (shape === 'round-hexagon') {
  29163. sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
  29164. } else if (shape === 'round-pentagon') {
  29165. sMult = (bWidth + outlineOffset + outlineWidth) * 1.13;
  29166. offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 15;
  29167. } else if (shape === 'round-tag') {
  29168. sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
  29169. offsetX = (bWidth / 2 + outlineWidth + outlineOffset) * .07;
  29170. } else if (shape === 'round-triangle') {
  29171. sMult = (bWidth + outlineOffset + outlineWidth) * (Math.PI / 2);
  29172. offsetY = -(bWidth + outlineOffset / 2 + outlineWidth) / Math.PI;
  29173. }
  29174. if (sMult !== 0) {
  29175. scaleX = (nodeWidth + sMult) / nodeWidth;
  29176. sWidth = nodeWidth * scaleX;
  29177. if (!['round-hexagon', 'round-tag'].includes(shape)) {
  29178. scaleY = (nodeHeight + sMult) / nodeHeight;
  29179. sHeight = nodeHeight * scaleY;
  29180. }
  29181. }
  29182. cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(sWidth, sHeight) : cornerRadius;
  29183. var halfW = sWidth / 2;
  29184. var halfH = sHeight / 2;
  29185. var radius = cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2;
  29186. var p = new Array(points.length / 2);
  29187. var corners = new Array(points.length / 2);
  29188. for (var _i2 = 0; _i2 < points.length / 2; _i2++) {
  29189. p[_i2] = {
  29190. x: npos.x + offsetX + halfW * points[_i2 * 2],
  29191. y: npos.y + offsetY + halfH * points[_i2 * 2 + 1]
  29192. };
  29193. }
  29194. var _i3,
  29195. p1,
  29196. p2,
  29197. p3,
  29198. len = p.length;
  29199. p1 = p[len - 1];
  29200. // for each point
  29201. for (_i3 = 0; _i3 < len; _i3++) {
  29202. p2 = p[_i3 % len];
  29203. p3 = p[(_i3 + 1) % len];
  29204. corners[_i3] = getRoundCorner(p1, p2, p3, radius);
  29205. p1 = p2;
  29206. p2 = p3;
  29207. }
  29208. r.drawRoundPolygonPath(_path || context, npos.x + offsetX, npos.y + offsetY, nodeWidth * scaleX, nodeHeight * scaleY, points, corners);
  29209. } else if (['roundrectangle', 'round-rectangle'].includes(shape)) {
  29210. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
  29211. r.drawRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
  29212. } else if (['cutrectangle', 'cut-rectangle'].includes(shape)) {
  29213. cornerRadius = cornerRadius === 'auto' ? getCutRectangleCornerLength() : cornerRadius;
  29214. r.drawCutRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, null, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 4);
  29215. } else if (['bottomroundrectangle', 'bottom-round-rectangle'].includes(shape)) {
  29216. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
  29217. r.drawBottomRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
  29218. } else if (shape === "barrel") {
  29219. r.drawBarrelPath(_path || context, npos.x, npos.y, sWidth, sHeight);
  29220. } else if (shape.startsWith("polygon") || ['rhomboid', 'right-rhomboid', 'round-tag', 'tag', 'vee'].includes(shape)) {
  29221. var pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
  29222. points = joinLines(expandPolygon(points, pad));
  29223. r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
  29224. } else {
  29225. var _pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
  29226. points = joinLines(expandPolygon(points, -_pad));
  29227. r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
  29228. }
  29229. if (usePaths) {
  29230. context.stroke(_path);
  29231. } else {
  29232. context.stroke();
  29233. }
  29234. if (outlineStyle === 'double') {
  29235. context.lineWidth = bWidth / 3;
  29236. var gco = context.globalCompositeOperation;
  29237. context.globalCompositeOperation = 'destination-out';
  29238. if (usePaths) {
  29239. context.stroke(_path);
  29240. } else {
  29241. context.stroke();
  29242. }
  29243. context.globalCompositeOperation = gco;
  29244. }
  29245. // reset in case we changed the border style
  29246. if (context.setLineDash) {
  29247. // for very outofdate browsers
  29248. context.setLineDash([]);
  29249. }
  29250. }
  29251. };
  29252. var drawOverlay = function drawOverlay() {
  29253. if (shouldDrawOverlay) {
  29254. r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);
  29255. }
  29256. };
  29257. var drawUnderlay = function drawUnderlay() {
  29258. if (shouldDrawOverlay) {
  29259. r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);
  29260. }
  29261. };
  29262. var drawText = function drawText() {
  29263. r.drawElementText(context, node, null, drawLabel);
  29264. };
  29265. var ghost = node.pstyle('ghost').value === 'yes';
  29266. if (ghost) {
  29267. var gx = node.pstyle('ghost-offset-x').pfValue;
  29268. var gy = node.pstyle('ghost-offset-y').pfValue;
  29269. var ghostOpacity = node.pstyle('ghost-opacity').value;
  29270. var effGhostOpacity = ghostOpacity * eleOpacity;
  29271. context.translate(gx, gy);
  29272. setupOutlineColor();
  29273. drawOutline();
  29274. setupShapeColor(ghostOpacity * bgOpacity);
  29275. drawShape();
  29276. drawImages(effGhostOpacity, true);
  29277. setupBorderColor(ghostOpacity * borderOpacity);
  29278. drawBorder();
  29279. drawPie(darkness !== 0 || borderWidth !== 0);
  29280. drawStripe(darkness !== 0 || borderWidth !== 0);
  29281. drawImages(effGhostOpacity, false);
  29282. darken(effGhostOpacity);
  29283. context.translate(-gx, -gy);
  29284. }
  29285. if (usePaths) {
  29286. context.translate(-pos.x, -pos.y);
  29287. }
  29288. drawUnderlay();
  29289. if (usePaths) {
  29290. context.translate(pos.x, pos.y);
  29291. }
  29292. setupOutlineColor();
  29293. drawOutline();
  29294. setupShapeColor();
  29295. drawShape();
  29296. drawImages(eleOpacity, true);
  29297. setupBorderColor();
  29298. drawBorder();
  29299. drawPie(darkness !== 0 || borderWidth !== 0);
  29300. drawStripe(darkness !== 0 || borderWidth !== 0);
  29301. drawImages(eleOpacity, false);
  29302. darken();
  29303. if (usePaths) {
  29304. context.translate(-pos.x, -pos.y);
  29305. }
  29306. drawText();
  29307. drawOverlay();
  29308. //
  29309. // clean up shift
  29310. if (shiftToOriginWithBb) {
  29311. context.translate(bb.x1, bb.y1);
  29312. }
  29313. };
  29314. var drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {
  29315. if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
  29316. throw new Error('Invalid state');
  29317. }
  29318. return function (context, node, pos, nodeWidth, nodeHeight) {
  29319. var r = this;
  29320. if (!node.visible()) {
  29321. return;
  29322. }
  29323. var padding = node.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
  29324. var opacity = node.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
  29325. var color = node.pstyle("".concat(overlayOrUnderlay, "-color")).value;
  29326. var shape = node.pstyle("".concat(overlayOrUnderlay, "-shape")).value;
  29327. var radius = node.pstyle("".concat(overlayOrUnderlay, "-corner-radius")).value;
  29328. if (opacity > 0) {
  29329. pos = pos || node.position();
  29330. if (nodeWidth == null || nodeHeight == null) {
  29331. var _padding = node.padding();
  29332. nodeWidth = node.width() + 2 * _padding;
  29333. nodeHeight = node.height() + 2 * _padding;
  29334. }
  29335. r.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29336. r.nodeShapes[shape].draw(context, pos.x, pos.y, nodeWidth + padding * 2, nodeHeight + padding * 2, radius);
  29337. context.fill();
  29338. }
  29339. };
  29340. };
  29341. CRp$6.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');
  29342. CRp$6.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay');
  29343. // does the node have at least one pie piece?
  29344. CRp$6.hasPie = function (node) {
  29345. node = node[0]; // ensure ele ref
  29346. return node._private.hasPie;
  29347. };
  29348. CRp$6.hasStripe = function (node) {
  29349. node = node[0]; // ensure ele ref
  29350. return node._private.hasStripe;
  29351. };
  29352. CRp$6.drawPie = function (context, node, nodeOpacity, pos) {
  29353. node = node[0]; // ensure ele ref
  29354. pos = pos || node.position();
  29355. var cyStyle = node.cy().style();
  29356. var pieSize = node.pstyle('pie-size');
  29357. var hole = node.pstyle('pie-hole');
  29358. var overallStartAngle = node.pstyle('pie-start-angle').pfValue;
  29359. var x = pos.x;
  29360. var y = pos.y;
  29361. var nodeW = node.width();
  29362. var nodeH = node.height();
  29363. var radius = Math.min(nodeW, nodeH) / 2; // must fit in node
  29364. var holeRadius;
  29365. var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  29366. var usePaths = this.usePaths();
  29367. if (usePaths) {
  29368. x = 0;
  29369. y = 0;
  29370. }
  29371. if (pieSize.units === '%') {
  29372. radius = radius * pieSize.pfValue;
  29373. } else if (pieSize.pfValue !== undefined) {
  29374. radius = pieSize.pfValue / 2; // diameter in pixels => radius
  29375. }
  29376. if (hole.units === '%') {
  29377. holeRadius = radius * hole.pfValue;
  29378. } else if (hole.pfValue !== undefined) {
  29379. holeRadius = hole.pfValue / 2; // diameter in pixels => radius
  29380. }
  29381. if (holeRadius >= radius) {
  29382. return; // the pie would be invisible anyway
  29383. }
  29384. for (var i = 1; i <= cyStyle.pieBackgroundN; i++) {
  29385. // 1..N
  29386. var size = node.pstyle('pie-' + i + '-background-size').value;
  29387. var color = node.pstyle('pie-' + i + '-background-color').value;
  29388. var opacity = node.pstyle('pie-' + i + '-background-opacity').value * nodeOpacity;
  29389. var percent = size / 100; // map integer range [0, 100] to [0, 1]
  29390. // percent can't push beyond 1
  29391. if (percent + lastPercent > 1) {
  29392. percent = 1 - lastPercent;
  29393. }
  29394. var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise
  29395. angleStart += overallStartAngle; // shift by the overall pie start angle
  29396. var angleDelta = 2 * Math.PI * percent;
  29397. var angleEnd = angleStart + angleDelta;
  29398. // ignore if
  29399. // - zero size
  29400. // - we're already beyond the full circle
  29401. // - adding the current slice would go beyond the full circle
  29402. if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
  29403. continue;
  29404. }
  29405. if (holeRadius === 0) {
  29406. // make a pie slice
  29407. context.beginPath();
  29408. context.moveTo(x, y);
  29409. context.arc(x, y, radius, angleStart, angleEnd);
  29410. context.closePath();
  29411. } else {
  29412. // make a pie slice that's like the above but with a hole in the middle
  29413. context.beginPath();
  29414. context.arc(x, y, radius, angleStart, angleEnd);
  29415. context.arc(x, y, holeRadius, angleEnd, angleStart, true); // true for anticlockwise
  29416. context.closePath();
  29417. }
  29418. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29419. context.fill();
  29420. lastPercent += percent;
  29421. }
  29422. };
  29423. CRp$6.drawStripe = function (context, node, nodeOpacity, pos) {
  29424. node = node[0]; // ensure ele ref
  29425. pos = pos || node.position();
  29426. var cyStyle = node.cy().style();
  29427. var x = pos.x;
  29428. var y = pos.y;
  29429. var nodeW = node.width();
  29430. var nodeH = node.height();
  29431. var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  29432. var usePaths = this.usePaths();
  29433. context.save();
  29434. var direction = node.pstyle('stripe-direction').value;
  29435. var stripeSize = node.pstyle('stripe-size');
  29436. switch (direction) {
  29437. case 'vertical':
  29438. break;
  29439. // default
  29440. case 'righward':
  29441. context.rotate(-Math.PI / 2);
  29442. break;
  29443. }
  29444. var stripeW = nodeW;
  29445. var stripeH = nodeH;
  29446. if (stripeSize.units === '%') {
  29447. stripeW = stripeW * stripeSize.pfValue;
  29448. stripeH = stripeH * stripeSize.pfValue;
  29449. } else if (stripeSize.pfValue !== undefined) {
  29450. stripeW = stripeSize.pfValue;
  29451. stripeH = stripeSize.pfValue;
  29452. }
  29453. if (usePaths) {
  29454. x = 0;
  29455. y = 0;
  29456. }
  29457. // shift up from the centre of the node to the top-left corner
  29458. y -= stripeW / 2;
  29459. x -= stripeH / 2;
  29460. for (var i = 1; i <= cyStyle.stripeBackgroundN; i++) {
  29461. // 1..N
  29462. var size = node.pstyle('stripe-' + i + '-background-size').value;
  29463. var color = node.pstyle('stripe-' + i + '-background-color').value;
  29464. var opacity = node.pstyle('stripe-' + i + '-background-opacity').value * nodeOpacity;
  29465. var percent = size / 100; // map integer range [0, 100] to [0, 1]
  29466. // percent can't push beyond 1
  29467. if (percent + lastPercent > 1) {
  29468. percent = 1 - lastPercent;
  29469. }
  29470. // ignore if
  29471. // - zero size
  29472. // - we're already beyond the full chart
  29473. // - adding the current slice would go beyond the full chart
  29474. if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
  29475. continue;
  29476. }
  29477. // draw rect for the current stripe
  29478. context.beginPath();
  29479. context.rect(x, y + stripeH * lastPercent, stripeW, stripeH * percent);
  29480. context.closePath();
  29481. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29482. context.fill();
  29483. lastPercent += percent;
  29484. }
  29485. context.restore();
  29486. };
  29487. var CRp$5 = {};
  29488. var motionBlurDelay = 100;
  29489. // var isFirefox = typeof InstallTrigger !== 'undefined';
  29490. CRp$5.getPixelRatio = function () {
  29491. var context = this.data.contexts[0];
  29492. if (this.forcedPixelRatio != null) {
  29493. return this.forcedPixelRatio;
  29494. }
  29495. var containerWindow = this.cy.window();
  29496. var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29497. return (containerWindow.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef
  29498. };
  29499. CRp$5.paintCache = function (context) {
  29500. var caches = this.paintCaches = this.paintCaches || [];
  29501. var needToCreateCache = true;
  29502. var cache;
  29503. for (var i = 0; i < caches.length; i++) {
  29504. cache = caches[i];
  29505. if (cache.context === context) {
  29506. needToCreateCache = false;
  29507. break;
  29508. }
  29509. }
  29510. if (needToCreateCache) {
  29511. cache = {
  29512. context: context
  29513. };
  29514. caches.push(cache);
  29515. }
  29516. return cache;
  29517. };
  29518. CRp$5.createGradientStyleFor = function (context, shapeStyleName, ele, fill, opacity) {
  29519. var gradientStyle;
  29520. var usePaths = this.usePaths();
  29521. var colors = ele.pstyle(shapeStyleName + '-gradient-stop-colors').value,
  29522. positions = ele.pstyle(shapeStyleName + '-gradient-stop-positions').pfValue;
  29523. if (fill === 'radial-gradient') {
  29524. if (ele.isEdge()) {
  29525. var start = ele.sourceEndpoint(),
  29526. end = ele.targetEndpoint(),
  29527. mid = ele.midpoint();
  29528. var d1 = dist(start, mid);
  29529. var d2 = dist(end, mid);
  29530. gradientStyle = context.createRadialGradient(mid.x, mid.y, 0, mid.x, mid.y, Math.max(d1, d2));
  29531. } else {
  29532. var pos = usePaths ? {
  29533. x: 0,
  29534. y: 0
  29535. } : ele.position(),
  29536. width = ele.paddedWidth(),
  29537. height = ele.paddedHeight();
  29538. gradientStyle = context.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, Math.max(width, height));
  29539. }
  29540. } else {
  29541. if (ele.isEdge()) {
  29542. var _start = ele.sourceEndpoint(),
  29543. _end = ele.targetEndpoint();
  29544. gradientStyle = context.createLinearGradient(_start.x, _start.y, _end.x, _end.y);
  29545. } else {
  29546. var _pos = usePaths ? {
  29547. x: 0,
  29548. y: 0
  29549. } : ele.position(),
  29550. _width = ele.paddedWidth(),
  29551. _height = ele.paddedHeight(),
  29552. halfWidth = _width / 2,
  29553. halfHeight = _height / 2;
  29554. var direction = ele.pstyle('background-gradient-direction').value;
  29555. switch (direction) {
  29556. case 'to-bottom':
  29557. gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);
  29558. break;
  29559. case 'to-top':
  29560. gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);
  29561. break;
  29562. case 'to-left':
  29563. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);
  29564. break;
  29565. case 'to-right':
  29566. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);
  29567. break;
  29568. case 'to-bottom-right':
  29569. case 'to-right-bottom':
  29570. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y - halfHeight, _pos.x + halfWidth, _pos.y + halfHeight);
  29571. break;
  29572. case 'to-top-right':
  29573. case 'to-right-top':
  29574. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y + halfHeight, _pos.x + halfWidth, _pos.y - halfHeight);
  29575. break;
  29576. case 'to-bottom-left':
  29577. case 'to-left-bottom':
  29578. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y - halfHeight, _pos.x - halfWidth, _pos.y + halfHeight);
  29579. break;
  29580. case 'to-top-left':
  29581. case 'to-left-top':
  29582. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y + halfHeight, _pos.x - halfWidth, _pos.y - halfHeight);
  29583. break;
  29584. }
  29585. }
  29586. }
  29587. if (!gradientStyle) return null; // invalid gradient style
  29588. var hasPositions = positions.length === colors.length;
  29589. var length = colors.length;
  29590. for (var i = 0; i < length; i++) {
  29591. gradientStyle.addColorStop(hasPositions ? positions[i] : i / (length - 1), 'rgba(' + colors[i][0] + ',' + colors[i][1] + ',' + colors[i][2] + ',' + opacity + ')');
  29592. }
  29593. return gradientStyle;
  29594. };
  29595. CRp$5.gradientFillStyle = function (context, ele, fill, opacity) {
  29596. var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);
  29597. if (!gradientStyle) return null; // error
  29598. context.fillStyle = gradientStyle;
  29599. };
  29600. CRp$5.colorFillStyle = function (context, r, g, b, a) {
  29601. context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29602. // turn off for now, seems context does its own caching
  29603. // var cache = this.paintCache(context);
  29604. // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29605. // if( cache.fillStyle !== fillStyle ){
  29606. // context.fillStyle = cache.fillStyle = fillStyle;
  29607. // }
  29608. };
  29609. CRp$5.eleFillStyle = function (context, ele, opacity) {
  29610. var backgroundFill = ele.pstyle('background-fill').value;
  29611. if (backgroundFill === 'linear-gradient' || backgroundFill === 'radial-gradient') {
  29612. this.gradientFillStyle(context, ele, backgroundFill, opacity);
  29613. } else {
  29614. var backgroundColor = ele.pstyle('background-color').value;
  29615. this.colorFillStyle(context, backgroundColor[0], backgroundColor[1], backgroundColor[2], opacity);
  29616. }
  29617. };
  29618. CRp$5.gradientStrokeStyle = function (context, ele, fill, opacity) {
  29619. var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);
  29620. if (!gradientStyle) return null; // error
  29621. context.strokeStyle = gradientStyle;
  29622. };
  29623. CRp$5.colorStrokeStyle = function (context, r, g, b, a) {
  29624. context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29625. // turn off for now, seems context does its own caching
  29626. // var cache = this.paintCache(context);
  29627. // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29628. // if( cache.strokeStyle !== strokeStyle ){
  29629. // context.strokeStyle = cache.strokeStyle = strokeStyle;
  29630. // }
  29631. };
  29632. CRp$5.eleStrokeStyle = function (context, ele, opacity) {
  29633. var lineFill = ele.pstyle('line-fill').value;
  29634. if (lineFill === 'linear-gradient' || lineFill === 'radial-gradient') {
  29635. this.gradientStrokeStyle(context, ele, lineFill, opacity);
  29636. } else {
  29637. var lineColor = ele.pstyle('line-color').value;
  29638. this.colorStrokeStyle(context, lineColor[0], lineColor[1], lineColor[2], opacity);
  29639. }
  29640. };
  29641. // Resize canvas
  29642. CRp$5.matchCanvasSize = function (container) {
  29643. var r = this;
  29644. var data = r.data;
  29645. var bb = r.findContainerClientCoords();
  29646. var width = bb[2];
  29647. var height = bb[3];
  29648. var pixelRatio = r.getPixelRatio();
  29649. var mbPxRatio = r.motionBlurPxRatio;
  29650. if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {
  29651. pixelRatio = mbPxRatio;
  29652. }
  29653. var canvasWidth = width * pixelRatio;
  29654. var canvasHeight = height * pixelRatio;
  29655. var canvas;
  29656. if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {
  29657. return; // save cycles if same
  29658. }
  29659. r.fontCaches = null; // resizing resets the style
  29660. var canvasContainer = data.canvasContainer;
  29661. canvasContainer.style.width = width + 'px';
  29662. canvasContainer.style.height = height + 'px';
  29663. for (var i = 0; i < r.CANVAS_LAYERS; i++) {
  29664. canvas = data.canvases[i];
  29665. canvas.width = canvasWidth;
  29666. canvas.height = canvasHeight;
  29667. canvas.style.width = width + 'px';
  29668. canvas.style.height = height + 'px';
  29669. }
  29670. for (var i = 0; i < r.BUFFER_COUNT; i++) {
  29671. canvas = data.bufferCanvases[i];
  29672. canvas.width = canvasWidth;
  29673. canvas.height = canvasHeight;
  29674. canvas.style.width = width + 'px';
  29675. canvas.style.height = height + 'px';
  29676. }
  29677. r.textureMult = 1;
  29678. if (pixelRatio <= 1) {
  29679. canvas = data.bufferCanvases[r.TEXTURE_BUFFER];
  29680. r.textureMult = 2;
  29681. canvas.width = canvasWidth * r.textureMult;
  29682. canvas.height = canvasHeight * r.textureMult;
  29683. }
  29684. r.canvasWidth = canvasWidth;
  29685. r.canvasHeight = canvasHeight;
  29686. r.pixelRatio = pixelRatio;
  29687. };
  29688. CRp$5.renderTo = function (cxt, zoom, pan, pxRatio) {
  29689. this.render({
  29690. forcedContext: cxt,
  29691. forcedZoom: zoom,
  29692. forcedPan: pan,
  29693. drawAllLayers: true,
  29694. forcedPxRatio: pxRatio
  29695. });
  29696. };
  29697. CRp$5.clearCanvas = function () {
  29698. var r = this;
  29699. var data = r.data;
  29700. function clear(context) {
  29701. context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  29702. }
  29703. clear(data.contexts[r.NODE]);
  29704. clear(data.contexts[r.DRAG]);
  29705. };
  29706. CRp$5.render = function (options) {
  29707. var r = this;
  29708. options = options || staticEmptyObject();
  29709. var cy = r.cy;
  29710. var forcedContext = options.forcedContext;
  29711. var drawAllLayers = options.drawAllLayers;
  29712. var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  29713. var forcedZoom = options.forcedZoom;
  29714. var forcedPan = options.forcedPan;
  29715. var pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;
  29716. var data = r.data;
  29717. var needDraw = data.canvasNeedsRedraw;
  29718. var textureDraw = r.textureOnViewport && !forcedContext && (r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming);
  29719. var motionBlur = options.motionBlur !== undefined ? options.motionBlur : r.motionBlur;
  29720. var mbPxRatio = r.motionBlurPxRatio;
  29721. var hasCompoundNodes = cy.hasCompoundNodes();
  29722. var inNodeDragGesture = r.hoverData.draggingEles;
  29723. var inBoxSelection = r.hoverData.selecting || r.touchData.selecting ? true : false;
  29724. motionBlur = motionBlur && !forcedContext && r.motionBlurEnabled && !inBoxSelection;
  29725. var motionBlurFadeEffect = motionBlur;
  29726. if (!forcedContext) {
  29727. if (r.prevPxRatio !== pixelRatio) {
  29728. r.invalidateContainerClientCoordsCache();
  29729. r.matchCanvasSize(r.container);
  29730. r.redrawHint('eles', true);
  29731. r.redrawHint('drag', true);
  29732. }
  29733. r.prevPxRatio = pixelRatio;
  29734. }
  29735. if (!forcedContext && r.motionBlurTimeout) {
  29736. clearTimeout(r.motionBlurTimeout);
  29737. }
  29738. if (motionBlur) {
  29739. if (r.mbFrames == null) {
  29740. r.mbFrames = 0;
  29741. }
  29742. r.mbFrames++;
  29743. if (r.mbFrames < 3) {
  29744. // need several frames before even high quality motionblur
  29745. motionBlurFadeEffect = false;
  29746. }
  29747. // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)
  29748. if (r.mbFrames > r.minMbLowQualFrames) {
  29749. //r.fullQualityMb = false;
  29750. r.motionBlurPxRatio = r.mbPxRBlurry;
  29751. }
  29752. }
  29753. if (r.clearingMotionBlur) {
  29754. r.motionBlurPxRatio = 1;
  29755. }
  29756. // b/c drawToContext() may be async w.r.t. redraw(), keep track of last texture frame
  29757. // because a rogue async texture frame would clear needDraw
  29758. if (r.textureDrawLastFrame && !textureDraw) {
  29759. needDraw[r.NODE] = true;
  29760. needDraw[r.SELECT_BOX] = true;
  29761. }
  29762. var style = cy.style();
  29763. var zoom = cy.zoom();
  29764. var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;
  29765. var pan = cy.pan();
  29766. var effectivePan = {
  29767. x: pan.x,
  29768. y: pan.y
  29769. };
  29770. var vp = {
  29771. zoom: zoom,
  29772. pan: {
  29773. x: pan.x,
  29774. y: pan.y
  29775. }
  29776. };
  29777. var prevVp = r.prevViewport;
  29778. var viewportIsDiff = prevVp === undefined || vp.zoom !== prevVp.zoom || vp.pan.x !== prevVp.pan.x || vp.pan.y !== prevVp.pan.y;
  29779. // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)
  29780. if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {
  29781. r.motionBlurPxRatio = 1;
  29782. }
  29783. if (forcedPan) {
  29784. effectivePan = forcedPan;
  29785. }
  29786. // apply pixel ratio
  29787. effectiveZoom *= pixelRatio;
  29788. effectivePan.x *= pixelRatio;
  29789. effectivePan.y *= pixelRatio;
  29790. var eles = r.getCachedZSortedEles();
  29791. function mbclear(context, x, y, w, h) {
  29792. var gco = context.globalCompositeOperation;
  29793. context.globalCompositeOperation = 'destination-out';
  29794. r.colorFillStyle(context, 255, 255, 255, r.motionBlurTransparency);
  29795. context.fillRect(x, y, w, h);
  29796. context.globalCompositeOperation = gco;
  29797. }
  29798. function setContextTransform(context, clear) {
  29799. var ePan, eZoom, w, h;
  29800. if (!r.clearingMotionBlur && (context === data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] || context === data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG])) {
  29801. ePan = {
  29802. x: pan.x * mbPxRatio,
  29803. y: pan.y * mbPxRatio
  29804. };
  29805. eZoom = zoom * mbPxRatio;
  29806. w = r.canvasWidth * mbPxRatio;
  29807. h = r.canvasHeight * mbPxRatio;
  29808. } else {
  29809. ePan = effectivePan;
  29810. eZoom = effectiveZoom;
  29811. w = r.canvasWidth;
  29812. h = r.canvasHeight;
  29813. }
  29814. context.setTransform(1, 0, 0, 1, 0, 0);
  29815. if (clear === 'motionBlur') {
  29816. mbclear(context, 0, 0, w, h);
  29817. } else if (!forcedContext && (clear === undefined || clear)) {
  29818. context.clearRect(0, 0, w, h);
  29819. }
  29820. if (!drawAllLayers) {
  29821. context.translate(ePan.x, ePan.y);
  29822. context.scale(eZoom, eZoom);
  29823. }
  29824. if (forcedPan) {
  29825. context.translate(forcedPan.x, forcedPan.y);
  29826. }
  29827. if (forcedZoom) {
  29828. context.scale(forcedZoom, forcedZoom);
  29829. }
  29830. }
  29831. if (!textureDraw) {
  29832. r.textureDrawLastFrame = false;
  29833. }
  29834. if (textureDraw) {
  29835. r.textureDrawLastFrame = true;
  29836. if (!r.textureCache) {
  29837. r.textureCache = {};
  29838. r.textureCache.bb = cy.mutableElements().boundingBox();
  29839. r.textureCache.texture = r.data.bufferCanvases[r.TEXTURE_BUFFER];
  29840. var cxt = r.data.bufferContexts[r.TEXTURE_BUFFER];
  29841. cxt.setTransform(1, 0, 0, 1, 0, 0);
  29842. cxt.clearRect(0, 0, r.canvasWidth * r.textureMult, r.canvasHeight * r.textureMult);
  29843. r.render({
  29844. forcedContext: cxt,
  29845. drawOnlyNodeLayer: true,
  29846. forcedPxRatio: pixelRatio * r.textureMult
  29847. });
  29848. var vp = r.textureCache.viewport = {
  29849. zoom: cy.zoom(),
  29850. pan: cy.pan(),
  29851. width: r.canvasWidth,
  29852. height: r.canvasHeight
  29853. };
  29854. vp.mpan = {
  29855. x: (0 - vp.pan.x) / vp.zoom,
  29856. y: (0 - vp.pan.y) / vp.zoom
  29857. };
  29858. }
  29859. needDraw[r.DRAG] = false;
  29860. needDraw[r.NODE] = false;
  29861. var context = data.contexts[r.NODE];
  29862. var texture = r.textureCache.texture;
  29863. var vp = r.textureCache.viewport;
  29864. context.setTransform(1, 0, 0, 1, 0, 0);
  29865. if (motionBlur) {
  29866. mbclear(context, 0, 0, vp.width, vp.height);
  29867. } else {
  29868. context.clearRect(0, 0, vp.width, vp.height);
  29869. }
  29870. var outsideBgColor = style.core('outside-texture-bg-color').value;
  29871. var outsideBgOpacity = style.core('outside-texture-bg-opacity').value;
  29872. r.colorFillStyle(context, outsideBgColor[0], outsideBgColor[1], outsideBgColor[2], outsideBgOpacity);
  29873. context.fillRect(0, 0, vp.width, vp.height);
  29874. var zoom = cy.zoom();
  29875. setContextTransform(context, false);
  29876. context.clearRect(vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  29877. context.drawImage(texture, vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  29878. } else if (r.textureOnViewport && !forcedContext) {
  29879. // clear the cache since we don't need it
  29880. r.textureCache = null;
  29881. }
  29882. var extent = cy.extent();
  29883. var vpManip = r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming || r.hoverData.draggingEles || r.cy.animated();
  29884. var hideEdges = r.hideEdgesOnViewport && vpManip;
  29885. var needMbClear = [];
  29886. needMbClear[r.NODE] = !needDraw[r.NODE] && motionBlur && !r.clearedForMotionBlur[r.NODE] || r.clearingMotionBlur;
  29887. if (needMbClear[r.NODE]) {
  29888. r.clearedForMotionBlur[r.NODE] = true;
  29889. }
  29890. needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;
  29891. if (needMbClear[r.DRAG]) {
  29892. r.clearedForMotionBlur[r.DRAG] = true;
  29893. }
  29894. if (needDraw[r.NODE] || drawAllLayers || drawOnlyNodeLayer || needMbClear[r.NODE]) {
  29895. var useBuffer = motionBlur && !needMbClear[r.NODE] && mbPxRatio !== 1;
  29896. var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] : data.contexts[r.NODE]);
  29897. var clear = motionBlur && !useBuffer ? 'motionBlur' : undefined;
  29898. setContextTransform(context, clear);
  29899. if (hideEdges) {
  29900. r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);
  29901. } else {
  29902. r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);
  29903. }
  29904. if (r.debug) {
  29905. r.drawDebugPoints(context, eles.nondrag);
  29906. }
  29907. if (!drawAllLayers && !motionBlur) {
  29908. needDraw[r.NODE] = false;
  29909. }
  29910. }
  29911. if (!drawOnlyNodeLayer && (needDraw[r.DRAG] || drawAllLayers || needMbClear[r.DRAG])) {
  29912. var useBuffer = motionBlur && !needMbClear[r.DRAG] && mbPxRatio !== 1;
  29913. var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG] : data.contexts[r.DRAG]);
  29914. setContextTransform(context, motionBlur && !useBuffer ? 'motionBlur' : undefined);
  29915. if (hideEdges) {
  29916. r.drawCachedNodes(context, eles.drag, pixelRatio, extent);
  29917. } else {
  29918. r.drawCachedElements(context, eles.drag, pixelRatio, extent);
  29919. }
  29920. if (r.debug) {
  29921. r.drawDebugPoints(context, eles.drag);
  29922. }
  29923. if (!drawAllLayers && !motionBlur) {
  29924. needDraw[r.DRAG] = false;
  29925. }
  29926. }
  29927. this.drawSelectionRectangle(options, setContextTransform);
  29928. // motionblur: blit rendered blurry frames
  29929. if (motionBlur && mbPxRatio !== 1) {
  29930. var cxtNode = data.contexts[r.NODE];
  29931. var txtNode = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE];
  29932. var cxtDrag = data.contexts[r.DRAG];
  29933. var txtDrag = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG];
  29934. var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {
  29935. cxt.setTransform(1, 0, 0, 1, 0, 0);
  29936. if (needClear || !motionBlurFadeEffect) {
  29937. cxt.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  29938. } else {
  29939. mbclear(cxt, 0, 0, r.canvasWidth, r.canvasHeight);
  29940. }
  29941. var pxr = mbPxRatio;
  29942. cxt.drawImage(txt,
  29943. // img
  29944. 0, 0,
  29945. // sx, sy
  29946. r.canvasWidth * pxr, r.canvasHeight * pxr,
  29947. // sw, sh
  29948. 0, 0,
  29949. // x, y
  29950. r.canvasWidth, r.canvasHeight // w, h
  29951. );
  29952. };
  29953. if (needDraw[r.NODE] || needMbClear[r.NODE]) {
  29954. drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);
  29955. needDraw[r.NODE] = false;
  29956. }
  29957. if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {
  29958. drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);
  29959. needDraw[r.DRAG] = false;
  29960. }
  29961. }
  29962. r.prevViewport = vp;
  29963. if (r.clearingMotionBlur) {
  29964. r.clearingMotionBlur = false;
  29965. r.motionBlurCleared = true;
  29966. r.motionBlur = true;
  29967. }
  29968. if (motionBlur) {
  29969. r.motionBlurTimeout = setTimeout(function () {
  29970. r.motionBlurTimeout = null;
  29971. r.clearedForMotionBlur[r.NODE] = false;
  29972. r.clearedForMotionBlur[r.DRAG] = false;
  29973. r.motionBlur = false;
  29974. r.clearingMotionBlur = !textureDraw;
  29975. r.mbFrames = 0;
  29976. needDraw[r.NODE] = true;
  29977. needDraw[r.DRAG] = true;
  29978. r.redraw();
  29979. }, motionBlurDelay);
  29980. }
  29981. if (!forcedContext) {
  29982. cy.emit('render');
  29983. }
  29984. };
  29985. var fpsHeight;
  29986. CRp$5.drawSelectionRectangle = function (options, setContextTransform) {
  29987. var r = this;
  29988. var cy = r.cy;
  29989. var data = r.data;
  29990. var style = cy.style();
  29991. var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  29992. var drawAllLayers = options.drawAllLayers;
  29993. var needDraw = data.canvasNeedsRedraw;
  29994. var forcedContext = options.forcedContext;
  29995. if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {
  29996. var context = forcedContext || data.contexts[r.SELECT_BOX];
  29997. setContextTransform(context);
  29998. if (r.selection[4] == 1 && (r.hoverData.selecting || r.touchData.selecting)) {
  29999. var zoom = r.cy.zoom();
  30000. var borderWidth = style.core('selection-box-border-width').value / zoom;
  30001. context.lineWidth = borderWidth;
  30002. context.fillStyle = 'rgba(' + style.core('selection-box-color').value[0] + ',' + style.core('selection-box-color').value[1] + ',' + style.core('selection-box-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';
  30003. context.fillRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
  30004. if (borderWidth > 0) {
  30005. context.strokeStyle = 'rgba(' + style.core('selection-box-border-color').value[0] + ',' + style.core('selection-box-border-color').value[1] + ',' + style.core('selection-box-border-color').value[2] + ',' + style.core('selection-box-opacity').value + ')';
  30006. context.strokeRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
  30007. }
  30008. }
  30009. if (data.bgActivePosistion && !r.hoverData.selecting) {
  30010. var zoom = r.cy.zoom();
  30011. var pos = data.bgActivePosistion;
  30012. context.fillStyle = 'rgba(' + style.core('active-bg-color').value[0] + ',' + style.core('active-bg-color').value[1] + ',' + style.core('active-bg-color').value[2] + ',' + style.core('active-bg-opacity').value + ')';
  30013. context.beginPath();
  30014. context.arc(pos.x, pos.y, style.core('active-bg-size').pfValue / zoom, 0, 2 * Math.PI);
  30015. context.fill();
  30016. }
  30017. var timeToRender = r.lastRedrawTime;
  30018. if (r.showFps && timeToRender) {
  30019. timeToRender = Math.round(timeToRender);
  30020. var fps = Math.round(1000 / timeToRender);
  30021. var text = '1 frame = ' + timeToRender + ' ms = ' + fps + ' fps';
  30022. context.setTransform(1, 0, 0, 1, 0, 0);
  30023. context.fillStyle = 'rgba(255, 0, 0, 0.75)';
  30024. context.strokeStyle = 'rgba(255, 0, 0, 0.75)';
  30025. // context.lineWidth = 1;
  30026. context.font = '30px Arial';
  30027. if (!fpsHeight) {
  30028. var dims = context.measureText(text);
  30029. fpsHeight = dims.actualBoundingBoxAscent;
  30030. }
  30031. context.fillText(text, 0, fpsHeight);
  30032. var maxFps = 60;
  30033. context.strokeRect(0, fpsHeight + 10, 250, 20);
  30034. context.fillRect(0, fpsHeight + 10, 250 * Math.min(fps / maxFps, 1), 20);
  30035. }
  30036. if (!drawAllLayers) {
  30037. needDraw[r.SELECT_BOX] = false;
  30038. }
  30039. }
  30040. };
  30041. /**
  30042. * Notes:
  30043. * - All colors have premultiplied alpha. Very important for textues and
  30044. * blending to work correctly.
  30045. */
  30046. function compileShader(gl, type, source) {
  30047. var shader = gl.createShader(type);
  30048. gl.shaderSource(shader, source);
  30049. gl.compileShader(shader);
  30050. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  30051. throw new Error(gl.getShaderInfoLog(shader));
  30052. }
  30053. // console.log(gl.getShaderInfoLog(shader));
  30054. return shader;
  30055. }
  30056. function createProgram(gl, vertexSource, fragementSource) {
  30057. var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);
  30058. var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragementSource);
  30059. var program = gl.createProgram();
  30060. gl.attachShader(program, vertexShader);
  30061. gl.attachShader(program, fragmentShader);
  30062. gl.linkProgram(program);
  30063. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  30064. throw new Error('Could not initialize shaders');
  30065. }
  30066. return program;
  30067. }
  30068. /**
  30069. * Creates an offscren canvas with a 2D context, for the
  30070. * canvas renderer to use for drawing textures.
  30071. */
  30072. function createTextureCanvas(r, width, height) {
  30073. if (height === undefined) {
  30074. height = width;
  30075. }
  30076. var canvas = r.makeOffscreenCanvas(width, height);
  30077. var ctx = canvas.context = canvas.getContext('2d');
  30078. canvas.clear = function () {
  30079. return ctx.clearRect(0, 0, canvas.width, canvas.height);
  30080. };
  30081. canvas.clear();
  30082. return canvas;
  30083. }
  30084. /**
  30085. * Returns the current pan & zoom values, scaled by the pixel ratio.
  30086. */
  30087. function getEffectivePanZoom(r) {
  30088. var pixelRatio = r.pixelRatio;
  30089. var zoom = r.cy.zoom();
  30090. var pan = r.cy.pan();
  30091. return {
  30092. zoom: zoom * pixelRatio,
  30093. pan: {
  30094. x: pan.x * pixelRatio,
  30095. y: pan.y * pixelRatio
  30096. }
  30097. };
  30098. }
  30099. /**
  30100. * Returns the zoom value, scaled by the pixel ratio.
  30101. */
  30102. function getEffectiveZoom(r) {
  30103. var pixelRatio = r.pixelRatio;
  30104. var zoom = r.cy.zoom();
  30105. return zoom * pixelRatio;
  30106. }
  30107. function modelToRenderedPosition(r, pan, zoom, x, y) {
  30108. var rx = x * zoom + pan.x;
  30109. var ry = y * zoom + pan.y;
  30110. ry = Math.round(r.canvasHeight - ry); // adjust for webgl
  30111. return [rx, ry];
  30112. }
  30113. function isSimpleShape(node, renderTarget) {
  30114. // the actual shape is checked in ElementDrawingWebGL._getVertTypeForShape()
  30115. // no need to check it twice, this just checks other visual properties
  30116. if (renderTarget.picking) {
  30117. // We don't care about the border or background style for picking
  30118. return true;
  30119. } else {
  30120. if (node.pstyle('background-fill').value !== 'solid') return false;
  30121. if (node.pstyle('background-image').strValue !== 'none') return false;
  30122. if (node.pstyle('border-width').value === 0) return true;
  30123. if (node.pstyle('border-opacity').value === 0) return true;
  30124. // we have a border but it must be simple
  30125. if (node.pstyle('border-style').value !== 'solid') return false;
  30126. // TODO ignoring 'border-cap', 'border-join' and 'border-position' for now
  30127. return true;
  30128. }
  30129. }
  30130. function arrayEqual(a1, a2) {
  30131. if (a1.length !== a2.length) {
  30132. return false;
  30133. }
  30134. for (var i = 0; i < a1.length; i++) {
  30135. if (a1[i] !== a2[i]) {
  30136. return false;
  30137. }
  30138. }
  30139. return true;
  30140. }
  30141. /**
  30142. * Takes color & opacity style values and converts them to WebGL format.
  30143. * Alpha is premultiplied.
  30144. */
  30145. function toWebGLColor(color, opacity, outArray) {
  30146. var r = color[0] / 255;
  30147. var g = color[1] / 255;
  30148. var b = color[2] / 255;
  30149. var a = opacity;
  30150. var arr = outArray || new Array(4);
  30151. arr[0] = r * a;
  30152. arr[1] = g * a;
  30153. arr[2] = b * a;
  30154. arr[3] = a;
  30155. return arr;
  30156. }
  30157. function indexToVec4(index, outArray) {
  30158. var arr = outArray || new Array(4);
  30159. arr[0] = (index >> 0 & 0xFF) / 0xFF;
  30160. arr[1] = (index >> 8 & 0xFF) / 0xFF;
  30161. arr[2] = (index >> 16 & 0xFF) / 0xFF;
  30162. arr[3] = (index >> 24 & 0xFF) / 0xFF;
  30163. return arr;
  30164. }
  30165. function vec4ToIndex(vec4) {
  30166. return vec4[0] + (vec4[1] << 8) + (vec4[2] << 16) + (vec4[3] << 24);
  30167. }
  30168. function createTexture(gl, debugID) {
  30169. var texture = gl.createTexture();
  30170. texture.buffer = function (offscreenCanvas) {
  30171. gl.bindTexture(gl.TEXTURE_2D, texture);
  30172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  30173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  30174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  30175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  30176. // very important, this tells webgl to premultiply colors by the alpha channel
  30177. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
  30178. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offscreenCanvas);
  30179. gl.generateMipmap(gl.TEXTURE_2D);
  30180. gl.bindTexture(gl.TEXTURE_2D, null);
  30181. };
  30182. texture.deleteTexture = function () {
  30183. gl.deleteTexture(texture);
  30184. };
  30185. return texture;
  30186. }
  30187. function getTypeInfo(gl, glslType) {
  30188. switch (glslType) {
  30189. case 'float':
  30190. return [1, gl.FLOAT, 4];
  30191. case 'vec2':
  30192. return [2, gl.FLOAT, 4];
  30193. case 'vec3':
  30194. return [3, gl.FLOAT, 4];
  30195. case 'vec4':
  30196. return [4, gl.FLOAT, 4];
  30197. case 'int':
  30198. return [1, gl.INT, 4];
  30199. case 'ivec2':
  30200. return [2, gl.INT, 4];
  30201. }
  30202. }
  30203. function createTypedArray(gl, glType, dataOrSize) {
  30204. switch (glType) {
  30205. case gl.FLOAT:
  30206. return new Float32Array(dataOrSize);
  30207. case gl.INT:
  30208. return new Int32Array(dataOrSize);
  30209. }
  30210. }
  30211. function createTypedArrayView(gl, glType, array, stride, size, i) {
  30212. switch (glType) {
  30213. case gl.FLOAT:
  30214. return new Float32Array(array.buffer, i * stride, size);
  30215. case gl.INT:
  30216. return new Int32Array(array.buffer, i * stride, size);
  30217. }
  30218. }
  30219. /** @param {WebGLRenderingContext} gl */
  30220. function createBufferStaticDraw(gl, type, attributeLoc, dataArray) {
  30221. var _getTypeInfo = getTypeInfo(gl, type),
  30222. _getTypeInfo2 = _slicedToArray(_getTypeInfo, 2),
  30223. size = _getTypeInfo2[0],
  30224. glType = _getTypeInfo2[1];
  30225. var data = createTypedArray(gl, glType, dataArray);
  30226. var buffer = gl.createBuffer();
  30227. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30228. gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
  30229. if (glType === gl.FLOAT) {
  30230. gl.vertexAttribPointer(attributeLoc, size, glType, false, 0, 0);
  30231. } else if (glType === gl.INT) {
  30232. gl.vertexAttribIPointer(attributeLoc, size, glType, 0, 0);
  30233. }
  30234. gl.enableVertexAttribArray(attributeLoc);
  30235. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30236. return buffer;
  30237. }
  30238. /**
  30239. * Creates a float buffer with gl.DYNAMIC_DRAW.
  30240. * The returned buffer object contains functions to easily set instance data and buffer the data before a draw call.
  30241. * @param {WebGLRenderingContext} gl
  30242. */
  30243. function createBufferDynamicDraw(gl, instances, type, attributeLoc) {
  30244. var _getTypeInfo3 = getTypeInfo(gl, type),
  30245. _getTypeInfo4 = _slicedToArray(_getTypeInfo3, 3),
  30246. size = _getTypeInfo4[0],
  30247. glType = _getTypeInfo4[1],
  30248. bytes = _getTypeInfo4[2];
  30249. var dataArray = createTypedArray(gl, glType, instances * size);
  30250. var stride = size * bytes;
  30251. var buffer = gl.createBuffer();
  30252. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30253. gl.bufferData(gl.ARRAY_BUFFER, instances * stride, gl.DYNAMIC_DRAW);
  30254. gl.enableVertexAttribArray(attributeLoc);
  30255. if (glType === gl.FLOAT) {
  30256. gl.vertexAttribPointer(attributeLoc, size, glType, false, stride, 0);
  30257. } else if (glType === gl.INT) {
  30258. gl.vertexAttribIPointer(attributeLoc, size, glType, stride, 0);
  30259. }
  30260. gl.vertexAttribDivisor(attributeLoc, 1);
  30261. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30262. // use array views to set values directly into the buffer array
  30263. var views = new Array(instances);
  30264. for (var i = 0; i < instances; i++) {
  30265. views[i] = createTypedArrayView(gl, glType, dataArray, stride, size, i);
  30266. }
  30267. buffer.dataArray = dataArray;
  30268. buffer.stride = stride;
  30269. buffer.size = size;
  30270. buffer.getView = function (i) {
  30271. return views[i];
  30272. };
  30273. buffer.setPoint = function (i, x, y) {
  30274. var view = views[i];
  30275. view[0] = x;
  30276. view[1] = y;
  30277. };
  30278. buffer.bufferSubData = function (count) {
  30279. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30280. if (count) {
  30281. gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray, 0, count * size);
  30282. } else {
  30283. gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray);
  30284. }
  30285. };
  30286. return buffer;
  30287. }
  30288. /**
  30289. * Creates a buffer of 3x3 matrix data for use as attribute data.
  30290. * @param {WebGLRenderingContext} gl
  30291. */
  30292. function create3x3MatrixBufferDynamicDraw(gl, instances, attributeLoc) {
  30293. var matrixSize = 9; // 3x3 matrix
  30294. var matrixData = new Float32Array(instances * matrixSize);
  30295. // use matrix views to set values directly into the matrixData array
  30296. var matrixViews = new Array(instances);
  30297. for (var i = 0; i < instances; i++) {
  30298. var byteOffset = i * matrixSize * 4; // 4 bytes per float
  30299. matrixViews[i] = new Float32Array(matrixData.buffer, byteOffset, matrixSize); // array view
  30300. }
  30301. var buffer = gl.createBuffer();
  30302. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30303. gl.bufferData(gl.ARRAY_BUFFER, matrixData.byteLength, gl.DYNAMIC_DRAW);
  30304. // each row of the matrix needs to be a separate attribute
  30305. for (var _i = 0; _i < 3; _i++) {
  30306. var loc = attributeLoc + _i;
  30307. gl.enableVertexAttribArray(loc);
  30308. gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 3 * 12, _i * 12);
  30309. gl.vertexAttribDivisor(loc, 1);
  30310. }
  30311. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30312. buffer.getMatrixView = function (i) {
  30313. return matrixViews[i];
  30314. };
  30315. // TODO this is too slow, use getMatrixView and pass the view directly to the glmatrix library
  30316. buffer.setData = function (matrix, i) {
  30317. matrixViews[i].set(matrix, 0);
  30318. };
  30319. buffer.bufferSubData = function () {
  30320. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30321. gl.bufferSubData(gl.ARRAY_BUFFER, 0, matrixData);
  30322. };
  30323. return buffer;
  30324. }
  30325. /**
  30326. * Creates a Frame Buffer to use for offscreen rendering.
  30327. * @param {WebGLRenderingContext} gl
  30328. */
  30329. function createPickingFrameBuffer(gl) {
  30330. // Create and bind the framebuffer
  30331. var fb = gl.createFramebuffer();
  30332. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  30333. // Create a texture to render to
  30334. var targetTexture = gl.createTexture();
  30335. gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  30336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  30337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  30338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  30339. // attach the texture as the first color attachment
  30340. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);
  30341. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  30342. fb.setFramebufferAttachmentSizes = function (width, height) {
  30343. gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  30344. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  30345. };
  30346. return fb;
  30347. }
  30348. /**
  30349. * Common utilities
  30350. * @module glMatrix
  30351. */
  30352. // Configuration Constants
  30353. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  30354. if (!Math.hypot) Math.hypot = function () {
  30355. var y = 0,
  30356. i = arguments.length;
  30357. while (i--) {
  30358. y += arguments[i] * arguments[i];
  30359. }
  30360. return Math.sqrt(y);
  30361. };
  30362. /**
  30363. * 3x3 Matrix
  30364. * @module mat3
  30365. */
  30366. /**
  30367. * Creates a new identity mat3
  30368. *
  30369. * @returns {mat3} a new 3x3 matrix
  30370. */
  30371. function create() {
  30372. var out = new ARRAY_TYPE(9);
  30373. if (ARRAY_TYPE != Float32Array) {
  30374. out[1] = 0;
  30375. out[2] = 0;
  30376. out[3] = 0;
  30377. out[5] = 0;
  30378. out[6] = 0;
  30379. out[7] = 0;
  30380. }
  30381. out[0] = 1;
  30382. out[4] = 1;
  30383. out[8] = 1;
  30384. return out;
  30385. }
  30386. /**
  30387. * Set a mat3 to the identity matrix
  30388. *
  30389. * @param {mat3} out the receiving matrix
  30390. * @returns {mat3} out
  30391. */
  30392. function identity(out) {
  30393. out[0] = 1;
  30394. out[1] = 0;
  30395. out[2] = 0;
  30396. out[3] = 0;
  30397. out[4] = 1;
  30398. out[5] = 0;
  30399. out[6] = 0;
  30400. out[7] = 0;
  30401. out[8] = 1;
  30402. return out;
  30403. }
  30404. /**
  30405. * Multiplies two mat3's
  30406. *
  30407. * @param {mat3} out the receiving matrix
  30408. * @param {ReadonlyMat3} a the first operand
  30409. * @param {ReadonlyMat3} b the second operand
  30410. * @returns {mat3} out
  30411. */
  30412. function multiply(out, a, b) {
  30413. var a00 = a[0],
  30414. a01 = a[1],
  30415. a02 = a[2];
  30416. var a10 = a[3],
  30417. a11 = a[4],
  30418. a12 = a[5];
  30419. var a20 = a[6],
  30420. a21 = a[7],
  30421. a22 = a[8];
  30422. var b00 = b[0],
  30423. b01 = b[1],
  30424. b02 = b[2];
  30425. var b10 = b[3],
  30426. b11 = b[4],
  30427. b12 = b[5];
  30428. var b20 = b[6],
  30429. b21 = b[7],
  30430. b22 = b[8];
  30431. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  30432. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  30433. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  30434. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  30435. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  30436. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  30437. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  30438. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  30439. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  30440. return out;
  30441. }
  30442. /**
  30443. * Translate a mat3 by the given vector
  30444. *
  30445. * @param {mat3} out the receiving matrix
  30446. * @param {ReadonlyMat3} a the matrix to translate
  30447. * @param {ReadonlyVec2} v vector to translate by
  30448. * @returns {mat3} out
  30449. */
  30450. function translate(out, a, v) {
  30451. var a00 = a[0],
  30452. a01 = a[1],
  30453. a02 = a[2],
  30454. a10 = a[3],
  30455. a11 = a[4],
  30456. a12 = a[5],
  30457. a20 = a[6],
  30458. a21 = a[7],
  30459. a22 = a[8],
  30460. x = v[0],
  30461. y = v[1];
  30462. out[0] = a00;
  30463. out[1] = a01;
  30464. out[2] = a02;
  30465. out[3] = a10;
  30466. out[4] = a11;
  30467. out[5] = a12;
  30468. out[6] = x * a00 + y * a10 + a20;
  30469. out[7] = x * a01 + y * a11 + a21;
  30470. out[8] = x * a02 + y * a12 + a22;
  30471. return out;
  30472. }
  30473. /**
  30474. * Rotates a mat3 by the given angle
  30475. *
  30476. * @param {mat3} out the receiving matrix
  30477. * @param {ReadonlyMat3} a the matrix to rotate
  30478. * @param {Number} rad the angle to rotate the matrix by
  30479. * @returns {mat3} out
  30480. */
  30481. function rotate(out, a, rad) {
  30482. var a00 = a[0],
  30483. a01 = a[1],
  30484. a02 = a[2],
  30485. a10 = a[3],
  30486. a11 = a[4],
  30487. a12 = a[5],
  30488. a20 = a[6],
  30489. a21 = a[7],
  30490. a22 = a[8],
  30491. s = Math.sin(rad),
  30492. c = Math.cos(rad);
  30493. out[0] = c * a00 + s * a10;
  30494. out[1] = c * a01 + s * a11;
  30495. out[2] = c * a02 + s * a12;
  30496. out[3] = c * a10 - s * a00;
  30497. out[4] = c * a11 - s * a01;
  30498. out[5] = c * a12 - s * a02;
  30499. out[6] = a20;
  30500. out[7] = a21;
  30501. out[8] = a22;
  30502. return out;
  30503. }
  30504. /**
  30505. * Scales the mat3 by the dimensions in the given vec2
  30506. *
  30507. * @param {mat3} out the receiving matrix
  30508. * @param {ReadonlyMat3} a the matrix to rotate
  30509. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  30510. * @returns {mat3} out
  30511. **/
  30512. function scale(out, a, v) {
  30513. var x = v[0],
  30514. y = v[1];
  30515. out[0] = x * a[0];
  30516. out[1] = x * a[1];
  30517. out[2] = x * a[2];
  30518. out[3] = y * a[3];
  30519. out[4] = y * a[4];
  30520. out[5] = y * a[5];
  30521. out[6] = a[6];
  30522. out[7] = a[7];
  30523. out[8] = a[8];
  30524. return out;
  30525. }
  30526. /**
  30527. * Generates a 2D projection matrix with the given bounds
  30528. *
  30529. * @param {mat3} out mat3 frustum matrix will be written into
  30530. * @param {number} width Width of your gl context
  30531. * @param {number} height Height of gl context
  30532. * @returns {mat3} out
  30533. */
  30534. function projection(out, width, height) {
  30535. out[0] = 2 / width;
  30536. out[1] = 0;
  30537. out[2] = 0;
  30538. out[3] = 0;
  30539. out[4] = -2 / height;
  30540. out[5] = 0;
  30541. out[6] = -1;
  30542. out[7] = 1;
  30543. out[8] = 1;
  30544. return out;
  30545. }
  30546. // A "texture atlas" is a big canvas, and sections of it are used as textures for nodes/labels.
  30547. /**
  30548. * A single square texture atlas (also known as a "sprite sheet").
  30549. */
  30550. var Atlas = /*#__PURE__*/function () {
  30551. function Atlas(r, texSize, texRows, createTextureCanvas) {
  30552. _classCallCheck(this, Atlas);
  30553. this.debugID = Math.floor(Math.random() * 10000);
  30554. this.r = r;
  30555. this.texSize = texSize;
  30556. this.texRows = texRows;
  30557. this.texHeight = Math.floor(texSize / texRows);
  30558. this.enableWrapping = true; // hardcoded for now, can be made an option
  30559. this.locked = false; // once an atlas is locked it can no longer be drawn to
  30560. this.texture = null; // WebGLTexture object
  30561. this.needsBuffer = true;
  30562. // a "location" is an pointer into the atlas with a 'row' and 'x' fields
  30563. this.freePointer = {
  30564. x: 0,
  30565. row: 0
  30566. };
  30567. // map from the style key to the row/x where the texture starts
  30568. // if the texture wraps then there's a second location
  30569. this.keyToLocation = new Map(); // styleKey -> [ location, location ]
  30570. this.canvas = createTextureCanvas(r, texSize, texSize);
  30571. this.scratch = createTextureCanvas(r, texSize, this.texHeight, 'scratch');
  30572. }
  30573. return _createClass(Atlas, [{
  30574. key: "lock",
  30575. value: function lock() {
  30576. this.locked = true;
  30577. }
  30578. }, {
  30579. key: "getKeys",
  30580. value: function getKeys() {
  30581. return new Set(this.keyToLocation.keys());
  30582. }
  30583. }, {
  30584. key: "getScale",
  30585. value: function getScale(_ref) {
  30586. var w = _ref.w,
  30587. h = _ref.h;
  30588. var texHeight = this.texHeight,
  30589. maxTexWidth = this.texSize;
  30590. // try to fit to the height of a row
  30591. var scale = texHeight / h; // TODO what about pixelRatio?
  30592. var texW = w * scale;
  30593. var texH = h * scale;
  30594. // if the scaled width is too wide then scale to fit max width instead
  30595. if (texW > maxTexWidth) {
  30596. scale = maxTexWidth / w;
  30597. texW = w * scale;
  30598. texH = h * scale;
  30599. }
  30600. return {
  30601. scale: scale,
  30602. texW: texW,
  30603. texH: texH
  30604. };
  30605. }
  30606. }, {
  30607. key: "draw",
  30608. value: function draw(key, bb, doDrawing) {
  30609. var _this = this;
  30610. if (this.locked) throw new Error('can\'t draw, atlas is locked');
  30611. var texSize = this.texSize,
  30612. texRows = this.texRows,
  30613. texHeight = this.texHeight;
  30614. var _this$getScale = this.getScale(bb),
  30615. scale = _this$getScale.scale,
  30616. texW = _this$getScale.texW,
  30617. texH = _this$getScale.texH;
  30618. var drawAt = function drawAt(location, canvas) {
  30619. if (doDrawing && canvas) {
  30620. var context = canvas.context;
  30621. var x = location.x,
  30622. row = location.row;
  30623. var xOffset = x;
  30624. var yOffset = texHeight * row;
  30625. context.save();
  30626. context.translate(xOffset, yOffset);
  30627. context.scale(scale, scale);
  30628. doDrawing(context, bb);
  30629. context.restore();
  30630. }
  30631. };
  30632. var locations = [null, null];
  30633. var drawNormal = function drawNormal() {
  30634. // don't need to wrap, draw directly on the canvas
  30635. drawAt(_this.freePointer, _this.canvas);
  30636. locations[0] = {
  30637. x: _this.freePointer.x,
  30638. y: _this.freePointer.row * texHeight,
  30639. w: texW,
  30640. h: texH
  30641. };
  30642. locations[1] = {
  30643. // create a second location with a width of 0, for convenience
  30644. x: _this.freePointer.x + texW,
  30645. y: _this.freePointer.row * texHeight,
  30646. w: 0,
  30647. h: texH
  30648. };
  30649. // move the pointer to the end of the texture
  30650. _this.freePointer.x += texW;
  30651. if (_this.freePointer.x == texSize) {
  30652. _this.freePointer.x = 0;
  30653. _this.freePointer.row++;
  30654. }
  30655. };
  30656. var drawWrapped = function drawWrapped() {
  30657. var scratch = _this.scratch,
  30658. canvas = _this.canvas;
  30659. // Draw to the scratch canvas
  30660. scratch.clear();
  30661. drawAt({
  30662. x: 0,
  30663. row: 0
  30664. }, scratch);
  30665. var firstTexW = texSize - _this.freePointer.x;
  30666. var secondTexW = texW - firstTexW;
  30667. var h = texHeight;
  30668. {
  30669. // copy first part of scratch to the first texture
  30670. var dx = _this.freePointer.x;
  30671. var dy = _this.freePointer.row * texHeight;
  30672. var w = firstTexW;
  30673. canvas.context.drawImage(scratch, 0, 0, w, h, dx, dy, w, h);
  30674. locations[0] = {
  30675. x: dx,
  30676. y: dy,
  30677. w: w,
  30678. h: texH
  30679. };
  30680. }
  30681. {
  30682. // copy second part of scratch to the second texture
  30683. var sx = firstTexW;
  30684. var _dy = (_this.freePointer.row + 1) * texHeight;
  30685. var _w = secondTexW;
  30686. if (canvas) {
  30687. canvas.context.drawImage(scratch, sx, 0, _w, h, 0, _dy, _w, h);
  30688. }
  30689. locations[1] = {
  30690. x: 0,
  30691. y: _dy,
  30692. w: _w,
  30693. h: texH
  30694. };
  30695. }
  30696. _this.freePointer.x = secondTexW;
  30697. _this.freePointer.row++;
  30698. };
  30699. var moveToStartOfNextRow = function moveToStartOfNextRow() {
  30700. _this.freePointer.x = 0;
  30701. _this.freePointer.row++;
  30702. };
  30703. if (this.freePointer.x + texW <= texSize) {
  30704. // There's enough space in the current row
  30705. drawNormal();
  30706. } else if (this.freePointer.row >= texRows - 1) {
  30707. // Need to move to the next row, but there are no more rows, atlas is full.
  30708. return false;
  30709. } else if (this.freePointer.x === texSize) {
  30710. // happen to be right at end of current row
  30711. moveToStartOfNextRow();
  30712. drawNormal();
  30713. } else if (this.enableWrapping) {
  30714. // draw part of the texture to the end of the curent row, then wrap to the next row
  30715. drawWrapped();
  30716. } else {
  30717. // move to the start of the next row, then draw normally
  30718. moveToStartOfNextRow();
  30719. drawNormal();
  30720. }
  30721. this.keyToLocation.set(key, locations);
  30722. this.needsBuffer = true;
  30723. return locations;
  30724. }
  30725. }, {
  30726. key: "getOffsets",
  30727. value: function getOffsets(key) {
  30728. return this.keyToLocation.get(key);
  30729. }
  30730. }, {
  30731. key: "isEmpty",
  30732. value: function isEmpty() {
  30733. return this.freePointer.x === 0 && this.freePointer.row === 0;
  30734. }
  30735. }, {
  30736. key: "canFit",
  30737. value: function canFit(bb) {
  30738. if (this.locked) return false;
  30739. var texSize = this.texSize,
  30740. texRows = this.texRows;
  30741. var _this$getScale2 = this.getScale(bb),
  30742. texW = _this$getScale2.texW;
  30743. if (this.freePointer.x + texW > texSize) {
  30744. // need to wrap
  30745. return this.freePointer.row < texRows - 1; // return true if there's a row to wrap to
  30746. }
  30747. return true;
  30748. }
  30749. // called on every frame
  30750. }, {
  30751. key: "bufferIfNeeded",
  30752. value: function bufferIfNeeded(gl) {
  30753. if (!this.texture) {
  30754. this.texture = createTexture(gl, this.debugID);
  30755. }
  30756. if (this.needsBuffer) {
  30757. this.texture.buffer(this.canvas);
  30758. this.needsBuffer = false;
  30759. if (this.locked) {
  30760. this.canvas = null;
  30761. this.scratch = null;
  30762. }
  30763. }
  30764. }
  30765. }, {
  30766. key: "dispose",
  30767. value: function dispose() {
  30768. if (this.texture) {
  30769. this.texture.deleteTexture();
  30770. this.texture = null;
  30771. }
  30772. this.canvas = null;
  30773. this.scratch = null;
  30774. this.locked = true;
  30775. }
  30776. }]);
  30777. }();
  30778. /**
  30779. * A collection of texture atlases, all of the same "render type".
  30780. * ('node-body' is an example of a render type.)
  30781. * An AtlasCollection can also be notified when a texture is no longer needed,
  30782. * and it can garbage collect the unused textures.
  30783. */
  30784. var AtlasCollection = /*#__PURE__*/function () {
  30785. function AtlasCollection(r, texSize, texRows, createTextureCanvas) {
  30786. _classCallCheck(this, AtlasCollection);
  30787. this.r = r;
  30788. this.texSize = texSize;
  30789. this.texRows = texRows;
  30790. this.createTextureCanvas = createTextureCanvas;
  30791. this.atlases = [];
  30792. this.styleKeyToAtlas = new Map();
  30793. this.markedKeys = new Set(); // marked for garbage collection
  30794. }
  30795. return _createClass(AtlasCollection, [{
  30796. key: "getKeys",
  30797. value: function getKeys() {
  30798. return new Set(this.styleKeyToAtlas.keys());
  30799. }
  30800. }, {
  30801. key: "_createAtlas",
  30802. value: function _createAtlas() {
  30803. var r = this.r,
  30804. texSize = this.texSize,
  30805. texRows = this.texRows,
  30806. createTextureCanvas = this.createTextureCanvas;
  30807. return new Atlas(r, texSize, texRows, createTextureCanvas);
  30808. }
  30809. }, {
  30810. key: "_getScratchCanvas",
  30811. value: function _getScratchCanvas() {
  30812. if (!this.scratch) {
  30813. var r = this.r,
  30814. texSize = this.texSize,
  30815. texRows = this.texRows,
  30816. createTextureCanvas = this.createTextureCanvas;
  30817. var texHeight = Math.floor(texSize / texRows);
  30818. this.scratch = createTextureCanvas(r, texSize, texHeight, 'scratch');
  30819. }
  30820. return this.scratch;
  30821. }
  30822. }, {
  30823. key: "draw",
  30824. value: function draw(key, bb, doDrawing) {
  30825. var atlas = this.styleKeyToAtlas.get(key);
  30826. if (!atlas) {
  30827. // check for space at the end of the last atlas
  30828. atlas = this.atlases[this.atlases.length - 1];
  30829. if (!atlas || !atlas.canFit(bb)) {
  30830. if (atlas) atlas.lock();
  30831. // create a new atlas
  30832. atlas = this._createAtlas();
  30833. this.atlases.push(atlas);
  30834. }
  30835. atlas.draw(key, bb, doDrawing);
  30836. this.styleKeyToAtlas.set(key, atlas);
  30837. }
  30838. return atlas;
  30839. }
  30840. }, {
  30841. key: "getAtlas",
  30842. value: function getAtlas(key) {
  30843. return this.styleKeyToAtlas.get(key);
  30844. }
  30845. }, {
  30846. key: "hasAtlas",
  30847. value: function hasAtlas(key) {
  30848. return this.styleKeyToAtlas.has(key);
  30849. }
  30850. }, {
  30851. key: "markKeyForGC",
  30852. value: function markKeyForGC(key) {
  30853. this.markedKeys.add(key);
  30854. }
  30855. }, {
  30856. key: "gc",
  30857. value: function gc() {
  30858. var _this2 = this;
  30859. var markedKeys = this.markedKeys;
  30860. if (markedKeys.size === 0) {
  30861. console.log('nothing to garbage collect');
  30862. return;
  30863. }
  30864. var newAtlases = [];
  30865. var newStyleKeyToAtlas = new Map();
  30866. var newAtlas = null;
  30867. var _iterator = _createForOfIteratorHelper(this.atlases),
  30868. _step;
  30869. try {
  30870. var _loop = function _loop() {
  30871. var atlas = _step.value;
  30872. var keys = atlas.getKeys();
  30873. var keysToCollect = intersection(markedKeys, keys);
  30874. if (keysToCollect.size === 0) {
  30875. // this atlas can still be used
  30876. newAtlases.push(atlas);
  30877. keys.forEach(function (k) {
  30878. return newStyleKeyToAtlas.set(k, atlas);
  30879. });
  30880. return 1; // continue
  30881. }
  30882. if (!newAtlas) {
  30883. newAtlas = _this2._createAtlas();
  30884. newAtlases.push(newAtlas);
  30885. }
  30886. var _iterator2 = _createForOfIteratorHelper(keys),
  30887. _step2;
  30888. try {
  30889. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  30890. var key = _step2.value;
  30891. if (!keysToCollect.has(key)) {
  30892. var _atlas$getOffsets = atlas.getOffsets(key),
  30893. _atlas$getOffsets2 = _slicedToArray(_atlas$getOffsets, 2),
  30894. s1 = _atlas$getOffsets2[0],
  30895. s2 = _atlas$getOffsets2[1];
  30896. if (!newAtlas.canFit({
  30897. w: s1.w + s2.w,
  30898. h: s1.h
  30899. })) {
  30900. newAtlas.lock();
  30901. newAtlas = _this2._createAtlas();
  30902. newAtlases.push(newAtlas);
  30903. }
  30904. if (atlas.canvas) {
  30905. // if the texture can't be copied then it will have to be redrawn on the next frame
  30906. _this2._copyTextureToNewAtlas(key, atlas, newAtlas);
  30907. newStyleKeyToAtlas.set(key, newAtlas);
  30908. }
  30909. }
  30910. }
  30911. } catch (err) {
  30912. _iterator2.e(err);
  30913. } finally {
  30914. _iterator2.f();
  30915. }
  30916. atlas.dispose();
  30917. };
  30918. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  30919. if (_loop()) continue;
  30920. }
  30921. } catch (err) {
  30922. _iterator.e(err);
  30923. } finally {
  30924. _iterator.f();
  30925. }
  30926. this.atlases = newAtlases;
  30927. this.styleKeyToAtlas = newStyleKeyToAtlas;
  30928. this.markedKeys = new Set();
  30929. }
  30930. }, {
  30931. key: "_copyTextureToNewAtlas",
  30932. value: function _copyTextureToNewAtlas(key, oldAtlas, newAtlas) {
  30933. var _oldAtlas$getOffsets = oldAtlas.getOffsets(key),
  30934. _oldAtlas$getOffsets2 = _slicedToArray(_oldAtlas$getOffsets, 2),
  30935. s1 = _oldAtlas$getOffsets2[0],
  30936. s2 = _oldAtlas$getOffsets2[1];
  30937. if (s2.w === 0) {
  30938. // the texture does not wrap, draw directly to new atlas
  30939. newAtlas.draw(key, s1, function (context) {
  30940. context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
  30941. });
  30942. } else {
  30943. // the texture wraps, first draw both parts to a scratch canvas
  30944. var scratch = this._getScratchCanvas();
  30945. scratch.clear();
  30946. scratch.context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
  30947. scratch.context.drawImage(oldAtlas.canvas, s2.x, s2.y, s2.w, s2.h, s1.w, 0, s2.w, s2.h);
  30948. // now draw the scratch to the new atlas
  30949. var w = s1.w + s2.w;
  30950. var h = s1.h;
  30951. newAtlas.draw(key, {
  30952. w: w,
  30953. h: h
  30954. }, function (context) {
  30955. context.drawImage(scratch, 0, 0, w, h, 0, 0, w, h // the destination context has already been translated to the correct position
  30956. );
  30957. });
  30958. }
  30959. }
  30960. }, {
  30961. key: "getCounts",
  30962. value: function getCounts() {
  30963. return {
  30964. keyCount: this.styleKeyToAtlas.size,
  30965. atlasCount: new Set(this.styleKeyToAtlas.values()).size
  30966. };
  30967. }
  30968. }]);
  30969. }();
  30970. function intersection(set1, set2) {
  30971. // TODO why no Set.intersection in node 16???
  30972. if (set1.intersection) return set1.intersection(set2);else return new Set(_toConsumableArray(set1).filter(function (x) {
  30973. return set2.has(x);
  30974. }));
  30975. }
  30976. /**
  30977. * Used to manage batches of Atlases for drawing nodes and labels.
  30978. * Supports different types of AtlasCollections for different render types,
  30979. * for example 'node-body' and 'node-label' would be different render types.
  30980. * Render types are kept separate because they will likely need to be garbage collected
  30981. * separately and its not entierly guaranteed that their style keys won't collide.
  30982. */
  30983. var AtlasManager = /*#__PURE__*/function () {
  30984. function AtlasManager(r, globalOptions) {
  30985. _classCallCheck(this, AtlasManager);
  30986. this.r = r;
  30987. this.globalOptions = globalOptions;
  30988. this.atlasSize = globalOptions.webglTexSize;
  30989. this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
  30990. this.renderTypes = new Map(); // renderType:string -> renderTypeOptions
  30991. this.collections = new Map(); // collectionName:string -> AtlasCollection
  30992. this.typeAndIdToKey = new Map(); // [renderType,id] => Array<style key>
  30993. }
  30994. return _createClass(AtlasManager, [{
  30995. key: "getAtlasSize",
  30996. value: function getAtlasSize() {
  30997. return this.atlasSize;
  30998. }
  30999. }, {
  31000. key: "addAtlasCollection",
  31001. value: function addAtlasCollection(collectionName, atlasCollectionOptions) {
  31002. var _this$globalOptions = this.globalOptions,
  31003. webglTexSize = _this$globalOptions.webglTexSize,
  31004. createTextureCanvas = _this$globalOptions.createTextureCanvas;
  31005. var texRows = atlasCollectionOptions.texRows;
  31006. var cachedCreateTextureCanvas = this._cacheScratchCanvas(createTextureCanvas);
  31007. var atlasCollection = new AtlasCollection(this.r, webglTexSize, texRows, cachedCreateTextureCanvas);
  31008. this.collections.set(collectionName, atlasCollection);
  31009. }
  31010. }, {
  31011. key: "addRenderType",
  31012. value: function addRenderType(type, renderTypeOptions) {
  31013. var collection = renderTypeOptions.collection;
  31014. if (!this.collections.has(collection)) throw new Error("invalid atlas collection name '".concat(collection, "'"));
  31015. var atlasCollection = this.collections.get(collection);
  31016. var opts = extend({
  31017. type: type,
  31018. atlasCollection: atlasCollection
  31019. }, renderTypeOptions);
  31020. this.renderTypes.set(type, opts);
  31021. }
  31022. }, {
  31023. key: "getRenderTypeOpts",
  31024. value: function getRenderTypeOpts(type) {
  31025. return this.renderTypes.get(type);
  31026. }
  31027. }, {
  31028. key: "getAtlasCollection",
  31029. value: function getAtlasCollection(name) {
  31030. return this.collections.get(name);
  31031. }
  31032. }, {
  31033. key: "_cacheScratchCanvas",
  31034. value: function _cacheScratchCanvas(createTextureCanvas) {
  31035. // all scratch canvases for the same render type will have the same width and height (ie webglTexRows option)
  31036. // but we'll keep track of the width and height just to be safe
  31037. var prevW = -1;
  31038. var prevH = -1;
  31039. var scratchCanvas = null;
  31040. return function (r, w, h, scratch) {
  31041. if (scratch) {
  31042. if (!scratchCanvas || w != prevW || h != prevH) {
  31043. prevW = w;
  31044. prevH = h;
  31045. scratchCanvas = createTextureCanvas(r, w, h);
  31046. }
  31047. return scratchCanvas;
  31048. } else {
  31049. return createTextureCanvas(r, w, h);
  31050. }
  31051. };
  31052. }
  31053. }, {
  31054. key: "_key",
  31055. value: function _key(renderType, id) {
  31056. return "".concat(renderType, "-").concat(id); // TODO not very efficient
  31057. }
  31058. /** Marks textues associated with the element for garbage collection. */
  31059. }, {
  31060. key: "invalidate",
  31061. value: function invalidate(eles) {
  31062. var _this3 = this;
  31063. var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  31064. _ref2$forceRedraw = _ref2.forceRedraw,
  31065. forceRedraw = _ref2$forceRedraw === undefined ? false : _ref2$forceRedraw,
  31066. _ref2$filterEle = _ref2.filterEle,
  31067. filterEle = _ref2$filterEle === undefined ? function () {
  31068. return true;
  31069. } : _ref2$filterEle,
  31070. _ref2$filterType = _ref2.filterType,
  31071. filterType = _ref2$filterType === undefined ? function () {
  31072. return true;
  31073. } : _ref2$filterType;
  31074. var needGC = false;
  31075. var runGCNow = false;
  31076. var _iterator3 = _createForOfIteratorHelper(eles),
  31077. _step3;
  31078. try {
  31079. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  31080. var ele = _step3.value;
  31081. if (filterEle(ele)) {
  31082. var _iterator4 = _createForOfIteratorHelper(this.renderTypes.values()),
  31083. _step4;
  31084. try {
  31085. var _loop2 = function _loop2() {
  31086. var opts = _step4.value;
  31087. var renderType = opts.type;
  31088. if (filterType(renderType)) {
  31089. var atlasCollection = _this3.collections.get(opts.collection);
  31090. var key = opts.getKey(ele);
  31091. var keyArray = Array.isArray(key) ? key : [key];
  31092. // when a node's background image finishes loading, the style key doesn't change but still needs to be redrawn
  31093. if (forceRedraw) {
  31094. keyArray.forEach(function (key) {
  31095. return atlasCollection.markKeyForGC(key);
  31096. });
  31097. runGCNow = true; // run GC to remove the old texture right now, that way we don't need to remember for the next gc
  31098. } else {
  31099. var id = opts.getID ? opts.getID(ele) : ele.id();
  31100. var mapKey = _this3._key(renderType, id);
  31101. var oldKeyArray = _this3.typeAndIdToKey.get(mapKey);
  31102. if (oldKeyArray !== undefined && !arrayEqual(keyArray, oldKeyArray)) {
  31103. // conservative approach, if any of the keys don't match then throw them all away
  31104. needGC = true;
  31105. _this3.typeAndIdToKey["delete"](mapKey);
  31106. oldKeyArray.forEach(function (oldKey) {
  31107. return atlasCollection.markKeyForGC(oldKey);
  31108. });
  31109. }
  31110. }
  31111. }
  31112. };
  31113. for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
  31114. _loop2();
  31115. }
  31116. } catch (err) {
  31117. _iterator4.e(err);
  31118. } finally {
  31119. _iterator4.f();
  31120. }
  31121. }
  31122. }
  31123. } catch (err) {
  31124. _iterator3.e(err);
  31125. } finally {
  31126. _iterator3.f();
  31127. }
  31128. if (runGCNow) {
  31129. this.gc();
  31130. needGC = false;
  31131. }
  31132. return needGC;
  31133. }
  31134. /** Garbage collect */
  31135. }, {
  31136. key: "gc",
  31137. value: function gc() {
  31138. var _iterator5 = _createForOfIteratorHelper(this.collections.values()),
  31139. _step5;
  31140. try {
  31141. for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
  31142. var collection = _step5.value;
  31143. collection.gc();
  31144. }
  31145. } catch (err) {
  31146. _iterator5.e(err);
  31147. } finally {
  31148. _iterator5.f();
  31149. }
  31150. }
  31151. }, {
  31152. key: "getOrCreateAtlas",
  31153. value: function getOrCreateAtlas(ele, type, bb, styleKey) {
  31154. // styleKey is not an array here
  31155. var opts = this.renderTypes.get(type);
  31156. var atlasCollection = this.collections.get(opts.collection);
  31157. // draws the texture only if needed
  31158. var drawn = false;
  31159. var atlas = atlasCollection.draw(styleKey, bb, function (context) {
  31160. if (opts.drawClipped) {
  31161. context.save();
  31162. context.beginPath();
  31163. context.rect(0, 0, bb.w, bb.h);
  31164. context.clip();
  31165. opts.drawElement(context, ele, bb, true, true);
  31166. context.restore();
  31167. } else {
  31168. opts.drawElement(context, ele, bb, true, true);
  31169. }
  31170. drawn = true;
  31171. });
  31172. if (drawn) {
  31173. var id = opts.getID ? opts.getID(ele) : ele.id(); // for testing
  31174. var mapKey = this._key(type, id);
  31175. if (this.typeAndIdToKey.has(mapKey)) {
  31176. this.typeAndIdToKey.get(mapKey).push(styleKey);
  31177. } else {
  31178. this.typeAndIdToKey.set(mapKey, [styleKey]);
  31179. }
  31180. }
  31181. return atlas;
  31182. }
  31183. }, {
  31184. key: "getAtlasInfo",
  31185. value: function getAtlasInfo(ele, type) {
  31186. var _this4 = this;
  31187. var opts = this.renderTypes.get(type);
  31188. var key = opts.getKey(ele);
  31189. var keyArray = Array.isArray(key) ? key : [key];
  31190. return keyArray.map(function (styleKey) {
  31191. var bb = opts.getBoundingBox(ele, styleKey); // pass the key back to the getBoundingBox method
  31192. var atlas = _this4.getOrCreateAtlas(ele, type, bb, styleKey);
  31193. var _atlas$getOffsets3 = atlas.getOffsets(styleKey),
  31194. _atlas$getOffsets4 = _slicedToArray(_atlas$getOffsets3, 2),
  31195. tex1 = _atlas$getOffsets4[0],
  31196. tex2 = _atlas$getOffsets4[1];
  31197. return {
  31198. atlas: atlas,
  31199. tex: tex1,
  31200. tex1: tex1,
  31201. tex2: tex2,
  31202. bb: bb
  31203. };
  31204. });
  31205. }
  31206. }, {
  31207. key: "getDebugInfo",
  31208. value: function getDebugInfo() {
  31209. var debugInfo = [];
  31210. var _iterator6 = _createForOfIteratorHelper(this.collections),
  31211. _step6;
  31212. try {
  31213. for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
  31214. var _step6$value = _slicedToArray(_step6.value, 2),
  31215. name = _step6$value[0],
  31216. collection = _step6$value[1];
  31217. var _collection$getCounts = collection.getCounts(),
  31218. keyCount = _collection$getCounts.keyCount,
  31219. atlasCount = _collection$getCounts.atlasCount;
  31220. debugInfo.push({
  31221. type: name,
  31222. keyCount: keyCount,
  31223. atlasCount: atlasCount
  31224. });
  31225. }
  31226. } catch (err) {
  31227. _iterator6.e(err);
  31228. } finally {
  31229. _iterator6.f();
  31230. }
  31231. return debugInfo;
  31232. }
  31233. }]);
  31234. }();
  31235. var AtlasBatchManager = /*#__PURE__*/function () {
  31236. function AtlasBatchManager(globalOptions) {
  31237. _classCallCheck(this, AtlasBatchManager);
  31238. this.globalOptions = globalOptions;
  31239. this.atlasSize = globalOptions.webglTexSize;
  31240. this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
  31241. this.batchAtlases = [];
  31242. }
  31243. return _createClass(AtlasBatchManager, [{
  31244. key: "getMaxAtlasesPerBatch",
  31245. value: function getMaxAtlasesPerBatch() {
  31246. return this.maxAtlasesPerBatch;
  31247. }
  31248. }, {
  31249. key: "getAtlasSize",
  31250. value: function getAtlasSize() {
  31251. return this.atlasSize;
  31252. }
  31253. }, {
  31254. key: "getIndexArray",
  31255. value: function getIndexArray() {
  31256. return Array.from({
  31257. length: this.maxAtlasesPerBatch
  31258. }, function (v, i) {
  31259. return i;
  31260. });
  31261. }
  31262. }, {
  31263. key: "startBatch",
  31264. value: function startBatch() {
  31265. this.batchAtlases = [];
  31266. }
  31267. }, {
  31268. key: "getAtlasCount",
  31269. value: function getAtlasCount() {
  31270. return this.batchAtlases.length;
  31271. }
  31272. }, {
  31273. key: "getAtlases",
  31274. value: function getAtlases() {
  31275. return this.batchAtlases;
  31276. }
  31277. }, {
  31278. key: "canAddToCurrentBatch",
  31279. value: function canAddToCurrentBatch(atlas) {
  31280. if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
  31281. return this.batchAtlases.includes(atlas);
  31282. }
  31283. return true; // not full
  31284. }
  31285. }, {
  31286. key: "getAtlasIndexForBatch",
  31287. value: function getAtlasIndexForBatch(atlas) {
  31288. var atlasID = this.batchAtlases.indexOf(atlas);
  31289. if (atlasID < 0) {
  31290. if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
  31291. throw new Error('cannot add more atlases to batch');
  31292. }
  31293. this.batchAtlases.push(atlas);
  31294. atlasID = this.batchAtlases.length - 1;
  31295. }
  31296. return atlasID;
  31297. }
  31298. }]);
  31299. }();
  31300. // Fragment shader functions to calculate signed distance
  31301. // https://iquilezles.org/articles/distfunctions2d/
  31302. // ellipse: https://www.shadertoy.com/view/4lsXDN
  31303. /**
  31304. * param p - point
  31305. * float r - circle radius, eg 0.5 for unit circle
  31306. */
  31307. var circleSD = "\n float circleSD(vec2 p, float r) {\n return distance(vec2(0), p) - r; // signed distance\n }\n";
  31308. /**
  31309. * param p - point
  31310. * param b - b.x = half width, b.y = half height
  31311. */
  31312. var rectangleSD = "\n float rectangleSD(vec2 p, vec2 b) {\n vec2 d = abs(p)-b;\n return distance(vec2(0),max(d,0.0)) + min(max(d.x,d.y),0.0);\n }\n";
  31313. /**
  31314. * param p - point
  31315. * param b - b.x = half width, b.y = half height
  31316. * param cr - vector of corner radiuses
  31317. */
  31318. var roundRectangleSD = "\n float roundRectangleSD(vec2 p, vec2 b, vec4 cr) {\n cr.xy = (p.x > 0.0) ? cr.xy : cr.zw;\n cr.x = (p.y > 0.0) ? cr.x : cr.y;\n vec2 q = abs(p) - b + cr.x;\n return min(max(q.x, q.y), 0.0) + distance(vec2(0), max(q, 0.0)) - cr.x;\n }\n";
  31319. /**
  31320. * param p - point
  31321. * param ab - a.x = horizontal radius, a.y = vertical radius
  31322. */
  31323. var ellipseSD = "\n float ellipseSD(vec2 p, vec2 ab) {\n p = abs( p ); // symmetry\n\n // find root with Newton solver\n vec2 q = ab*(p-ab);\n float w = (q.x<q.y)? 1.570796327 : 0.0;\n for( int i=0; i<5; i++ ) {\n vec2 cs = vec2(cos(w),sin(w));\n vec2 u = ab*vec2( cs.x,cs.y);\n vec2 v = ab*vec2(-cs.y,cs.x);\n w = w + dot(p-u,v)/(dot(p-u,u)+dot(v,v));\n }\n \n // compute final point and distance\n float d = length(p-ab*vec2(cos(w),sin(w)));\n \n // return signed distance\n return (dot(p/ab,p/ab)>1.0) ? d : -d;\n }\n";
  31324. /**
  31325. * Two render modes. Each mode has its own shader program. They are almost identical, the main difference is the output.
  31326. * SCREEN: output pixel colors to the screen
  31327. * PICKING: output z-order index to an offscreen framebuffer, used to detect what's under the mouse cursor
  31328. */
  31329. var RENDER_TARGET = {
  31330. SCREEN: {
  31331. name: 'screen',
  31332. screen: true
  31333. },
  31334. PICKING: {
  31335. name: 'picking',
  31336. picking: true
  31337. }
  31338. };
  31339. /**
  31340. * Special handing for label textures in PICKING mode. See issue #3337.
  31341. */
  31342. var TEX_PICKING_MODE = {
  31343. // render the texture just like in RENDER_TARGET.SCREEN mode
  31344. IGNORE: 1,
  31345. // don't render the texture at all
  31346. USE_BB: 2 // render the bounding box as an opaque rectangle
  31347. };
  31348. // Vertex types.
  31349. // Used directly in the shaders so must be numeric.
  31350. // There is only one shader program used for an entire frame that renders all types of elements.
  31351. // There are if-else blocks in the shaders that do different things depending on the vertex type.
  31352. // This allows all elements to be rendererd in large batches without switching shader programs.
  31353. var TEXTURE = 0;
  31354. var EDGE_STRAIGHT = 1;
  31355. var EDGE_CURVE_SEGMENT = 2;
  31356. var EDGE_ARROW = 3;
  31357. var RECTANGLE = 4;
  31358. var ROUND_RECTANGLE = 5;
  31359. var BOTTOM_ROUND_RECTANGLE = 6;
  31360. var ELLIPSE = 7;
  31361. var ElementDrawingWebGL = /*#__PURE__*/function () {
  31362. /**
  31363. * @param {WebGLRenderingContext} gl
  31364. */
  31365. function ElementDrawingWebGL(r, gl, opts) {
  31366. _classCallCheck(this, ElementDrawingWebGL);
  31367. this.r = r; // reference to the canvas renderer
  31368. this.gl = gl;
  31369. this.maxInstances = opts.webglBatchSize;
  31370. this.atlasSize = opts.webglTexSize;
  31371. this.bgColor = opts.bgColor;
  31372. this.debug = opts.webglDebug;
  31373. this.batchDebugInfo = [];
  31374. opts.enableWrapping = true;
  31375. opts.createTextureCanvas = createTextureCanvas; // Unit tests mock this
  31376. this.atlasManager = new AtlasManager(r, opts);
  31377. this.batchManager = new AtlasBatchManager(opts);
  31378. this.simpleShapeOptions = new Map();
  31379. this.program = this._createShaderProgram(RENDER_TARGET.SCREEN);
  31380. this.pickingProgram = this._createShaderProgram(RENDER_TARGET.PICKING);
  31381. this.vao = this._createVAO();
  31382. }
  31383. /**
  31384. * @param { string } collectionName
  31385. * @param {{ texRows: number }} opts
  31386. */
  31387. return _createClass(ElementDrawingWebGL, [{
  31388. key: "addAtlasCollection",
  31389. value: function addAtlasCollection(collectionName, opts) {
  31390. this.atlasManager.addAtlasCollection(collectionName, opts);
  31391. }
  31392. /**
  31393. * @typedef { Object } TextureRenderTypeOpts
  31394. * @property { string } collection - name of atlas collection to render textures to
  31395. * @property { function } getKey - returns the "style key" for an element, may be a single value or an array for multi-line lables
  31396. * @property { function } drawElement - uses a canvas renderer to draw the element to the texture atlas
  31397. * @property { boolean } drawClipped - if true the context will be clipped to the bounding box before drawElement() is called, may affect performance
  31398. * @property { function } getBoundingBox - returns the bounding box for an element
  31399. * @property { function } getRotation
  31400. * @property { function } getRotationPoint
  31401. * @property { function } getRotationOffset
  31402. * @property { function } isVisible - an extra check for visibility in addition to ele.visible()
  31403. * @property { function } getTexPickingMode - returns a value from the TEX_PICKING_MODE enum
  31404. */
  31405. /**
  31406. * @param { string } typeName
  31407. * @param { TextureRenderTypeOpts } opts
  31408. */
  31409. }, {
  31410. key: "addTextureAtlasRenderType",
  31411. value: function addTextureAtlasRenderType(typeName, opts) {
  31412. this.atlasManager.addRenderType(typeName, opts);
  31413. }
  31414. /**
  31415. * @typedef { Object } SimpleShapeRenderTypeOpts
  31416. * @property { function } getBoundingBox - returns the bounding box for an element
  31417. * @property { function } isVisible - this is an extra check for visibility in addition to ele.visible()
  31418. * @property { function } isSimple - check if element is a simple shape, or if it needs to fall back to texture rendering
  31419. * @property { ShapeVisualProperties } shapeProps
  31420. */
  31421. /**
  31422. * @typedef { Object } ShapeVisualProperties
  31423. * @property { string } shape
  31424. * @property { string } color
  31425. * @property { string } opacity
  31426. * @property { string } padding
  31427. * @property { string } radius
  31428. * @property { boolean } border
  31429. */
  31430. /**
  31431. * @param { string } typeName
  31432. * @param { SimpleShapeRenderTypeOpts } opts
  31433. */
  31434. }, {
  31435. key: "addSimpleShapeRenderType",
  31436. value: function addSimpleShapeRenderType(typeName, opts) {
  31437. this.simpleShapeOptions.set(typeName, opts);
  31438. }
  31439. /**
  31440. * Inform the atlasManager when element style keys may have changed.
  31441. * The atlasManager can then mark unused textures for "garbage collection".
  31442. */
  31443. }, {
  31444. key: "invalidate",
  31445. value: function invalidate(eles) {
  31446. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  31447. type = _ref.type;
  31448. var atlasManager = this.atlasManager;
  31449. if (type) {
  31450. return atlasManager.invalidate(eles, {
  31451. filterType: function filterType(t) {
  31452. return t === type;
  31453. },
  31454. forceRedraw: true
  31455. });
  31456. } else {
  31457. return atlasManager.invalidate(eles);
  31458. }
  31459. }
  31460. /**
  31461. * Run texture garbage collection.
  31462. */
  31463. }, {
  31464. key: "gc",
  31465. value: function gc() {
  31466. this.atlasManager.gc();
  31467. }
  31468. }, {
  31469. key: "_createShaderProgram",
  31470. value: function _createShaderProgram(renderTarget) {
  31471. var gl = this.gl;
  31472. var vertexShaderSource = "#version 300 es\n precision highp float;\n\n uniform mat3 uPanZoomMatrix;\n uniform int uAtlasSize;\n \n // instanced\n in vec2 aPosition; // a vertex from the unit square\n \n in mat3 aTransform; // used to transform verticies, eg into a bounding box\n in int aVertType; // the type of thing we are rendering\n\n // the z-index that is output when using picking mode\n in vec4 aIndex;\n \n // For textures\n in int aAtlasId; // which shader unit/atlas to use\n in vec4 aTex; // x/y/w/h of texture in atlas\n\n // for edges\n in vec4 aPointAPointB;\n in vec4 aPointCPointD;\n in vec2 aLineWidth; // also used for node border width\n\n // simple shapes\n in vec4 aCornerRadius; // for round-rectangle [top-right, bottom-right, top-left, bottom-left]\n in vec4 aColor; // also used for edges\n in vec4 aBorderColor; // aLineWidth is used for border width\n\n // output values passed to the fragment shader\n out vec2 vTexCoord;\n out vec4 vColor;\n out vec2 vPosition;\n // flat values are not interpolated\n flat out int vAtlasId; \n flat out int vVertType;\n flat out vec2 vTopRight;\n flat out vec2 vBotLeft;\n flat out vec4 vCornerRadius;\n flat out vec4 vBorderColor;\n flat out vec2 vBorderWidth;\n flat out vec4 vIndex;\n \n void main(void) {\n int vid = gl_VertexID;\n vec2 position = aPosition; // TODO make this a vec3, simplifies some code below\n\n if(aVertType == ".concat(TEXTURE, ") {\n float texX = aTex.x; // texture coordinates\n float texY = aTex.y;\n float texW = aTex.z;\n float texH = aTex.w;\n\n if(vid == 1 || vid == 2 || vid == 4) {\n texX += texW;\n }\n if(vid == 2 || vid == 4 || vid == 5) {\n texY += texH;\n }\n\n float d = float(uAtlasSize);\n vTexCoord = vec2(texX / d, texY / d); // tex coords must be between 0 and 1\n\n gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\n }\n else if(aVertType == ").concat(RECTANGLE, " || aVertType == ").concat(ELLIPSE, " \n || aVertType == ").concat(ROUND_RECTANGLE, " || aVertType == ").concat(BOTTOM_ROUND_RECTANGLE, ") { // simple shapes\n\n // the bounding box is needed by the fragment shader\n vBotLeft = (aTransform * vec3(0, 0, 1)).xy; // flat\n vTopRight = (aTransform * vec3(1, 1, 1)).xy; // flat\n vPosition = (aTransform * vec3(position, 1)).xy; // will be interpolated\n\n // calculations are done in the fragment shader, just pass these along\n vColor = aColor;\n vCornerRadius = aCornerRadius;\n vBorderColor = aBorderColor;\n vBorderWidth = aLineWidth;\n\n gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\n }\n else if(aVertType == ").concat(EDGE_STRAIGHT, ") {\n vec2 source = aPointAPointB.xy;\n vec2 target = aPointAPointB.zw;\n\n // adjust the geometry so that the line is centered on the edge\n position.y = position.y - 0.5;\n\n // stretch the unit square into a long skinny rectangle\n vec2 xBasis = target - source;\n vec2 yBasis = normalize(vec2(-xBasis.y, xBasis.x));\n vec2 point = source + xBasis * position.x + yBasis * aLineWidth[0] * position.y;\n\n gl_Position = vec4(uPanZoomMatrix * vec3(point, 1.0), 1.0);\n vColor = aColor;\n } \n else if(aVertType == ").concat(EDGE_CURVE_SEGMENT, ") {\n vec2 pointA = aPointAPointB.xy;\n vec2 pointB = aPointAPointB.zw;\n vec2 pointC = aPointCPointD.xy;\n vec2 pointD = aPointCPointD.zw;\n\n // adjust the geometry so that the line is centered on the edge\n position.y = position.y - 0.5;\n\n vec2 p0, p1, p2, pos;\n if(position.x == 0.0) { // The left side of the unit square\n p0 = pointA;\n p1 = pointB;\n p2 = pointC;\n pos = position;\n } else { // The right side of the unit square, use same approach but flip the geometry upside down\n p0 = pointD;\n p1 = pointC;\n p2 = pointB;\n pos = vec2(0.0, -position.y);\n }\n\n vec2 p01 = p1 - p0;\n vec2 p12 = p2 - p1;\n vec2 p21 = p1 - p2;\n\n // Find the normal vector.\n vec2 tangent = normalize(normalize(p12) + normalize(p01));\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n // Find the vector perpendicular to p0 -> p1.\n vec2 p01Norm = normalize(vec2(-p01.y, p01.x));\n\n // Determine the bend direction.\n float sigma = sign(dot(p01 + p21, normal));\n float width = aLineWidth[0];\n\n if(sign(pos.y) == -sigma) {\n // This is an intersecting vertex. Adjust the position so that there's no overlap.\n vec2 point = 0.5 * width * normal * -sigma / dot(normal, p01Norm);\n gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0);\n } else {\n // This is a non-intersecting vertex. Treat it like a mitre join.\n vec2 point = 0.5 * width * normal * sigma * dot(normal, p01Norm);\n gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0);\n }\n\n vColor = aColor;\n } \n else if(aVertType == ").concat(EDGE_ARROW, " && vid < 3) {\n // massage the first triangle into an edge arrow\n if(vid == 0)\n position = vec2(-0.15, -0.3);\n if(vid == 1)\n position = vec2( 0.0, 0.0);\n if(vid == 2)\n position = vec2( 0.15, -0.3);\n\n gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0);\n vColor = aColor;\n }\n else {\n gl_Position = vec4(2.0, 0.0, 0.0, 1.0); // discard vertex by putting it outside webgl clip space\n }\n\n vAtlasId = aAtlasId;\n vVertType = aVertType;\n vIndex = aIndex;\n }\n ");
  31473. var idxs = this.batchManager.getIndexArray();
  31474. var fragmentShaderSource = "#version 300 es\n precision highp float;\n\n // declare texture unit for each texture atlas in the batch\n ".concat(idxs.map(function (i) {
  31475. return "uniform sampler2D uTexture".concat(i, ";");
  31476. }).join('\n\t'), "\n\n uniform vec4 uBGColor;\n uniform float uZoom;\n\n in vec2 vTexCoord;\n in vec4 vColor;\n in vec2 vPosition; // model coordinates\n\n flat in int vAtlasId;\n flat in vec4 vIndex;\n flat in int vVertType;\n flat in vec2 vTopRight;\n flat in vec2 vBotLeft;\n flat in vec4 vCornerRadius;\n flat in vec4 vBorderColor;\n flat in vec2 vBorderWidth;\n\n out vec4 outColor;\n\n ").concat(circleSD, "\n ").concat(rectangleSD, "\n ").concat(roundRectangleSD, "\n ").concat(ellipseSD, "\n\n vec4 blend(vec4 top, vec4 bot) { // blend colors with premultiplied alpha\n return vec4( \n top.rgb + (bot.rgb * (1.0 - top.a)),\n top.a + (bot.a * (1.0 - top.a)) \n );\n }\n\n vec4 distInterp(vec4 cA, vec4 cB, float d) { // interpolate color using Signed Distance\n // scale to the zoom level so that borders don't look blurry when zoomed in\n // note 1.5 is an aribitrary value chosen because it looks good\n return mix(cA, cB, 1.0 - smoothstep(0.0, 1.5 / uZoom, abs(d))); \n }\n\n void main(void) {\n if(vVertType == ").concat(TEXTURE, ") {\n // look up the texel from the texture unit\n ").concat(idxs.map(function (i) {
  31477. return "if(vAtlasId == ".concat(i, ") outColor = texture(uTexture").concat(i, ", vTexCoord);");
  31478. }).join('\n\telse '), "\n } \n else if(vVertType == ").concat(EDGE_ARROW, ") {\n // mimics how canvas renderer uses context.globalCompositeOperation = 'destination-out';\n outColor = blend(vColor, uBGColor);\n outColor.a = 1.0; // make opaque, masks out line under arrow\n }\n else if(vVertType == ").concat(RECTANGLE, " && vBorderWidth == vec2(0.0)) { // simple rectangle with no border\n outColor = vColor; // unit square is already transformed to the rectangle, nothing else needs to be done\n }\n else if(vVertType == ").concat(RECTANGLE, " || vVertType == ").concat(ELLIPSE, " \n || vVertType == ").concat(ROUND_RECTANGLE, " || vVertType == ").concat(BOTTOM_ROUND_RECTANGLE, ") { // use SDF\n\n float outerBorder = vBorderWidth[0];\n float innerBorder = vBorderWidth[1];\n float borderPadding = outerBorder * 2.0;\n float w = vTopRight.x - vBotLeft.x - borderPadding;\n float h = vTopRight.y - vBotLeft.y - borderPadding;\n vec2 b = vec2(w/2.0, h/2.0); // half width, half height\n vec2 p = vPosition - vec2(vTopRight.x - b[0] - outerBorder, vTopRight.y - b[1] - outerBorder); // translate to center\n\n float d; // signed distance\n if(vVertType == ").concat(RECTANGLE, ") {\n d = rectangleSD(p, b);\n } else if(vVertType == ").concat(ELLIPSE, " && w == h) {\n d = circleSD(p, b.x); // faster than ellipse\n } else if(vVertType == ").concat(ELLIPSE, ") {\n d = ellipseSD(p, b);\n } else {\n d = roundRectangleSD(p, b, vCornerRadius.wzyx);\n }\n\n // use the distance to interpolate a color to smooth the edges of the shape, doesn't need multisampling\n // we must smooth colors inwards, because we can't change pixels outside the shape's bounding box\n if(d > 0.0) {\n if(d > outerBorder) {\n discard;\n } else {\n outColor = distInterp(vBorderColor, vec4(0), d - outerBorder);\n }\n } else {\n if(d > innerBorder) {\n vec4 outerColor = outerBorder == 0.0 ? vec4(0) : vBorderColor;\n vec4 innerBorderColor = blend(vBorderColor, vColor);\n outColor = distInterp(innerBorderColor, outerColor, d);\n } \n else {\n vec4 outerColor;\n if(innerBorder == 0.0 && outerBorder == 0.0) {\n outerColor = vec4(0);\n } else if(innerBorder == 0.0) {\n outerColor = vBorderColor;\n } else {\n outerColor = blend(vBorderColor, vColor);\n }\n outColor = distInterp(vColor, outerColor, d - innerBorder);\n }\n }\n }\n else {\n outColor = vColor;\n }\n\n ").concat(renderTarget.picking ? "if(outColor.a == 0.0) discard;\n else outColor = vIndex;" : '', "\n }\n ");
  31479. var program = createProgram(gl, vertexShaderSource, fragmentShaderSource);
  31480. // instance geometry
  31481. program.aPosition = gl.getAttribLocation(program, 'aPosition');
  31482. // attributes
  31483. program.aIndex = gl.getAttribLocation(program, 'aIndex');
  31484. program.aVertType = gl.getAttribLocation(program, 'aVertType');
  31485. program.aTransform = gl.getAttribLocation(program, 'aTransform');
  31486. program.aAtlasId = gl.getAttribLocation(program, 'aAtlasId');
  31487. program.aTex = gl.getAttribLocation(program, 'aTex');
  31488. program.aPointAPointB = gl.getAttribLocation(program, 'aPointAPointB');
  31489. program.aPointCPointD = gl.getAttribLocation(program, 'aPointCPointD');
  31490. program.aLineWidth = gl.getAttribLocation(program, 'aLineWidth');
  31491. program.aColor = gl.getAttribLocation(program, 'aColor');
  31492. program.aCornerRadius = gl.getAttribLocation(program, 'aCornerRadius');
  31493. program.aBorderColor = gl.getAttribLocation(program, 'aBorderColor');
  31494. // uniforms
  31495. program.uPanZoomMatrix = gl.getUniformLocation(program, 'uPanZoomMatrix');
  31496. program.uAtlasSize = gl.getUniformLocation(program, 'uAtlasSize');
  31497. program.uBGColor = gl.getUniformLocation(program, 'uBGColor');
  31498. program.uZoom = gl.getUniformLocation(program, 'uZoom');
  31499. program.uTextures = [];
  31500. for (var i = 0; i < this.batchManager.getMaxAtlasesPerBatch(); i++) {
  31501. program.uTextures.push(gl.getUniformLocation(program, "uTexture".concat(i)));
  31502. }
  31503. return program;
  31504. }
  31505. }, {
  31506. key: "_createVAO",
  31507. value: function _createVAO() {
  31508. var unitSquare = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1];
  31509. this.vertexCount = unitSquare.length / 2;
  31510. var n = this.maxInstances;
  31511. var gl = this.gl,
  31512. program = this.program;
  31513. var vao = gl.createVertexArray();
  31514. gl.bindVertexArray(vao);
  31515. createBufferStaticDraw(gl, 'vec2', program.aPosition, unitSquare);
  31516. // Create buffers for all the attributes
  31517. this.transformBuffer = create3x3MatrixBufferDynamicDraw(gl, n, program.aTransform);
  31518. this.indexBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aIndex);
  31519. this.vertTypeBuffer = createBufferDynamicDraw(gl, n, 'int', program.aVertType);
  31520. this.atlasIdBuffer = createBufferDynamicDraw(gl, n, 'int', program.aAtlasId);
  31521. this.texBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aTex);
  31522. this.pointAPointBBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointAPointB);
  31523. this.pointCPointDBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointCPointD);
  31524. this.lineWidthBuffer = createBufferDynamicDraw(gl, n, 'vec2', program.aLineWidth);
  31525. this.colorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aColor);
  31526. this.cornerRadiusBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aCornerRadius);
  31527. this.borderColorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aBorderColor);
  31528. gl.bindVertexArray(null);
  31529. return vao;
  31530. }
  31531. }, {
  31532. key: "buffers",
  31533. get: function get() {
  31534. var _this = this;
  31535. if (!this._buffers) {
  31536. this._buffers = Object.keys(this).filter(function (k) {
  31537. return endsWith(k, 'Buffer');
  31538. }).map(function (k) {
  31539. return _this[k];
  31540. });
  31541. }
  31542. return this._buffers;
  31543. }
  31544. }, {
  31545. key: "startFrame",
  31546. value: function startFrame(panZoomMatrix) {
  31547. var renderTarget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : RENDER_TARGET.SCREEN;
  31548. this.panZoomMatrix = panZoomMatrix;
  31549. this.renderTarget = renderTarget;
  31550. this.batchDebugInfo = [];
  31551. this.wrappedCount = 0;
  31552. this.simpleCount = 0;
  31553. this.startBatch();
  31554. }
  31555. }, {
  31556. key: "startBatch",
  31557. value: function startBatch() {
  31558. this.instanceCount = 0;
  31559. this.batchManager.startBatch();
  31560. }
  31561. }, {
  31562. key: "endFrame",
  31563. value: function endFrame() {
  31564. this.endBatch();
  31565. }
  31566. }, {
  31567. key: "_isVisible",
  31568. value: function _isVisible(ele, opts) {
  31569. if (ele.visible()) {
  31570. if (opts && opts.isVisible) {
  31571. return opts.isVisible(ele);
  31572. }
  31573. return true;
  31574. }
  31575. return false;
  31576. }
  31577. /**
  31578. * Draws a texture using the texture atlas.
  31579. */
  31580. }, {
  31581. key: "drawTexture",
  31582. value: function drawTexture(ele, eleIndex, type) {
  31583. var atlasManager = this.atlasManager,
  31584. batchManager = this.batchManager;
  31585. var opts = atlasManager.getRenderTypeOpts(type);
  31586. if (!this._isVisible(ele, opts)) {
  31587. return;
  31588. }
  31589. // Edges with invalid points could be passed here (labels), causing errors
  31590. // Ref: Random "Script Error" thrown when generating nodes and edges in newest webgl version #3365
  31591. // https://github.com/cytoscape/cytoscape.js/issues/3365
  31592. if (ele.isEdge() && !this._isValidEdge(ele)) {
  31593. return;
  31594. }
  31595. if (this.renderTarget.picking && opts.getTexPickingMode) {
  31596. var mode = opts.getTexPickingMode(ele);
  31597. if (mode === TEX_PICKING_MODE.IGNORE) {
  31598. return;
  31599. } else if (mode == TEX_PICKING_MODE.USE_BB) {
  31600. this.drawPickingRectangle(ele, eleIndex, type);
  31601. return;
  31602. }
  31603. }
  31604. // Get the atlas and the texture coordinates, will draw the texture if it hasn't been drawn yet
  31605. // May be more than one texture if for example the label has multiple lines
  31606. var atlasInfoArray = atlasManager.getAtlasInfo(ele, type);
  31607. var _iterator = _createForOfIteratorHelper(atlasInfoArray),
  31608. _step;
  31609. try {
  31610. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  31611. var atlasInfo = _step.value;
  31612. var atlas = atlasInfo.atlas,
  31613. tex1 = atlasInfo.tex1,
  31614. tex2 = atlasInfo.tex2; // tex2 is used if the label wraps and there are two textures
  31615. if (!batchManager.canAddToCurrentBatch(atlas)) {
  31616. this.endBatch();
  31617. }
  31618. var atlasIndex = batchManager.getAtlasIndexForBatch(atlas);
  31619. for (var _i = 0, _arr = [[tex1, true], [tex2, false]]; _i < _arr.length; _i++) {
  31620. var _arr$_i = _slicedToArray(_arr[_i], 2),
  31621. tex = _arr$_i[0],
  31622. first = _arr$_i[1];
  31623. if (tex.w != 0) {
  31624. var instance = this.instanceCount;
  31625. this.vertTypeBuffer.getView(instance)[0] = TEXTURE;
  31626. var indexView = this.indexBuffer.getView(instance);
  31627. indexToVec4(eleIndex, indexView);
  31628. // Set values in the buffers using Typed Array Views for performance.
  31629. var atlasIdView = this.atlasIdBuffer.getView(instance);
  31630. atlasIdView[0] = atlasIndex;
  31631. // we have two sets of texture coordinates and transforms because textures can wrap in the atlas
  31632. var texView = this.texBuffer.getView(instance);
  31633. texView[0] = tex.x;
  31634. texView[1] = tex.y;
  31635. texView[2] = tex.w;
  31636. texView[3] = tex.h;
  31637. var matrixView = this.transformBuffer.getMatrixView(instance);
  31638. this.setTransformMatrix(ele, matrixView, opts, atlasInfo, first);
  31639. this.instanceCount++;
  31640. if (!first) this.wrappedCount++;
  31641. if (this.instanceCount >= this.maxInstances) {
  31642. this.endBatch();
  31643. }
  31644. }
  31645. }
  31646. }
  31647. } catch (err) {
  31648. _iterator.e(err);
  31649. } finally {
  31650. _iterator.f();
  31651. }
  31652. }
  31653. /**
  31654. * matrix is expected to be a 9 element array
  31655. * this function follows same pattern as CRp.drawCachedElementPortion(...)
  31656. */
  31657. }, {
  31658. key: "setTransformMatrix",
  31659. value: function setTransformMatrix(ele, matrix, opts, atlasInfo) {
  31660. var first = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  31661. var padding = 0;
  31662. if (opts.shapeProps && opts.shapeProps.padding) {
  31663. padding = ele.pstyle(opts.shapeProps.padding).pfValue;
  31664. }
  31665. if (atlasInfo) {
  31666. // we've already computed the bb and tex bounds for a texture
  31667. var bb = atlasInfo.bb,
  31668. tex1 = atlasInfo.tex1,
  31669. tex2 = atlasInfo.tex2;
  31670. // wrapped textures need separate matrix for each part
  31671. var ratio = tex1.w / (tex1.w + tex2.w);
  31672. if (!first) {
  31673. // first = true means its the first part of the wrapped texture
  31674. ratio = 1 - ratio;
  31675. }
  31676. var adjBB = this._getAdjustedBB(bb, padding, first, ratio);
  31677. this._applyTransformMatrix(matrix, adjBB, opts, ele);
  31678. } else {
  31679. // we don't have a texture, or we want to avoid creating a texture for simple shapes
  31680. var _bb = opts.getBoundingBox(ele);
  31681. var _adjBB = this._getAdjustedBB(_bb, padding, true, 1);
  31682. this._applyTransformMatrix(matrix, _adjBB, opts, ele);
  31683. }
  31684. }
  31685. }, {
  31686. key: "_applyTransformMatrix",
  31687. value: function _applyTransformMatrix(matrix, adjBB, opts, ele) {
  31688. var x, y;
  31689. identity(matrix);
  31690. var theta = opts.getRotation ? opts.getRotation(ele) : 0;
  31691. if (theta !== 0) {
  31692. var _opts$getRotationPoin = opts.getRotationPoint(ele),
  31693. sx = _opts$getRotationPoin.x,
  31694. sy = _opts$getRotationPoin.y;
  31695. translate(matrix, matrix, [sx, sy]);
  31696. rotate(matrix, matrix, theta);
  31697. var offset = opts.getRotationOffset(ele);
  31698. x = offset.x + (adjBB.xOffset || 0);
  31699. y = offset.y + (adjBB.yOffset || 0);
  31700. } else {
  31701. x = adjBB.x1;
  31702. y = adjBB.y1;
  31703. }
  31704. translate(matrix, matrix, [x, y]);
  31705. scale(matrix, matrix, [adjBB.w, adjBB.h]);
  31706. }
  31707. /**
  31708. * Adjusts a node or label BB to accomodate padding and split for wrapped textures.
  31709. * @param bb - the original bounding box
  31710. * @param padding - the padding to add to the bounding box
  31711. * @param first - whether this is the first part of a wrapped texture
  31712. * @param ratio - the ratio of the texture width of part of the text to the entire texture
  31713. */
  31714. }, {
  31715. key: "_getAdjustedBB",
  31716. value: function _getAdjustedBB(bb, padding, first, ratio) {
  31717. var x1 = bb.x1,
  31718. y1 = bb.y1,
  31719. w = bb.w,
  31720. h = bb.h,
  31721. yOffset = bb.yOffset;
  31722. if (padding) {
  31723. x1 -= padding;
  31724. y1 -= padding;
  31725. w += 2 * padding;
  31726. h += 2 * padding;
  31727. }
  31728. var xOffset = 0;
  31729. var adjW = w * ratio;
  31730. if (first && ratio < 1) {
  31731. w = adjW;
  31732. } else if (!first && ratio < 1) {
  31733. xOffset = w - adjW;
  31734. x1 += xOffset;
  31735. w = adjW;
  31736. }
  31737. return {
  31738. x1: x1,
  31739. y1: y1,
  31740. w: w,
  31741. h: h,
  31742. xOffset: xOffset,
  31743. yOffset: yOffset
  31744. };
  31745. }
  31746. /**
  31747. * Draw a solid opaque rectangle matching the element's Bounding Box.
  31748. * Used by the PICKING mode to make the entire BB of a label clickable.
  31749. */
  31750. }, {
  31751. key: "drawPickingRectangle",
  31752. value: function drawPickingRectangle(ele, eleIndex, type) {
  31753. var opts = this.atlasManager.getRenderTypeOpts(type);
  31754. var instance = this.instanceCount;
  31755. this.vertTypeBuffer.getView(instance)[0] = RECTANGLE;
  31756. var indexView = this.indexBuffer.getView(instance);
  31757. indexToVec4(eleIndex, indexView);
  31758. var colorView = this.colorBuffer.getView(instance);
  31759. toWebGLColor([0, 0, 0], 1, colorView); // opaque, so entire label BB is clickable
  31760. var matrixView = this.transformBuffer.getMatrixView(instance);
  31761. this.setTransformMatrix(ele, matrixView, opts);
  31762. this.simpleCount++;
  31763. this.instanceCount++;
  31764. if (this.instanceCount >= this.maxInstances) {
  31765. this.endBatch();
  31766. }
  31767. }
  31768. /**
  31769. * Draw a node using either a texture or a "simple shape".
  31770. */
  31771. }, {
  31772. key: "drawNode",
  31773. value: function drawNode(node, eleIndex, type) {
  31774. var opts = this.simpleShapeOptions.get(type);
  31775. if (!this._isVisible(node, opts)) {
  31776. return;
  31777. }
  31778. var props = opts.shapeProps;
  31779. // Check if we have to use a texture
  31780. var vertType = this._getVertTypeForShape(node, props.shape);
  31781. if (vertType === undefined || opts.isSimple && !opts.isSimple(node, this.renderTarget)) {
  31782. this.drawTexture(node, eleIndex, type);
  31783. return;
  31784. }
  31785. // Render a "simple shape" using SDF (signed distance fields)
  31786. var instance = this.instanceCount;
  31787. this.vertTypeBuffer.getView(instance)[0] = vertType;
  31788. if (vertType === ROUND_RECTANGLE || vertType === BOTTOM_ROUND_RECTANGLE) {
  31789. // get corner radius
  31790. var bb = opts.getBoundingBox(node);
  31791. var radius = this._getCornerRadius(node, props.radius, bb);
  31792. var radiusView = this.cornerRadiusBuffer.getView(instance);
  31793. radiusView[0] = radius; // top-right
  31794. radiusView[1] = radius; // bottom-right
  31795. radiusView[2] = radius; // top-left
  31796. radiusView[3] = radius; // bottom-left
  31797. if (vertType === BOTTOM_ROUND_RECTANGLE) {
  31798. radiusView[0] = 0;
  31799. radiusView[2] = 0;
  31800. }
  31801. }
  31802. var indexView = this.indexBuffer.getView(instance);
  31803. indexToVec4(eleIndex, indexView);
  31804. // Nodes should still be clickable if they pass the visibility check but
  31805. // have background-opacity: 0
  31806. var opacity = this.renderTarget.picking ? 1 : node.pstyle(props.opacity).value;
  31807. var color = node.pstyle(props.color).value;
  31808. var colorView = this.colorBuffer.getView(instance);
  31809. toWebGLColor(color, opacity, colorView);
  31810. var lineWidthView = this.lineWidthBuffer.getView(instance); // reuse edge line width attribute for node border
  31811. lineWidthView[0] = 0;
  31812. lineWidthView[1] = 0;
  31813. if (props.border) {
  31814. var borderWidth = node.pstyle('border-width').value;
  31815. if (borderWidth > 0) {
  31816. var borderColor = node.pstyle('border-color').value;
  31817. var borderOpacity = node.pstyle('border-opacity').value;
  31818. var borderColorView = this.borderColorBuffer.getView(instance);
  31819. toWebGLColor(borderColor, borderOpacity, borderColorView);
  31820. // SDF distance is negative inside the shape and positive outside
  31821. var borderPos = node.pstyle('border-position').value;
  31822. if (borderPos === 'inside') {
  31823. lineWidthView[0] = 0;
  31824. lineWidthView[1] = -borderWidth;
  31825. } else if (borderPos === 'outside') {
  31826. lineWidthView[0] = borderWidth;
  31827. lineWidthView[1] = 0;
  31828. } else {
  31829. // 'center'
  31830. var halfWidth = borderWidth / 2;
  31831. lineWidthView[0] = halfWidth;
  31832. lineWidthView[1] = -halfWidth;
  31833. }
  31834. }
  31835. }
  31836. var matrixView = this.transformBuffer.getMatrixView(instance);
  31837. this.setTransformMatrix(node, matrixView, opts);
  31838. this.simpleCount++;
  31839. this.instanceCount++;
  31840. if (this.instanceCount >= this.maxInstances) {
  31841. this.endBatch();
  31842. }
  31843. }
  31844. }, {
  31845. key: "_getVertTypeForShape",
  31846. value: function _getVertTypeForShape(node, shapeProp) {
  31847. var shape = node.pstyle(shapeProp).value;
  31848. switch (shape) {
  31849. case 'rectangle':
  31850. return RECTANGLE;
  31851. case 'ellipse':
  31852. return ELLIPSE;
  31853. case 'roundrectangle':
  31854. case 'round-rectangle':
  31855. return ROUND_RECTANGLE;
  31856. case 'bottom-round-rectangle':
  31857. return BOTTOM_ROUND_RECTANGLE;
  31858. default:
  31859. return undefined;
  31860. }
  31861. }
  31862. }, {
  31863. key: "_getCornerRadius",
  31864. value: function _getCornerRadius(node, radiusProp, _ref2) {
  31865. var w = _ref2.w,
  31866. h = _ref2.h;
  31867. // see CRp.drawRoundRectanglePath
  31868. if (node.pstyle(radiusProp).value === 'auto') {
  31869. return getRoundRectangleRadius(w, h);
  31870. } else {
  31871. var radius = node.pstyle(radiusProp).pfValue;
  31872. var halfWidth = w / 2;
  31873. var halfHeight = h / 2;
  31874. return Math.min(radius, halfHeight, halfWidth);
  31875. }
  31876. }
  31877. /**
  31878. * Only supports drawing triangles at the moment.
  31879. */
  31880. }, {
  31881. key: "drawEdgeArrow",
  31882. value: function drawEdgeArrow(edge, eleIndex, prefix) {
  31883. if (!edge.visible()) {
  31884. return;
  31885. }
  31886. // Edge points and arrow angles etc are calculated by the base renderer and cached in the rscratch object.
  31887. var rs = edge._private.rscratch;
  31888. var x, y, angle;
  31889. if (prefix === 'source') {
  31890. x = rs.arrowStartX;
  31891. y = rs.arrowStartY;
  31892. angle = rs.srcArrowAngle;
  31893. } else {
  31894. x = rs.arrowEndX;
  31895. y = rs.arrowEndY;
  31896. angle = rs.tgtArrowAngle;
  31897. }
  31898. // taken from CRp.drawArrowhead
  31899. if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
  31900. return;
  31901. }
  31902. // check shape after the x/y check because pstyle() is a bit slow
  31903. var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  31904. if (arrowShape === 'none') {
  31905. return;
  31906. }
  31907. var color = edge.pstyle(prefix + '-arrow-color').value;
  31908. var baseOpacity = edge.pstyle('opacity').value;
  31909. var lineOpacity = edge.pstyle('line-opacity').value;
  31910. var opacity = baseOpacity * lineOpacity;
  31911. var lineWidth = edge.pstyle('width').pfValue;
  31912. var scale$1 = edge.pstyle('arrow-scale').value;
  31913. var size = this.r.getArrowWidth(lineWidth, scale$1);
  31914. var instance = this.instanceCount;
  31915. var transform = this.transformBuffer.getMatrixView(instance);
  31916. identity(transform);
  31917. translate(transform, transform, [x, y]);
  31918. scale(transform, transform, [size, size]);
  31919. rotate(transform, transform, angle);
  31920. this.vertTypeBuffer.getView(instance)[0] = EDGE_ARROW;
  31921. var indexView = this.indexBuffer.getView(instance);
  31922. indexToVec4(eleIndex, indexView);
  31923. var colorView = this.colorBuffer.getView(instance);
  31924. toWebGLColor(color, opacity, colorView);
  31925. this.instanceCount++;
  31926. if (this.instanceCount >= this.maxInstances) {
  31927. this.endBatch();
  31928. }
  31929. }
  31930. /**
  31931. * Draw straight-line or bezier curve edges.
  31932. */
  31933. }, {
  31934. key: "drawEdgeLine",
  31935. value: function drawEdgeLine(edge, eleIndex) {
  31936. if (!edge.visible()) {
  31937. return;
  31938. }
  31939. var points = this._getEdgePoints(edge);
  31940. if (!points) {
  31941. return;
  31942. }
  31943. // line style
  31944. var baseOpacity = edge.pstyle('opacity').value;
  31945. var lineOpacity = edge.pstyle('line-opacity').value;
  31946. var width = edge.pstyle('width').pfValue;
  31947. var color = edge.pstyle('line-color').value;
  31948. var opacity = baseOpacity * lineOpacity;
  31949. if (points.length / 2 + this.instanceCount > this.maxInstances) {
  31950. this.endBatch();
  31951. }
  31952. if (points.length == 4) {
  31953. // straight line
  31954. var instance = this.instanceCount;
  31955. this.vertTypeBuffer.getView(instance)[0] = EDGE_STRAIGHT;
  31956. var indexView = this.indexBuffer.getView(instance);
  31957. indexToVec4(eleIndex, indexView);
  31958. var colorView = this.colorBuffer.getView(instance);
  31959. toWebGLColor(color, opacity, colorView);
  31960. var lineWidthBuffer = this.lineWidthBuffer.getView(instance);
  31961. lineWidthBuffer[0] = width;
  31962. var sourceTargetView = this.pointAPointBBuffer.getView(instance);
  31963. sourceTargetView[0] = points[0]; // source x
  31964. sourceTargetView[1] = points[1]; // source y
  31965. sourceTargetView[2] = points[2]; // target x
  31966. sourceTargetView[3] = points[3]; // target y
  31967. this.instanceCount++;
  31968. if (this.instanceCount >= this.maxInstances) {
  31969. this.endBatch();
  31970. }
  31971. } else {
  31972. // curved line
  31973. for (var i = 0; i < points.length - 2; i += 2) {
  31974. var _instance = this.instanceCount;
  31975. this.vertTypeBuffer.getView(_instance)[0] = EDGE_CURVE_SEGMENT;
  31976. var _indexView = this.indexBuffer.getView(_instance);
  31977. indexToVec4(eleIndex, _indexView);
  31978. var _colorView = this.colorBuffer.getView(_instance);
  31979. toWebGLColor(color, opacity, _colorView);
  31980. var _lineWidthBuffer = this.lineWidthBuffer.getView(_instance);
  31981. _lineWidthBuffer[0] = width;
  31982. var pAx = points[i - 2],
  31983. pAy = points[i - 1];
  31984. var pBx = points[i],
  31985. pBy = points[i + 1];
  31986. var pCx = points[i + 2],
  31987. pCy = points[i + 3];
  31988. var pDx = points[i + 4],
  31989. pDy = points[i + 5];
  31990. // make phantom points for the first and last segments
  31991. // TODO adding 0.001 to avoid division by zero in the shader (I think), need a better solution
  31992. if (i == 0) {
  31993. pAx = 2 * pBx - pCx + 0.001;
  31994. pAy = 2 * pBy - pCy + 0.001;
  31995. }
  31996. if (i == points.length - 4) {
  31997. pDx = 2 * pCx - pBx + 0.001;
  31998. pDy = 2 * pCy - pBy + 0.001;
  31999. }
  32000. var pointABView = this.pointAPointBBuffer.getView(_instance);
  32001. pointABView[0] = pAx;
  32002. pointABView[1] = pAy;
  32003. pointABView[2] = pBx;
  32004. pointABView[3] = pBy;
  32005. var pointCDView = this.pointCPointDBuffer.getView(_instance);
  32006. pointCDView[0] = pCx;
  32007. pointCDView[1] = pCy;
  32008. pointCDView[2] = pDx;
  32009. pointCDView[3] = pDy;
  32010. this.instanceCount++;
  32011. if (this.instanceCount >= this.maxInstances) {
  32012. this.endBatch();
  32013. }
  32014. }
  32015. }
  32016. }
  32017. }, {
  32018. key: "_isValidEdge",
  32019. value: function _isValidEdge(edge) {
  32020. var rs = edge._private.rscratch;
  32021. if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
  32022. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  32023. return false;
  32024. }
  32025. return true;
  32026. }
  32027. }, {
  32028. key: "_getEdgePoints",
  32029. value: function _getEdgePoints(edge) {
  32030. var rs = edge._private.rscratch;
  32031. // if bezier ctrl pts can not be calculated, then die
  32032. if (!this._isValidEdge(edge)) {
  32033. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  32034. return;
  32035. }
  32036. var controlPoints = rs.allpts;
  32037. if (controlPoints.length == 4) {
  32038. return controlPoints;
  32039. }
  32040. var numSegments = this._getNumSegments(edge);
  32041. return this._getCurveSegmentPoints(controlPoints, numSegments);
  32042. }
  32043. }, {
  32044. key: "_getNumSegments",
  32045. value: function _getNumSegments(edge) {
  32046. // TODO Need a heuristic that decides how many segments to use. Factors to consider:
  32047. // - edge width/length
  32048. // - edge curvature (the more the curvature, the more segments)
  32049. // - zoom level (more segments when zoomed in)
  32050. // - number of visible edges (more segments when there are fewer edges)
  32051. // - performance (fewer segments when performance is a concern)
  32052. // - user configurable option(s)
  32053. // note: number of segments must be less than the max number of instances
  32054. // note: segments don't need to be evenly spaced out, it might make sense to have shorter segments nearer to the control points
  32055. var numSegments = 15;
  32056. return Math.min(Math.max(numSegments, 5), this.maxInstances);
  32057. }
  32058. }, {
  32059. key: "_getCurveSegmentPoints",
  32060. value: function _getCurveSegmentPoints(controlPoints, segments) {
  32061. if (controlPoints.length == 4) {
  32062. return controlPoints; // straight line
  32063. }
  32064. var curvePoints = Array((segments + 1) * 2);
  32065. for (var i = 0; i <= segments; i++) {
  32066. // the first and last points are the same as the first and last control points
  32067. if (i == 0) {
  32068. curvePoints[0] = controlPoints[0];
  32069. curvePoints[1] = controlPoints[1];
  32070. } else if (i == segments) {
  32071. curvePoints[i * 2] = controlPoints[controlPoints.length - 2];
  32072. curvePoints[i * 2 + 1] = controlPoints[controlPoints.length - 1];
  32073. } else {
  32074. var t = i / segments; // segments have equal length, its not strictly necessary to do it this way
  32075. // pass in curvePoints to set the values in the array directly
  32076. this._setCurvePoint(controlPoints, t, curvePoints, i * 2);
  32077. }
  32078. }
  32079. return curvePoints;
  32080. }
  32081. }, {
  32082. key: "_setCurvePoint",
  32083. value: function _setCurvePoint(points, t, curvePoints, cpi) {
  32084. if (points.length <= 2) {
  32085. curvePoints[cpi] = points[0];
  32086. curvePoints[cpi + 1] = points[1];
  32087. } else {
  32088. var newpoints = Array(points.length - 2);
  32089. for (var i = 0; i < newpoints.length; i += 2) {
  32090. var x = (1 - t) * points[i] + t * points[i + 2];
  32091. var y = (1 - t) * points[i + 1] + t * points[i + 3];
  32092. newpoints[i] = x;
  32093. newpoints[i + 1] = y;
  32094. }
  32095. return this._setCurvePoint(newpoints, t, curvePoints, cpi);
  32096. }
  32097. }
  32098. }, {
  32099. key: "endBatch",
  32100. value: function endBatch() {
  32101. var gl = this.gl,
  32102. vao = this.vao,
  32103. vertexCount = this.vertexCount,
  32104. count = this.instanceCount;
  32105. if (count === 0) return;
  32106. var program = this.renderTarget.picking ? this.pickingProgram : this.program;
  32107. gl.useProgram(program);
  32108. gl.bindVertexArray(vao);
  32109. // buffer the attribute data
  32110. var _iterator2 = _createForOfIteratorHelper(this.buffers),
  32111. _step2;
  32112. try {
  32113. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  32114. var buffer = _step2.value;
  32115. buffer.bufferSubData(count);
  32116. }
  32117. } catch (err) {
  32118. _iterator2.e(err);
  32119. } finally {
  32120. _iterator2.f();
  32121. }
  32122. var atlases = this.batchManager.getAtlases();
  32123. // must buffer before activating texture units
  32124. for (var i = 0; i < atlases.length; i++) {
  32125. atlases[i].bufferIfNeeded(gl);
  32126. }
  32127. // Activate all the texture units that we need
  32128. for (var _i2 = 0; _i2 < atlases.length; _i2++) {
  32129. gl.activeTexture(gl.TEXTURE0 + _i2);
  32130. gl.bindTexture(gl.TEXTURE_2D, atlases[_i2].texture);
  32131. gl.uniform1i(program.uTextures[_i2], _i2);
  32132. }
  32133. // Set the uniforms
  32134. gl.uniform1f(program.uZoom, getEffectiveZoom(this.r));
  32135. gl.uniformMatrix3fv(program.uPanZoomMatrix, false, this.panZoomMatrix);
  32136. gl.uniform1i(program.uAtlasSize, this.batchManager.getAtlasSize());
  32137. // set background color, needed for edge arrow color blending
  32138. var webglBgColor = toWebGLColor(this.bgColor, 1);
  32139. gl.uniform4fv(program.uBGColor, webglBgColor);
  32140. // draw!
  32141. gl.drawArraysInstanced(gl.TRIANGLES, 0, vertexCount, count);
  32142. gl.bindVertexArray(null);
  32143. gl.bindTexture(gl.TEXTURE_2D, null); // TODO is this right when having multiple texture units?
  32144. if (this.debug) {
  32145. this.batchDebugInfo.push({
  32146. count: count,
  32147. // instance count
  32148. atlasCount: atlases.length
  32149. });
  32150. }
  32151. // start the next batch, even if not needed
  32152. this.startBatch();
  32153. }
  32154. }, {
  32155. key: "getDebugInfo",
  32156. value: function getDebugInfo() {
  32157. var atlasInfo = this.atlasManager.getDebugInfo();
  32158. var totalAtlases = atlasInfo.reduce(function (count, info) {
  32159. return count + info.atlasCount;
  32160. }, 0);
  32161. var batchInfo = this.batchDebugInfo;
  32162. var totalInstances = batchInfo.reduce(function (count, info) {
  32163. return count + info.count;
  32164. }, 0);
  32165. return {
  32166. atlasInfo: atlasInfo,
  32167. totalAtlases: totalAtlases,
  32168. wrappedCount: this.wrappedCount,
  32169. simpleCount: this.simpleCount,
  32170. batchCount: batchInfo.length,
  32171. batchInfo: batchInfo,
  32172. totalInstances: totalInstances
  32173. };
  32174. }
  32175. }]);
  32176. }();
  32177. var CRp$4 = {};
  32178. /**
  32179. * Initialize the WebGL rendering mode after the Canvas renderer has been initialized.
  32180. */
  32181. CRp$4.initWebgl = function (opts, fns) {
  32182. var r = this;
  32183. var gl = r.data.contexts[r.WEBGL];
  32184. // Set defaults and limits for configuration options.
  32185. opts.bgColor = getBGColor(r);
  32186. opts.webglTexSize = Math.min(opts.webglTexSize, gl.getParameter(gl.MAX_TEXTURE_SIZE));
  32187. opts.webglTexRows = Math.min(opts.webglTexRows, 54);
  32188. opts.webglTexRowsNodes = Math.min(opts.webglTexRowsNodes, 54);
  32189. opts.webglBatchSize = Math.min(opts.webglBatchSize, 16384);
  32190. opts.webglTexPerBatch = Math.min(opts.webglTexPerBatch, gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS));
  32191. // Turn debug mode on or off.
  32192. r.webglDebug = opts.webglDebug;
  32193. r.webglDebugShowAtlases = opts.webglDebugShowAtlases;
  32194. // Create offscreen framebuffer that stores the results when RENDER_TARGET.PICKING is enabled.
  32195. // This is used to store the topmost element z-index for each pixel, which is used to tell whats under the mouse cursor point.
  32196. r.pickingFrameBuffer = createPickingFrameBuffer(gl);
  32197. r.pickingFrameBuffer.needsDraw = true;
  32198. // Create an ElementDrawingWebGL instance wich is used to do the actual WebGL rendering.
  32199. // This instance needs to be configured to draw various types of elements.
  32200. r.drawing = new ElementDrawingWebGL(r, gl, opts);
  32201. // Some functions that are used to configure ElementDrawingWebGL
  32202. var getLabelRotation = function getLabelRotation(prop) {
  32203. return function (ele) {
  32204. return r.getTextAngle(ele, prop);
  32205. };
  32206. };
  32207. var isLabelVisible = function isLabelVisible(prop) {
  32208. return function (ele) {
  32209. var label = ele.pstyle(prop);
  32210. return label && label.value;
  32211. };
  32212. };
  32213. var isLayerVisible = function isLayerVisible(prefix) {
  32214. return function (node) {
  32215. // prefix is 'overlay' or 'underlay'
  32216. return node.pstyle("".concat(prefix, "-opacity")).value > 0;
  32217. };
  32218. };
  32219. var getTexPickingMode = function getTexPickingMode(ele) {
  32220. // tells when a label should be clickable
  32221. var enabled = ele.pstyle('text-events').strValue === 'yes';
  32222. return enabled ? TEX_PICKING_MODE.USE_BB : TEX_PICKING_MODE.IGNORE;
  32223. };
  32224. var getBBForSimpleShape = function getBBForSimpleShape(node) {
  32225. // "simple" shapes need their BB to include border and padding
  32226. var _node$position = node.position(),
  32227. x = _node$position.x,
  32228. y = _node$position.y;
  32229. var w = node.outerWidth(); // includes border and padding
  32230. var h = node.outerHeight();
  32231. return {
  32232. w: w,
  32233. h: h,
  32234. x1: x - w / 2,
  32235. y1: y - h / 2
  32236. };
  32237. };
  32238. // An AtlasCollection is a collection of Atlases that have the same configuraiton options.
  32239. // Create one for node bodies and one for all types of labels.
  32240. r.drawing.addAtlasCollection('node', {
  32241. texRows: opts.webglTexRowsNodes
  32242. });
  32243. r.drawing.addAtlasCollection('label', {
  32244. texRows: opts.webglTexRows
  32245. });
  32246. // Configure the different types of elements that can be rendered.
  32247. // Node bodies can be rendered as textures or as "simple shapes".
  32248. // Simple shapes are preferred because they do not use texture memory.
  32249. // Textures are required if the node body uses complex styles.
  32250. r.drawing.addTextureAtlasRenderType('node-body', {
  32251. collection: 'node',
  32252. getKey: fns.getStyleKey,
  32253. getBoundingBox: fns.getElementBox,
  32254. drawElement: fns.drawElement
  32255. });
  32256. r.drawing.addSimpleShapeRenderType('node-body', {
  32257. getBoundingBox: getBBForSimpleShape,
  32258. isSimple: isSimpleShape,
  32259. shapeProps: {
  32260. shape: 'shape',
  32261. color: 'background-color',
  32262. opacity: 'background-opacity',
  32263. radius: 'corner-radius',
  32264. border: true
  32265. }
  32266. });
  32267. r.drawing.addSimpleShapeRenderType('node-overlay', {
  32268. getBoundingBox: getBBForSimpleShape,
  32269. isVisible: isLayerVisible('overlay'),
  32270. shapeProps: {
  32271. shape: 'overlay-shape',
  32272. color: 'overlay-color',
  32273. opacity: 'overlay-opacity',
  32274. padding: 'overlay-padding',
  32275. radius: 'overlay-corner-radius'
  32276. }
  32277. });
  32278. r.drawing.addSimpleShapeRenderType('node-underlay', {
  32279. getBoundingBox: getBBForSimpleShape,
  32280. isVisible: isLayerVisible('underlay'),
  32281. shapeProps: {
  32282. shape: 'underlay-shape',
  32283. color: 'underlay-color',
  32284. opacity: 'underlay-opacity',
  32285. padding: 'underlay-padding',
  32286. radius: 'underlay-corner-radius'
  32287. }
  32288. });
  32289. r.drawing.addTextureAtlasRenderType('label', {
  32290. // node label or edge mid label
  32291. collection: 'label',
  32292. getTexPickingMode: getTexPickingMode,
  32293. getKey: getStyleKeysForLabel(fns.getLabelKey, null),
  32294. getBoundingBox: getBoundingBoxForLabel(fns.getLabelBox, null),
  32295. drawClipped: true,
  32296. drawElement: fns.drawLabel,
  32297. getRotation: getLabelRotation(null),
  32298. getRotationPoint: fns.getLabelRotationPoint,
  32299. getRotationOffset: fns.getLabelRotationOffset,
  32300. isVisible: isLabelVisible('label')
  32301. });
  32302. r.drawing.addTextureAtlasRenderType('edge-source-label', {
  32303. collection: 'label',
  32304. getTexPickingMode: getTexPickingMode,
  32305. getKey: getStyleKeysForLabel(fns.getSourceLabelKey, 'source'),
  32306. getBoundingBox: getBoundingBoxForLabel(fns.getSourceLabelBox, 'source'),
  32307. drawClipped: true,
  32308. drawElement: fns.drawSourceLabel,
  32309. getRotation: getLabelRotation('source'),
  32310. getRotationPoint: fns.getSourceLabelRotationPoint,
  32311. getRotationOffset: fns.getSourceLabelRotationOffset,
  32312. isVisible: isLabelVisible('source-label')
  32313. });
  32314. r.drawing.addTextureAtlasRenderType('edge-target-label', {
  32315. collection: 'label',
  32316. getTexPickingMode: getTexPickingMode,
  32317. getKey: getStyleKeysForLabel(fns.getTargetLabelKey, 'target'),
  32318. getBoundingBox: getBoundingBoxForLabel(fns.getTargetLabelBox, 'target'),
  32319. drawClipped: true,
  32320. drawElement: fns.drawTargetLabel,
  32321. getRotation: getLabelRotation('target'),
  32322. getRotationPoint: fns.getTargetLabelRotationPoint,
  32323. getRotationOffset: fns.getTargetLabelRotationOffset,
  32324. isVisible: isLabelVisible('target-label')
  32325. });
  32326. // Very simplistic way of triggering garbage collection, just use a timer.
  32327. var setGCFlag = debounce(function () {
  32328. console.log('garbage collect flag set');
  32329. r.data.gc = true;
  32330. }, 10000);
  32331. // Event listener checks if style keys are no longer in use.
  32332. r.onUpdateEleCalcs(function (willDraw, eles) {
  32333. var gcNeeded = false;
  32334. if (eles && eles.length > 0) {
  32335. gcNeeded |= r.drawing.invalidate(eles);
  32336. }
  32337. if (gcNeeded) {
  32338. setGCFlag();
  32339. }
  32340. });
  32341. // "Override" certain functions in canvas and base renderer
  32342. overrideCanvasRendererFunctions(r);
  32343. };
  32344. function getBGColor(r) {
  32345. var container = r.cy.container();
  32346. var cssColor = container && container.style && container.style.backgroundColor || 'white';
  32347. return color2tuple(cssColor);
  32348. }
  32349. function getLabelLines(ele, prefix) {
  32350. var rs = ele._private.rscratch;
  32351. return getPrefixedProperty(rs, 'labelWrapCachedLines', prefix) || [];
  32352. }
  32353. /**
  32354. * Handle multi-line labels by rendering each line as a seperate texture.
  32355. * That means each line needs its own style key.
  32356. */
  32357. var getStyleKeysForLabel = function getStyleKeysForLabel(getKey, prefix) {
  32358. return function (ele) {
  32359. var key = getKey(ele);
  32360. var lines = getLabelLines(ele, prefix);
  32361. if (lines.length > 1) {
  32362. return lines.map(function (line, index) {
  32363. return "".concat(key, "_").concat(index);
  32364. });
  32365. }
  32366. return key;
  32367. };
  32368. };
  32369. /**
  32370. * Need to create a separate bounding box for each line of a multi-line label.
  32371. * Note that 'drawClipped: true' should be used with this.
  32372. */
  32373. var getBoundingBoxForLabel = function getBoundingBoxForLabel(getBoundingBox, prefix) {
  32374. return function (ele, styleKey) {
  32375. var bb = getBoundingBox(ele);
  32376. if (typeof styleKey === 'string') {
  32377. var ui = styleKey.indexOf('_');
  32378. if (ui > 0) {
  32379. var lineIndex = Number(styleKey.substring(ui + 1));
  32380. var lines = getLabelLines(ele, prefix);
  32381. // Adjust the height and Y coordinate for one line of the label.
  32382. var h = bb.h / lines.length;
  32383. var yOffset = h * lineIndex;
  32384. var y1 = bb.y1 + yOffset;
  32385. // the yOffset is needed when rotating the label
  32386. return {
  32387. x1: bb.x1,
  32388. w: bb.w,
  32389. y1: y1,
  32390. h: h,
  32391. yOffset: yOffset
  32392. };
  32393. }
  32394. }
  32395. return bb;
  32396. };
  32397. };
  32398. /**
  32399. * Plug into the canvas renderer by dynamically overriding some of its functions.
  32400. * This requires minimal changes to the canvas rendrerer.
  32401. */
  32402. function overrideCanvasRendererFunctions(r) {
  32403. {
  32404. // Override the render function to call the webgl render function if the zoom level is appropriate
  32405. var renderCanvas = r.render;
  32406. r.render = function (options) {
  32407. options = options || {};
  32408. var cy = r.cy;
  32409. if (r.webgl) {
  32410. // If the zoom level is greater than the max zoom level, then disable webgl and switch back to
  32411. // the canvas renderer.
  32412. if (cy.zoom() > maxZoom$1) {
  32413. clearWebgl(r);
  32414. renderCanvas.call(r, options);
  32415. } else {
  32416. clearCanvas(r);
  32417. renderWebgl(r, options, RENDER_TARGET.SCREEN);
  32418. }
  32419. }
  32420. };
  32421. }
  32422. {
  32423. // Override the matchCanvasSize function to update the picking frame buffer size
  32424. var baseFunc = r.matchCanvasSize;
  32425. r.matchCanvasSize = function (container) {
  32426. baseFunc.call(r, container);
  32427. r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth, r.canvasHeight);
  32428. r.pickingFrameBuffer.needsDraw = true;
  32429. };
  32430. }
  32431. {
  32432. // Override function to call the webgl version for picking.
  32433. // Don't override r.getAllInBox() selction box picking, its not accurate enough with webgl
  32434. r.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  32435. // the canvas version of this function is very slow on large graphs
  32436. return findNearestElementsWebgl(r, x, y);
  32437. };
  32438. }
  32439. {
  32440. // need to know when the cached elements have changed so we can invalidate our caches
  32441. var _baseFunc = r.invalidateCachedZSortedEles;
  32442. r.invalidateCachedZSortedEles = function () {
  32443. _baseFunc.call(r);
  32444. r.pickingFrameBuffer.needsDraw = true;
  32445. };
  32446. }
  32447. {
  32448. // need to know when the cached elements have changed so we can invalidate our caches
  32449. var _baseFunc2 = r.notify;
  32450. r.notify = function (eventName, eles) {
  32451. _baseFunc2.call(r, eventName, eles);
  32452. if (eventName === 'viewport' || eventName === 'bounds') {
  32453. r.pickingFrameBuffer.needsDraw = true;
  32454. } else if (eventName === 'background') {
  32455. // background image finished loading, need to redraw
  32456. r.drawing.invalidate(eles, {
  32457. type: 'node-body'
  32458. });
  32459. }
  32460. };
  32461. }
  32462. }
  32463. function clearWebgl(r) {
  32464. var gl = r.data.contexts[r.WEBGL];
  32465. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  32466. }
  32467. function clearCanvas(r) {
  32468. // the CRp.clearCanvas() function doesn't take the transform into account
  32469. var clear = function clear(context) {
  32470. context.save();
  32471. context.setTransform(1, 0, 0, 1, 0, 0);
  32472. context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  32473. context.restore();
  32474. };
  32475. clear(r.data.contexts[r.NODE]);
  32476. clear(r.data.contexts[r.DRAG]);
  32477. }
  32478. function createPanZoomMatrix(r) {
  32479. var width = r.canvasWidth;
  32480. var height = r.canvasHeight;
  32481. var _util$getEffectivePan = getEffectivePanZoom(r),
  32482. pan = _util$getEffectivePan.pan,
  32483. zoom = _util$getEffectivePan.zoom;
  32484. var transform = create();
  32485. translate(transform, transform, [pan.x, pan.y]);
  32486. scale(transform, transform, [zoom, zoom]);
  32487. var projection$1 = create();
  32488. projection(projection$1, width, height);
  32489. var product = create();
  32490. multiply(product, projection$1, transform);
  32491. return product;
  32492. }
  32493. function setContextTransform(r, context) {
  32494. var width = r.canvasWidth;
  32495. var height = r.canvasHeight;
  32496. var _util$getEffectivePan2 = getEffectivePanZoom(r),
  32497. pan = _util$getEffectivePan2.pan,
  32498. zoom = _util$getEffectivePan2.zoom;
  32499. context.setTransform(1, 0, 0, 1, 0, 0);
  32500. context.clearRect(0, 0, width, height);
  32501. context.translate(pan.x, pan.y);
  32502. context.scale(zoom, zoom);
  32503. }
  32504. function drawSelectionRectangle(r, options) {
  32505. r.drawSelectionRectangle(options, function (context) {
  32506. return setContextTransform(r, context);
  32507. });
  32508. }
  32509. function drawAxes(r) {
  32510. // for debgging
  32511. var context = r.data.contexts[r.NODE];
  32512. context.save();
  32513. setContextTransform(r, context);
  32514. context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
  32515. context.beginPath();
  32516. context.moveTo(-1e3, 0);
  32517. context.lineTo(1000, 0);
  32518. context.stroke();
  32519. context.beginPath();
  32520. context.moveTo(0, -1e3);
  32521. context.lineTo(0, 1000);
  32522. context.stroke();
  32523. context.restore();
  32524. }
  32525. function drawAtlases(r) {
  32526. // For debugging the atlases, this doesn't work for Atlases that are locked
  32527. var draw = function draw(drawing, name, row) {
  32528. var collection = drawing.atlasManager.getAtlasCollection(name);
  32529. var context = r.data.contexts[r.NODE];
  32530. var atlases = collection.atlases;
  32531. for (var _i = 0; _i < atlases.length; _i++) {
  32532. var atlas = atlases[_i];
  32533. var canvas = atlas.canvas;
  32534. if (canvas) {
  32535. var w = canvas.width;
  32536. var h = canvas.height;
  32537. var x = w * _i;
  32538. var y = canvas.height * row;
  32539. var scale = 0.4;
  32540. context.save();
  32541. context.scale(scale, scale);
  32542. context.drawImage(canvas, x, y);
  32543. context.strokeStyle = 'black';
  32544. context.rect(x, y, w, h);
  32545. context.stroke();
  32546. context.restore();
  32547. }
  32548. }
  32549. };
  32550. var i = 0;
  32551. draw(r.drawing, 'node', i++);
  32552. draw(r.drawing, 'label', i++);
  32553. }
  32554. /**
  32555. * Returns the z-order index of elments under or very close to the mouse cursor point.
  32556. * Arguments are in model coordinates.
  32557. * (x1, y1) is top left corner
  32558. * (x2, y2) is bottom right corner (optional)
  32559. * Returns a Set of indexes.
  32560. */
  32561. function getPickingIndexes(r, mX1, mY1, mX2, mY2) {
  32562. var x, y, w, h;
  32563. var _util$getEffectivePan3 = getEffectivePanZoom(r),
  32564. pan = _util$getEffectivePan3.pan,
  32565. zoom = _util$getEffectivePan3.zoom;
  32566. {
  32567. var _util$modelToRendered = modelToRenderedPosition(r, pan, zoom, mX1, mY1),
  32568. _util$modelToRendered2 = _slicedToArray(_util$modelToRendered, 2),
  32569. cX1 = _util$modelToRendered2[0],
  32570. cY1 = _util$modelToRendered2[1];
  32571. var t = 6; // should be even
  32572. x = cX1 - t / 2;
  32573. y = cY1 - t / 2;
  32574. w = t;
  32575. h = t;
  32576. }
  32577. if (w === 0 || h === 0) {
  32578. return [];
  32579. }
  32580. var gl = r.data.contexts[r.WEBGL];
  32581. gl.bindFramebuffer(gl.FRAMEBUFFER, r.pickingFrameBuffer);
  32582. if (r.pickingFrameBuffer.needsDraw) {
  32583. // Draw element z-indexes to the picking framebuffer
  32584. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  32585. renderWebgl(r, null, RENDER_TARGET.PICKING);
  32586. r.pickingFrameBuffer.needsDraw = false;
  32587. }
  32588. var n = w * h; // number of pixels to read
  32589. var data = new Uint8Array(n * 4); // 4 bytes per pixel
  32590. gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, data);
  32591. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  32592. var indexes = new Set();
  32593. for (var i = 0; i < n; i++) {
  32594. var pixel = data.slice(i * 4, i * 4 + 4);
  32595. var index = vec4ToIndex(pixel) - 1; // The framebuffer is cleared with 0s, so z-indexes are offset by 1
  32596. if (index >= 0) {
  32597. indexes.add(index);
  32598. }
  32599. }
  32600. return indexes;
  32601. }
  32602. /**
  32603. * Cy.js: model coordinate y axis goes down
  32604. */
  32605. function findNearestElementsWebgl(r, x, y) {
  32606. // model coordinates
  32607. var indexes = getPickingIndexes(r, x, y);
  32608. var eles = r.getCachedZSortedEles();
  32609. var node, edge;
  32610. var _iterator = _createForOfIteratorHelper(indexes),
  32611. _step;
  32612. try {
  32613. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  32614. var index = _step.value;
  32615. var ele = eles[index];
  32616. if (!node && ele.isNode()) {
  32617. node = ele;
  32618. }
  32619. if (!edge && ele.isEdge()) {
  32620. edge = ele;
  32621. }
  32622. if (node && edge) {
  32623. break;
  32624. }
  32625. }
  32626. } catch (err) {
  32627. _iterator.e(err);
  32628. } finally {
  32629. _iterator.f();
  32630. }
  32631. return [node, edge].filter(Boolean);
  32632. }
  32633. /**
  32634. * Draw one node or edge.
  32635. */
  32636. function drawEle(r, index, ele) {
  32637. var drawing = r.drawing;
  32638. index += 1; // 0 is used to clear the background, need to offset all z-indexes by one
  32639. if (ele.isNode()) {
  32640. drawing.drawNode(ele, index, 'node-underlay');
  32641. drawing.drawNode(ele, index, 'node-body');
  32642. drawing.drawTexture(ele, index, 'label');
  32643. drawing.drawNode(ele, index, 'node-overlay');
  32644. } else {
  32645. drawing.drawEdgeLine(ele, index);
  32646. drawing.drawEdgeArrow(ele, index, 'source');
  32647. drawing.drawEdgeArrow(ele, index, 'target');
  32648. drawing.drawTexture(ele, index, 'label');
  32649. drawing.drawTexture(ele, index, 'edge-source-label');
  32650. drawing.drawTexture(ele, index, 'edge-target-label');
  32651. }
  32652. }
  32653. /**
  32654. * Render one frame.
  32655. */
  32656. function renderWebgl(r, options, renderTarget) {
  32657. var start;
  32658. if (r.webglDebug) {
  32659. start = performance.now(); // eslint-disable-line no-undef
  32660. }
  32661. var drawing = r.drawing;
  32662. var eleCount = 0;
  32663. if (renderTarget.screen) {
  32664. if (r.data.canvasNeedsRedraw[r.SELECT_BOX]) {
  32665. drawSelectionRectangle(r, options);
  32666. }
  32667. }
  32668. // see drawing-elements.js drawCachedElement()
  32669. if (r.data.canvasNeedsRedraw[r.NODE] || renderTarget.picking) {
  32670. var gl = r.data.contexts[r.WEBGL];
  32671. if (renderTarget.screen) {
  32672. gl.clearColor(0, 0, 0, 0); // background color
  32673. gl.enable(gl.BLEND); // enable alpha blending of colors
  32674. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // webgl colors use premultiplied alpha
  32675. } else {
  32676. gl.disable(gl.BLEND); // don't blend z-order index values! they are not colors
  32677. }
  32678. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  32679. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  32680. var panZoomMatrix = createPanZoomMatrix(r);
  32681. var eles = r.getCachedZSortedEles();
  32682. eleCount = eles.length;
  32683. drawing.startFrame(panZoomMatrix, renderTarget);
  32684. if (renderTarget.screen) {
  32685. for (var i = 0; i < eles.nondrag.length; i++) {
  32686. drawEle(r, i, eles.nondrag[i]);
  32687. }
  32688. for (var _i2 = 0; _i2 < eles.drag.length; _i2++) {
  32689. drawEle(r, _i2, eles.drag[_i2]);
  32690. }
  32691. } else if (renderTarget.picking) {
  32692. for (var _i3 = 0; _i3 < eles.length; _i3++) {
  32693. drawEle(r, _i3, eles[_i3]);
  32694. }
  32695. }
  32696. drawing.endFrame();
  32697. if (renderTarget.screen && r.webglDebugShowAtlases) {
  32698. drawAxes(r);
  32699. drawAtlases(r);
  32700. }
  32701. r.data.canvasNeedsRedraw[r.NODE] = false;
  32702. r.data.canvasNeedsRedraw[r.DRAG] = false;
  32703. }
  32704. if (r.webglDebug) {
  32705. // eslint-disable-next-line no-undef
  32706. var end = performance.now();
  32707. var compact = false;
  32708. var time = Math.ceil(end - start);
  32709. var debugInfo = drawing.getDebugInfo();
  32710. var report = ["".concat(eleCount, " elements"), "".concat(debugInfo.totalInstances, " instances"), "".concat(debugInfo.batchCount, " batches"), "".concat(debugInfo.totalAtlases, " atlases"), "".concat(debugInfo.wrappedCount, " wrapped textures"), "".concat(debugInfo.simpleCount, " simple shapes")].join(', ');
  32711. if (compact) {
  32712. console.log("WebGL (".concat(renderTarget.name, ") - time ").concat(time, "ms, ").concat(report));
  32713. } else {
  32714. console.log("WebGL (".concat(renderTarget.name, ") - frame time ").concat(time, "ms"));
  32715. console.log('Totals:');
  32716. console.log(" ".concat(report));
  32717. console.log('Texture Atlases Used:');
  32718. var atlasInfo = debugInfo.atlasInfo;
  32719. var _iterator2 = _createForOfIteratorHelper(atlasInfo),
  32720. _step2;
  32721. try {
  32722. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  32723. var info = _step2.value;
  32724. console.log(" ".concat(info.type, ": ").concat(info.keyCount, " keys, ").concat(info.atlasCount, " atlases"));
  32725. }
  32726. } catch (err) {
  32727. _iterator2.e(err);
  32728. } finally {
  32729. _iterator2.f();
  32730. }
  32731. console.log('');
  32732. }
  32733. }
  32734. if (r.data.gc) {
  32735. console.log('Garbage Collect!');
  32736. r.data.gc = false;
  32737. drawing.gc();
  32738. }
  32739. }
  32740. var CRp$3 = {};
  32741. // @O Polygon drawing
  32742. CRp$3.drawPolygonPath = function (context, x, y, width, height, points) {
  32743. var halfW = width / 2;
  32744. var halfH = height / 2;
  32745. if (context.beginPath) {
  32746. context.beginPath();
  32747. }
  32748. context.moveTo(x + halfW * points[0], y + halfH * points[1]);
  32749. for (var i = 1; i < points.length / 2; i++) {
  32750. context.lineTo(x + halfW * points[i * 2], y + halfH * points[i * 2 + 1]);
  32751. }
  32752. context.closePath();
  32753. };
  32754. CRp$3.drawRoundPolygonPath = function (context, x, y, width, height, points, corners) {
  32755. corners.forEach(function (corner) {
  32756. return drawPreparedRoundCorner(context, corner);
  32757. });
  32758. context.closePath();
  32759. };
  32760. // Round rectangle drawing
  32761. CRp$3.drawRoundRectanglePath = function (context, x, y, width, height, radius) {
  32762. var halfWidth = width / 2;
  32763. var halfHeight = height / 2;
  32764. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : Math.min(radius, halfHeight, halfWidth);
  32765. if (context.beginPath) {
  32766. context.beginPath();
  32767. }
  32768. // Start at top middle
  32769. context.moveTo(x, y - halfHeight);
  32770. // Arc from middle top to right side
  32771. context.arcTo(x + halfWidth, y - halfHeight, x + halfWidth, y, cornerRadius);
  32772. // Arc from right side to bottom
  32773. context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  32774. // Arc from bottom to left side
  32775. context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  32776. // Arc from left side to topBorder
  32777. context.arcTo(x - halfWidth, y - halfHeight, x, y - halfHeight, cornerRadius);
  32778. // Join line
  32779. context.lineTo(x, y - halfHeight);
  32780. context.closePath();
  32781. };
  32782. CRp$3.drawBottomRoundRectanglePath = function (context, x, y, width, height, radius) {
  32783. var halfWidth = width / 2;
  32784. var halfHeight = height / 2;
  32785. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  32786. if (context.beginPath) {
  32787. context.beginPath();
  32788. }
  32789. // Start at top middle
  32790. context.moveTo(x, y - halfHeight);
  32791. context.lineTo(x + halfWidth, y - halfHeight);
  32792. context.lineTo(x + halfWidth, y);
  32793. context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  32794. context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  32795. context.lineTo(x - halfWidth, y - halfHeight);
  32796. context.lineTo(x, y - halfHeight);
  32797. context.closePath();
  32798. };
  32799. CRp$3.drawCutRectanglePath = function (context, x, y, width, height, points, corners) {
  32800. var halfWidth = width / 2;
  32801. var halfHeight = height / 2;
  32802. var cornerLength = corners === 'auto' ? getCutRectangleCornerLength() : corners;
  32803. if (context.beginPath) {
  32804. context.beginPath();
  32805. }
  32806. context.moveTo(x - halfWidth + cornerLength, y - halfHeight);
  32807. context.lineTo(x + halfWidth - cornerLength, y - halfHeight);
  32808. context.lineTo(x + halfWidth, y - halfHeight + cornerLength);
  32809. context.lineTo(x + halfWidth, y + halfHeight - cornerLength);
  32810. context.lineTo(x + halfWidth - cornerLength, y + halfHeight);
  32811. context.lineTo(x - halfWidth + cornerLength, y + halfHeight);
  32812. context.lineTo(x - halfWidth, y + halfHeight - cornerLength);
  32813. context.lineTo(x - halfWidth, y - halfHeight + cornerLength);
  32814. context.closePath();
  32815. };
  32816. CRp$3.drawBarrelPath = function (context, x, y, width, height) {
  32817. var halfWidth = width / 2;
  32818. var halfHeight = height / 2;
  32819. var xBegin = x - halfWidth;
  32820. var xEnd = x + halfWidth;
  32821. var yBegin = y - halfHeight;
  32822. var yEnd = y + halfHeight;
  32823. var barrelCurveConstants = getBarrelCurveConstants(width, height);
  32824. var wOffset = barrelCurveConstants.widthOffset;
  32825. var hOffset = barrelCurveConstants.heightOffset;
  32826. var ctrlPtXOffset = barrelCurveConstants.ctrlPtOffsetPct * wOffset;
  32827. if (context.beginPath) {
  32828. context.beginPath();
  32829. }
  32830. context.moveTo(xBegin, yBegin + hOffset);
  32831. context.lineTo(xBegin, yEnd - hOffset);
  32832. context.quadraticCurveTo(xBegin + ctrlPtXOffset, yEnd, xBegin + wOffset, yEnd);
  32833. context.lineTo(xEnd - wOffset, yEnd);
  32834. context.quadraticCurveTo(xEnd - ctrlPtXOffset, yEnd, xEnd, yEnd - hOffset);
  32835. context.lineTo(xEnd, yBegin + hOffset);
  32836. context.quadraticCurveTo(xEnd - ctrlPtXOffset, yBegin, xEnd - wOffset, yBegin);
  32837. context.lineTo(xBegin + wOffset, yBegin);
  32838. context.quadraticCurveTo(xBegin + ctrlPtXOffset, yBegin, xBegin, yBegin + hOffset);
  32839. context.closePath();
  32840. };
  32841. var sin0 = Math.sin(0);
  32842. var cos0 = Math.cos(0);
  32843. var sin = {};
  32844. var cos = {};
  32845. var ellipseStepSize = Math.PI / 40;
  32846. for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  32847. sin[i] = Math.sin(i);
  32848. cos[i] = Math.cos(i);
  32849. }
  32850. CRp$3.drawEllipsePath = function (context, centerX, centerY, width, height) {
  32851. if (context.beginPath) {
  32852. context.beginPath();
  32853. }
  32854. if (context.ellipse) {
  32855. context.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, 2 * Math.PI);
  32856. } else {
  32857. var xPos, yPos;
  32858. var rw = width / 2;
  32859. var rh = height / 2;
  32860. for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  32861. xPos = centerX - rw * sin[i] * sin0 + rw * cos[i] * cos0;
  32862. yPos = centerY + rh * cos[i] * sin0 + rh * sin[i] * cos0;
  32863. if (i === 0) {
  32864. context.moveTo(xPos, yPos);
  32865. } else {
  32866. context.lineTo(xPos, yPos);
  32867. }
  32868. }
  32869. }
  32870. context.closePath();
  32871. };
  32872. /* global atob, ArrayBuffer, Uint8Array, Blob */
  32873. var CRp$2 = {};
  32874. CRp$2.createBuffer = function (w, h) {
  32875. var buffer = document.createElement('canvas'); // eslint-disable-line no-undef
  32876. buffer.width = w;
  32877. buffer.height = h;
  32878. return [buffer, buffer.getContext('2d')];
  32879. };
  32880. CRp$2.bufferCanvasImage = function (options) {
  32881. var cy = this.cy;
  32882. var eles = cy.mutableElements();
  32883. var bb = eles.boundingBox();
  32884. var ctrRect = this.findContainerClientCoords();
  32885. var width = options.full ? Math.ceil(bb.w) : ctrRect[2];
  32886. var height = options.full ? Math.ceil(bb.h) : ctrRect[3];
  32887. var specdMaxDims = number$1(options.maxWidth) || number$1(options.maxHeight);
  32888. var pxRatio = this.getPixelRatio();
  32889. var scale = 1;
  32890. if (options.scale !== undefined) {
  32891. width *= options.scale;
  32892. height *= options.scale;
  32893. scale = options.scale;
  32894. } else if (specdMaxDims) {
  32895. var maxScaleW = Infinity;
  32896. var maxScaleH = Infinity;
  32897. if (number$1(options.maxWidth)) {
  32898. maxScaleW = scale * options.maxWidth / width;
  32899. }
  32900. if (number$1(options.maxHeight)) {
  32901. maxScaleH = scale * options.maxHeight / height;
  32902. }
  32903. scale = Math.min(maxScaleW, maxScaleH);
  32904. width *= scale;
  32905. height *= scale;
  32906. }
  32907. if (!specdMaxDims) {
  32908. width *= pxRatio;
  32909. height *= pxRatio;
  32910. scale *= pxRatio;
  32911. }
  32912. var buffCanvas = document.createElement('canvas'); // eslint-disable-line no-undef
  32913. buffCanvas.width = width;
  32914. buffCanvas.height = height;
  32915. buffCanvas.style.width = width + 'px';
  32916. buffCanvas.style.height = height + 'px';
  32917. var buffCxt = buffCanvas.getContext('2d');
  32918. // Rasterize the layers, but only if container has nonzero size
  32919. if (width > 0 && height > 0) {
  32920. buffCxt.clearRect(0, 0, width, height);
  32921. buffCxt.globalCompositeOperation = 'source-over';
  32922. var zsortedEles = this.getCachedZSortedEles();
  32923. if (options.full) {
  32924. // draw the full bounds of the graph
  32925. buffCxt.translate(-bb.x1 * scale, -bb.y1 * scale);
  32926. buffCxt.scale(scale, scale);
  32927. this.drawElements(buffCxt, zsortedEles);
  32928. buffCxt.scale(1 / scale, 1 / scale);
  32929. buffCxt.translate(bb.x1 * scale, bb.y1 * scale);
  32930. } else {
  32931. // draw the current view
  32932. var pan = cy.pan();
  32933. var translation = {
  32934. x: pan.x * scale,
  32935. y: pan.y * scale
  32936. };
  32937. scale *= cy.zoom();
  32938. buffCxt.translate(translation.x, translation.y);
  32939. buffCxt.scale(scale, scale);
  32940. this.drawElements(buffCxt, zsortedEles);
  32941. buffCxt.scale(1 / scale, 1 / scale);
  32942. buffCxt.translate(-translation.x, -translation.y);
  32943. }
  32944. // need to fill bg at end like this in order to fill cleared transparent pixels in jpgs
  32945. if (options.bg) {
  32946. buffCxt.globalCompositeOperation = 'destination-over';
  32947. buffCxt.fillStyle = options.bg;
  32948. buffCxt.rect(0, 0, width, height);
  32949. buffCxt.fill();
  32950. }
  32951. }
  32952. return buffCanvas;
  32953. };
  32954. function b64ToBlob(b64, mimeType) {
  32955. var bytes = atob(b64);
  32956. var buff = new ArrayBuffer(bytes.length);
  32957. var buffUint8 = new Uint8Array(buff);
  32958. for (var i = 0; i < bytes.length; i++) {
  32959. buffUint8[i] = bytes.charCodeAt(i);
  32960. }
  32961. return new Blob([buff], {
  32962. type: mimeType
  32963. });
  32964. }
  32965. function b64UriToB64(b64uri) {
  32966. var i = b64uri.indexOf(',');
  32967. return b64uri.substr(i + 1);
  32968. }
  32969. function output(options, canvas, mimeType) {
  32970. var getB64Uri = function getB64Uri() {
  32971. return canvas.toDataURL(mimeType, options.quality);
  32972. };
  32973. switch (options.output) {
  32974. case 'blob-promise':
  32975. return new Promise$1(function (resolve, reject) {
  32976. try {
  32977. canvas.toBlob(function (blob) {
  32978. if (blob != null) {
  32979. resolve(blob);
  32980. } else {
  32981. reject(new Error('`canvas.toBlob()` sent a null value in its callback'));
  32982. }
  32983. }, mimeType, options.quality);
  32984. } catch (err) {
  32985. reject(err);
  32986. }
  32987. });
  32988. case 'blob':
  32989. return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);
  32990. case 'base64':
  32991. return b64UriToB64(getB64Uri());
  32992. case 'base64uri':
  32993. default:
  32994. return getB64Uri();
  32995. }
  32996. }
  32997. CRp$2.png = function (options) {
  32998. return output(options, this.bufferCanvasImage(options), 'image/png');
  32999. };
  33000. CRp$2.jpg = function (options) {
  33001. return output(options, this.bufferCanvasImage(options), 'image/jpeg');
  33002. };
  33003. var CRp$1 = {};
  33004. CRp$1.nodeShapeImpl = function (name, context, centerX, centerY, width, height, points, corners) {
  33005. switch (name) {
  33006. case 'ellipse':
  33007. return this.drawEllipsePath(context, centerX, centerY, width, height);
  33008. case 'polygon':
  33009. return this.drawPolygonPath(context, centerX, centerY, width, height, points);
  33010. case 'round-polygon':
  33011. return this.drawRoundPolygonPath(context, centerX, centerY, width, height, points, corners);
  33012. case 'roundrectangle':
  33013. case 'round-rectangle':
  33014. return this.drawRoundRectanglePath(context, centerX, centerY, width, height, corners);
  33015. case 'cutrectangle':
  33016. case 'cut-rectangle':
  33017. return this.drawCutRectanglePath(context, centerX, centerY, width, height, points, corners);
  33018. case 'bottomroundrectangle':
  33019. case 'bottom-round-rectangle':
  33020. return this.drawBottomRoundRectanglePath(context, centerX, centerY, width, height, corners);
  33021. case 'barrel':
  33022. return this.drawBarrelPath(context, centerX, centerY, width, height);
  33023. }
  33024. };
  33025. var CR = CanvasRenderer;
  33026. var CRp = CanvasRenderer.prototype;
  33027. CRp.CANVAS_LAYERS = 3;
  33028. //
  33029. CRp.SELECT_BOX = 0;
  33030. CRp.DRAG = 1;
  33031. CRp.NODE = 2;
  33032. CRp.WEBGL = 3;
  33033. CRp.CANVAS_TYPES = ['2d', '2d', '2d', 'webgl2'];
  33034. CRp.BUFFER_COUNT = 3;
  33035. //
  33036. CRp.TEXTURE_BUFFER = 0;
  33037. CRp.MOTIONBLUR_BUFFER_NODE = 1;
  33038. CRp.MOTIONBLUR_BUFFER_DRAG = 2;
  33039. function CanvasRenderer(options) {
  33040. var r = this;
  33041. var containerWindow = r.cy.window();
  33042. var document = containerWindow.document;
  33043. if (options.webgl) {
  33044. CRp.CANVAS_LAYERS = r.CANVAS_LAYERS = 4;
  33045. console.log('webgl rendering enabled');
  33046. }
  33047. r.data = {
  33048. canvases: new Array(CRp.CANVAS_LAYERS),
  33049. contexts: new Array(CRp.CANVAS_LAYERS),
  33050. canvasNeedsRedraw: new Array(CRp.CANVAS_LAYERS),
  33051. bufferCanvases: new Array(CRp.BUFFER_COUNT),
  33052. bufferContexts: new Array(CRp.CANVAS_LAYERS)
  33053. };
  33054. var tapHlOffAttr = '-webkit-tap-highlight-color';
  33055. var tapHlOffStyle = 'rgba(0,0,0,0)';
  33056. r.data.canvasContainer = document.createElement('div'); // eslint-disable-line no-undef
  33057. var containerStyle = r.data.canvasContainer.style;
  33058. r.data.canvasContainer.style[tapHlOffAttr] = tapHlOffStyle;
  33059. containerStyle.position = 'relative';
  33060. containerStyle.zIndex = '0';
  33061. containerStyle.overflow = 'hidden';
  33062. var container = options.cy.container();
  33063. container.appendChild(r.data.canvasContainer);
  33064. container.style[tapHlOffAttr] = tapHlOffStyle;
  33065. var styleMap = {
  33066. '-webkit-user-select': 'none',
  33067. '-moz-user-select': '-moz-none',
  33068. 'user-select': 'none',
  33069. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',
  33070. 'outline-style': 'none'
  33071. };
  33072. if (ms()) {
  33073. styleMap['-ms-touch-action'] = 'none';
  33074. styleMap['touch-action'] = 'none';
  33075. }
  33076. for (var i = 0; i < CRp.CANVAS_LAYERS; i++) {
  33077. var canvas = r.data.canvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
  33078. var type = CRp.CANVAS_TYPES[i];
  33079. r.data.contexts[i] = canvas.getContext(type);
  33080. if (!r.data.contexts[i]) {
  33081. error('Could not create canvas of type ' + type);
  33082. }
  33083. Object.keys(styleMap).forEach(function (k) {
  33084. canvas.style[k] = styleMap[k];
  33085. });
  33086. canvas.style.position = 'absolute';
  33087. canvas.setAttribute('data-id', 'layer' + i);
  33088. canvas.style.zIndex = String(CRp.CANVAS_LAYERS - i);
  33089. r.data.canvasContainer.appendChild(canvas);
  33090. r.data.canvasNeedsRedraw[i] = false;
  33091. }
  33092. r.data.topCanvas = r.data.canvases[0];
  33093. r.data.canvases[CRp.NODE].setAttribute('data-id', 'layer' + CRp.NODE + '-node');
  33094. r.data.canvases[CRp.SELECT_BOX].setAttribute('data-id', 'layer' + CRp.SELECT_BOX + '-selectbox');
  33095. r.data.canvases[CRp.DRAG].setAttribute('data-id', 'layer' + CRp.DRAG + '-drag');
  33096. if (r.data.canvases[CRp.WEBGL]) {
  33097. r.data.canvases[CRp.WEBGL].setAttribute('data-id', 'layer' + CRp.WEBGL + '-webgl');
  33098. }
  33099. for (var i = 0; i < CRp.BUFFER_COUNT; i++) {
  33100. r.data.bufferCanvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
  33101. r.data.bufferContexts[i] = r.data.bufferCanvases[i].getContext('2d');
  33102. r.data.bufferCanvases[i].style.position = 'absolute';
  33103. r.data.bufferCanvases[i].setAttribute('data-id', 'buffer' + i);
  33104. r.data.bufferCanvases[i].style.zIndex = String(-i - 1);
  33105. r.data.bufferCanvases[i].style.visibility = 'hidden';
  33106. //r.data.canvasContainer.appendChild(r.data.bufferCanvases[i]);
  33107. }
  33108. r.pathsEnabled = true;
  33109. var emptyBb = makeBoundingBox();
  33110. var getBoxCenter = function getBoxCenter(bb) {
  33111. return {
  33112. x: (bb.x1 + bb.x2) / 2,
  33113. y: (bb.y1 + bb.y2) / 2
  33114. };
  33115. };
  33116. var getCenterOffset = function getCenterOffset(bb) {
  33117. return {
  33118. x: -bb.w / 2,
  33119. y: -bb.h / 2
  33120. };
  33121. };
  33122. var backgroundTimestampHasChanged = function backgroundTimestampHasChanged(ele) {
  33123. var _p = ele[0]._private;
  33124. var same = _p.oldBackgroundTimestamp === _p.backgroundTimestamp;
  33125. return !same;
  33126. };
  33127. var getStyleKey = function getStyleKey(ele) {
  33128. return ele[0]._private.nodeKey;
  33129. };
  33130. var getLabelKey = function getLabelKey(ele) {
  33131. return ele[0]._private.labelStyleKey;
  33132. };
  33133. var getSourceLabelKey = function getSourceLabelKey(ele) {
  33134. return ele[0]._private.sourceLabelStyleKey;
  33135. };
  33136. var getTargetLabelKey = function getTargetLabelKey(ele) {
  33137. return ele[0]._private.targetLabelStyleKey;
  33138. };
  33139. var drawElement = function drawElement(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33140. return r.drawElement(context, ele, bb, false, false, useEleOpacity);
  33141. };
  33142. var drawLabel = function drawLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33143. return r.drawElementText(context, ele, bb, scaledLabelShown, 'main', useEleOpacity);
  33144. };
  33145. var drawSourceLabel = function drawSourceLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33146. return r.drawElementText(context, ele, bb, scaledLabelShown, 'source', useEleOpacity);
  33147. };
  33148. var drawTargetLabel = function drawTargetLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33149. return r.drawElementText(context, ele, bb, scaledLabelShown, 'target', useEleOpacity);
  33150. };
  33151. var getElementBox = function getElementBox(ele) {
  33152. ele.boundingBox();
  33153. return ele[0]._private.bodyBounds;
  33154. };
  33155. var getLabelBox = function getLabelBox(ele) {
  33156. ele.boundingBox();
  33157. return ele[0]._private.labelBounds.main || emptyBb;
  33158. };
  33159. var getSourceLabelBox = function getSourceLabelBox(ele) {
  33160. ele.boundingBox();
  33161. return ele[0]._private.labelBounds.source || emptyBb;
  33162. };
  33163. var getTargetLabelBox = function getTargetLabelBox(ele) {
  33164. ele.boundingBox();
  33165. return ele[0]._private.labelBounds.target || emptyBb;
  33166. };
  33167. var isLabelVisibleAtScale = function isLabelVisibleAtScale(ele, scaledLabelShown) {
  33168. return scaledLabelShown;
  33169. };
  33170. var getElementRotationPoint = function getElementRotationPoint(ele) {
  33171. return getBoxCenter(getElementBox(ele));
  33172. };
  33173. var addTextMargin = function addTextMargin(prefix, pt, ele) {
  33174. var pre = prefix ? prefix + '-' : '';
  33175. return {
  33176. x: pt.x + ele.pstyle(pre + 'text-margin-x').pfValue,
  33177. y: pt.y + ele.pstyle(pre + 'text-margin-y').pfValue
  33178. };
  33179. };
  33180. var getRsPt = function getRsPt(ele, x, y) {
  33181. var rs = ele[0]._private.rscratch;
  33182. return {
  33183. x: rs[x],
  33184. y: rs[y]
  33185. };
  33186. };
  33187. var getLabelRotationPoint = function getLabelRotationPoint(ele) {
  33188. return addTextMargin('', getRsPt(ele, 'labelX', 'labelY'), ele);
  33189. };
  33190. var getSourceLabelRotationPoint = function getSourceLabelRotationPoint(ele) {
  33191. return addTextMargin('source', getRsPt(ele, 'sourceLabelX', 'sourceLabelY'), ele);
  33192. };
  33193. var getTargetLabelRotationPoint = function getTargetLabelRotationPoint(ele) {
  33194. return addTextMargin('target', getRsPt(ele, 'targetLabelX', 'targetLabelY'), ele);
  33195. };
  33196. var getElementRotationOffset = function getElementRotationOffset(ele) {
  33197. return getCenterOffset(getElementBox(ele));
  33198. };
  33199. var getSourceLabelRotationOffset = function getSourceLabelRotationOffset(ele) {
  33200. return getCenterOffset(getSourceLabelBox(ele));
  33201. };
  33202. var getTargetLabelRotationOffset = function getTargetLabelRotationOffset(ele) {
  33203. return getCenterOffset(getTargetLabelBox(ele));
  33204. };
  33205. var getLabelRotationOffset = function getLabelRotationOffset(ele) {
  33206. var bb = getLabelBox(ele);
  33207. var p = getCenterOffset(getLabelBox(ele));
  33208. if (ele.isNode()) {
  33209. switch (ele.pstyle('text-halign').value) {
  33210. case 'left':
  33211. p.x = -bb.w - (bb.leftPad || 0);
  33212. break;
  33213. case 'right':
  33214. p.x = -(bb.rightPad || 0);
  33215. break;
  33216. }
  33217. switch (ele.pstyle('text-valign').value) {
  33218. case 'top':
  33219. p.y = -bb.h - (bb.topPad || 0);
  33220. break;
  33221. case 'bottom':
  33222. p.y = -(bb.botPad || 0);
  33223. break;
  33224. }
  33225. }
  33226. return p;
  33227. };
  33228. var eleTxrCache = r.data.eleTxrCache = new ElementTextureCache(r, {
  33229. getKey: getStyleKey,
  33230. doesEleInvalidateKey: backgroundTimestampHasChanged,
  33231. drawElement: drawElement,
  33232. getBoundingBox: getElementBox,
  33233. getRotationPoint: getElementRotationPoint,
  33234. getRotationOffset: getElementRotationOffset,
  33235. allowEdgeTxrCaching: false,
  33236. allowParentTxrCaching: false
  33237. });
  33238. var lblTxrCache = r.data.lblTxrCache = new ElementTextureCache(r, {
  33239. getKey: getLabelKey,
  33240. drawElement: drawLabel,
  33241. getBoundingBox: getLabelBox,
  33242. getRotationPoint: getLabelRotationPoint,
  33243. getRotationOffset: getLabelRotationOffset,
  33244. isVisible: isLabelVisibleAtScale
  33245. });
  33246. var slbTxrCache = r.data.slbTxrCache = new ElementTextureCache(r, {
  33247. getKey: getSourceLabelKey,
  33248. drawElement: drawSourceLabel,
  33249. getBoundingBox: getSourceLabelBox,
  33250. getRotationPoint: getSourceLabelRotationPoint,
  33251. getRotationOffset: getSourceLabelRotationOffset,
  33252. isVisible: isLabelVisibleAtScale
  33253. });
  33254. var tlbTxrCache = r.data.tlbTxrCache = new ElementTextureCache(r, {
  33255. getKey: getTargetLabelKey,
  33256. drawElement: drawTargetLabel,
  33257. getBoundingBox: getTargetLabelBox,
  33258. getRotationPoint: getTargetLabelRotationPoint,
  33259. getRotationOffset: getTargetLabelRotationOffset,
  33260. isVisible: isLabelVisibleAtScale
  33261. });
  33262. var lyrTxrCache = r.data.lyrTxrCache = new LayeredTextureCache(r);
  33263. r.onUpdateEleCalcs(function invalidateTextureCaches(willDraw, eles) {
  33264. // each cache should check for sub-key diff to see that the update affects that cache particularly
  33265. eleTxrCache.invalidateElements(eles);
  33266. lblTxrCache.invalidateElements(eles);
  33267. slbTxrCache.invalidateElements(eles);
  33268. tlbTxrCache.invalidateElements(eles);
  33269. // any change invalidates the layers
  33270. lyrTxrCache.invalidateElements(eles);
  33271. // update the old bg timestamp so diffs can be done in the ele txr caches
  33272. for (var _i = 0; _i < eles.length; _i++) {
  33273. var _p = eles[_i]._private;
  33274. _p.oldBackgroundTimestamp = _p.backgroundTimestamp;
  33275. }
  33276. });
  33277. var refineInLayers = function refineInLayers(reqs) {
  33278. for (var i = 0; i < reqs.length; i++) {
  33279. lyrTxrCache.enqueueElementRefinement(reqs[i].ele);
  33280. }
  33281. };
  33282. eleTxrCache.onDequeue(refineInLayers);
  33283. lblTxrCache.onDequeue(refineInLayers);
  33284. slbTxrCache.onDequeue(refineInLayers);
  33285. tlbTxrCache.onDequeue(refineInLayers);
  33286. if (options.webgl) {
  33287. r.initWebgl(options, {
  33288. getStyleKey: getStyleKey,
  33289. getLabelKey: getLabelKey,
  33290. getSourceLabelKey: getSourceLabelKey,
  33291. getTargetLabelKey: getTargetLabelKey,
  33292. drawElement: drawElement,
  33293. drawLabel: drawLabel,
  33294. drawSourceLabel: drawSourceLabel,
  33295. drawTargetLabel: drawTargetLabel,
  33296. getElementBox: getElementBox,
  33297. getLabelBox: getLabelBox,
  33298. getSourceLabelBox: getSourceLabelBox,
  33299. getTargetLabelBox: getTargetLabelBox,
  33300. getElementRotationPoint: getElementRotationPoint,
  33301. getElementRotationOffset: getElementRotationOffset,
  33302. getLabelRotationPoint: getLabelRotationPoint,
  33303. getSourceLabelRotationPoint: getSourceLabelRotationPoint,
  33304. getTargetLabelRotationPoint: getTargetLabelRotationPoint,
  33305. getLabelRotationOffset: getLabelRotationOffset,
  33306. getSourceLabelRotationOffset: getSourceLabelRotationOffset,
  33307. getTargetLabelRotationOffset: getTargetLabelRotationOffset
  33308. });
  33309. }
  33310. }
  33311. CRp.redrawHint = function (group, bool) {
  33312. var r = this;
  33313. switch (group) {
  33314. case 'eles':
  33315. r.data.canvasNeedsRedraw[CRp.NODE] = bool;
  33316. break;
  33317. case 'drag':
  33318. r.data.canvasNeedsRedraw[CRp.DRAG] = bool;
  33319. break;
  33320. case 'select':
  33321. r.data.canvasNeedsRedraw[CRp.SELECT_BOX] = bool;
  33322. break;
  33323. case 'gc':
  33324. r.data.gc = true;
  33325. break;
  33326. }
  33327. };
  33328. // whether to use Path2D caching for drawing
  33329. var pathsImpld = typeof Path2D !== 'undefined';
  33330. CRp.path2dEnabled = function (on) {
  33331. if (on === undefined) {
  33332. return this.pathsEnabled;
  33333. }
  33334. this.pathsEnabled = on ? true : false;
  33335. };
  33336. CRp.usePaths = function () {
  33337. return pathsImpld && this.pathsEnabled;
  33338. };
  33339. CRp.setImgSmoothing = function (context, bool) {
  33340. if (context.imageSmoothingEnabled != null) {
  33341. context.imageSmoothingEnabled = bool;
  33342. } else {
  33343. context.webkitImageSmoothingEnabled = bool;
  33344. context.mozImageSmoothingEnabled = bool;
  33345. context.msImageSmoothingEnabled = bool;
  33346. }
  33347. };
  33348. CRp.getImgSmoothing = function (context) {
  33349. if (context.imageSmoothingEnabled != null) {
  33350. return context.imageSmoothingEnabled;
  33351. } else {
  33352. return context.webkitImageSmoothingEnabled || context.mozImageSmoothingEnabled || context.msImageSmoothingEnabled;
  33353. }
  33354. };
  33355. CRp.makeOffscreenCanvas = function (width, height) {
  33356. var canvas;
  33357. if ((typeof OffscreenCanvas === "undefined" ? "undefined" : _typeof(OffscreenCanvas)) !== ("undefined" )) {
  33358. canvas = new OffscreenCanvas(width, height);
  33359. } else {
  33360. var containerWindow = this.cy.window();
  33361. var document = containerWindow.document;
  33362. canvas = document.createElement('canvas'); // eslint-disable-line no-undef
  33363. canvas.width = width;
  33364. canvas.height = height;
  33365. }
  33366. return canvas;
  33367. };
  33368. [CRp$b, CRp$a, CRp$9, CRp$8, CRp$7, CRp$6, CRp$5, CRp$4, CRp$3, CRp$2, CRp$1].forEach(function (props) {
  33369. extend(CRp, props);
  33370. });
  33371. var renderer = [{
  33372. name: 'null',
  33373. impl: NullRenderer
  33374. }, {
  33375. name: 'base',
  33376. impl: BR
  33377. }, {
  33378. name: 'canvas',
  33379. impl: CR
  33380. }];
  33381. var incExts = [{
  33382. type: 'layout',
  33383. extensions: layout
  33384. }, {
  33385. type: 'renderer',
  33386. extensions: renderer
  33387. }];
  33388. // registered extensions to cytoscape, indexed by name
  33389. var extensions = {};
  33390. // registered modules for extensions, indexed by name
  33391. var modules = {};
  33392. function setExtension(type, name, registrant) {
  33393. var ext = registrant;
  33394. var overrideErr = function overrideErr(field) {
  33395. warn('Can not register `' + name + '` for `' + type + '` since `' + field + '` already exists in the prototype and can not be overridden');
  33396. };
  33397. if (type === 'core') {
  33398. if (Core.prototype[name]) {
  33399. return overrideErr(name);
  33400. } else {
  33401. Core.prototype[name] = registrant;
  33402. }
  33403. } else if (type === 'collection') {
  33404. if (Collection.prototype[name]) {
  33405. return overrideErr(name);
  33406. } else {
  33407. Collection.prototype[name] = registrant;
  33408. }
  33409. } else if (type === 'layout') {
  33410. // fill in missing layout functions in the prototype
  33411. var Layout = function Layout(options) {
  33412. this.options = options;
  33413. registrant.call(this, options);
  33414. // make sure layout has _private for use w/ std apis like .on()
  33415. if (!plainObject(this._private)) {
  33416. this._private = {};
  33417. }
  33418. this._private.cy = options.cy;
  33419. this._private.listeners = [];
  33420. this.createEmitter();
  33421. };
  33422. var layoutProto = Layout.prototype = Object.create(registrant.prototype);
  33423. var optLayoutFns = [];
  33424. for (var i = 0; i < optLayoutFns.length; i++) {
  33425. var fnName = optLayoutFns[i];
  33426. layoutProto[fnName] = layoutProto[fnName] || function () {
  33427. return this;
  33428. };
  33429. }
  33430. // either .start() or .run() is defined, so autogen the other
  33431. if (layoutProto.start && !layoutProto.run) {
  33432. layoutProto.run = function () {
  33433. this.start();
  33434. return this;
  33435. };
  33436. } else if (!layoutProto.start && layoutProto.run) {
  33437. layoutProto.start = function () {
  33438. this.run();
  33439. return this;
  33440. };
  33441. }
  33442. var regStop = registrant.prototype.stop;
  33443. layoutProto.stop = function () {
  33444. var opts = this.options;
  33445. if (opts && opts.animate) {
  33446. var anis = this.animations;
  33447. if (anis) {
  33448. for (var _i = 0; _i < anis.length; _i++) {
  33449. anis[_i].stop();
  33450. }
  33451. }
  33452. }
  33453. if (regStop) {
  33454. regStop.call(this);
  33455. } else {
  33456. this.emit('layoutstop');
  33457. }
  33458. return this;
  33459. };
  33460. if (!layoutProto.destroy) {
  33461. layoutProto.destroy = function () {
  33462. return this;
  33463. };
  33464. }
  33465. layoutProto.cy = function () {
  33466. return this._private.cy;
  33467. };
  33468. var getCy = function getCy(layout) {
  33469. return layout._private.cy;
  33470. };
  33471. var emitterOpts = {
  33472. addEventFields: function addEventFields(layout, evt) {
  33473. evt.layout = layout;
  33474. evt.cy = getCy(layout);
  33475. evt.target = layout;
  33476. },
  33477. bubble: function bubble() {
  33478. return true;
  33479. },
  33480. parent: function parent(layout) {
  33481. return getCy(layout);
  33482. }
  33483. };
  33484. extend(layoutProto, {
  33485. createEmitter: function createEmitter() {
  33486. this._private.emitter = new Emitter(emitterOpts, this);
  33487. return this;
  33488. },
  33489. emitter: function emitter() {
  33490. return this._private.emitter;
  33491. },
  33492. on: function on(evt, cb) {
  33493. this.emitter().on(evt, cb);
  33494. return this;
  33495. },
  33496. one: function one(evt, cb) {
  33497. this.emitter().one(evt, cb);
  33498. return this;
  33499. },
  33500. once: function once(evt, cb) {
  33501. this.emitter().one(evt, cb);
  33502. return this;
  33503. },
  33504. removeListener: function removeListener(evt, cb) {
  33505. this.emitter().removeListener(evt, cb);
  33506. return this;
  33507. },
  33508. removeAllListeners: function removeAllListeners() {
  33509. this.emitter().removeAllListeners();
  33510. return this;
  33511. },
  33512. emit: function emit(evt, params) {
  33513. this.emitter().emit(evt, params);
  33514. return this;
  33515. }
  33516. });
  33517. define.eventAliasesOn(layoutProto);
  33518. ext = Layout; // replace with our wrapped layout
  33519. } else if (type === 'renderer' && name !== 'null' && name !== 'base') {
  33520. // user registered renderers inherit from base
  33521. var BaseRenderer = getExtension('renderer', 'base');
  33522. var bProto = BaseRenderer.prototype;
  33523. var RegistrantRenderer = registrant;
  33524. var rProto = registrant.prototype;
  33525. var Renderer = function Renderer() {
  33526. BaseRenderer.apply(this, arguments);
  33527. RegistrantRenderer.apply(this, arguments);
  33528. };
  33529. var proto = Renderer.prototype;
  33530. for (var pName in bProto) {
  33531. var pVal = bProto[pName];
  33532. var existsInR = rProto[pName] != null;
  33533. if (existsInR) {
  33534. return overrideErr(pName);
  33535. }
  33536. proto[pName] = pVal; // take impl from base
  33537. }
  33538. for (var _pName in rProto) {
  33539. proto[_pName] = rProto[_pName]; // take impl from registrant
  33540. }
  33541. bProto.clientFunctions.forEach(function (name) {
  33542. proto[name] = proto[name] || function () {
  33543. error('Renderer does not implement `renderer.' + name + '()` on its prototype');
  33544. };
  33545. });
  33546. ext = Renderer;
  33547. } else if (type === '__proto__' || type === 'constructor' || type === 'prototype') {
  33548. // to avoid potential prototype pollution
  33549. return error(type + ' is an illegal type to be registered, possibly lead to prototype pollutions');
  33550. }
  33551. return setMap({
  33552. map: extensions,
  33553. keys: [type, name],
  33554. value: ext
  33555. });
  33556. }
  33557. function getExtension(type, name) {
  33558. return getMap({
  33559. map: extensions,
  33560. keys: [type, name]
  33561. });
  33562. }
  33563. function setModule(type, name, moduleType, moduleName, registrant) {
  33564. return setMap({
  33565. map: modules,
  33566. keys: [type, name, moduleType, moduleName],
  33567. value: registrant
  33568. });
  33569. }
  33570. function getModule(type, name, moduleType, moduleName) {
  33571. return getMap({
  33572. map: modules,
  33573. keys: [type, name, moduleType, moduleName]
  33574. });
  33575. }
  33576. var extension = function extension() {
  33577. // e.g. extension('renderer', 'svg')
  33578. if (arguments.length === 2) {
  33579. return getExtension.apply(null, arguments);
  33580. }
  33581. // e.g. extension('renderer', 'svg', { ... })
  33582. else if (arguments.length === 3) {
  33583. return setExtension.apply(null, arguments);
  33584. }
  33585. // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse')
  33586. else if (arguments.length === 4) {
  33587. return getModule.apply(null, arguments);
  33588. }
  33589. // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse', { ... })
  33590. else if (arguments.length === 5) {
  33591. return setModule.apply(null, arguments);
  33592. } else {
  33593. error('Invalid extension access syntax');
  33594. }
  33595. };
  33596. // allows a core instance to access extensions internally
  33597. Core.prototype.extension = extension;
  33598. // included extensions
  33599. incExts.forEach(function (group) {
  33600. group.extensions.forEach(function (ext) {
  33601. setExtension(group.type, ext.name, ext.impl);
  33602. });
  33603. });
  33604. // a dummy stylesheet object that doesn't need a reference to the core
  33605. // (useful for init)
  33606. var _Stylesheet = function Stylesheet() {
  33607. if (!(this instanceof _Stylesheet)) {
  33608. return new _Stylesheet();
  33609. }
  33610. this.length = 0;
  33611. };
  33612. var sheetfn = _Stylesheet.prototype;
  33613. sheetfn.instanceString = function () {
  33614. return 'stylesheet';
  33615. };
  33616. // just store the selector to be parsed later
  33617. sheetfn.selector = function (selector) {
  33618. var i = this.length++;
  33619. this[i] = {
  33620. selector: selector,
  33621. properties: []
  33622. };
  33623. return this; // chaining
  33624. };
  33625. // just store the property to be parsed later
  33626. sheetfn.css = function (name, value) {
  33627. var i = this.length - 1;
  33628. if (string(name)) {
  33629. this[i].properties.push({
  33630. name: name,
  33631. value: value
  33632. });
  33633. } else if (plainObject(name)) {
  33634. var map = name;
  33635. var propNames = Object.keys(map);
  33636. for (var j = 0; j < propNames.length; j++) {
  33637. var key = propNames[j];
  33638. var mapVal = map[key];
  33639. if (mapVal == null) {
  33640. continue;
  33641. }
  33642. var prop = _Style.properties[key] || _Style.properties[dash2camel(key)];
  33643. if (prop == null) {
  33644. continue;
  33645. }
  33646. var _name = prop.name;
  33647. var _value = mapVal;
  33648. this[i].properties.push({
  33649. name: _name,
  33650. value: _value
  33651. });
  33652. }
  33653. }
  33654. return this; // chaining
  33655. };
  33656. sheetfn.style = sheetfn.css;
  33657. // generate a real style object from the dummy stylesheet
  33658. sheetfn.generateStyle = function (cy) {
  33659. var style = new _Style(cy);
  33660. return this.appendToStyle(style);
  33661. };
  33662. // append a dummy stylesheet object on a real style object
  33663. sheetfn.appendToStyle = function (style) {
  33664. for (var i = 0; i < this.length; i++) {
  33665. var context = this[i];
  33666. var selector = context.selector;
  33667. var props = context.properties;
  33668. style.selector(selector); // apply selector
  33669. for (var j = 0; j < props.length; j++) {
  33670. var prop = props[j];
  33671. style.css(prop.name, prop.value); // apply property
  33672. }
  33673. }
  33674. return style;
  33675. };
  33676. var version = "3.33.2";
  33677. var cytoscape = function cytoscape(options) {
  33678. // if no options specified, use default
  33679. if (options === undefined) {
  33680. options = {};
  33681. }
  33682. // create instance
  33683. if (plainObject(options)) {
  33684. return new Core(options);
  33685. }
  33686. // allow for registration of extensions
  33687. else if (string(options)) {
  33688. return extension.apply(extension, arguments);
  33689. }
  33690. };
  33691. // e.g. cytoscape.use( require('cytoscape-foo'), bar )
  33692. cytoscape.use = function (ext) {
  33693. var args = Array.prototype.slice.call(arguments, 1); // args to pass to ext
  33694. args.unshift(cytoscape); // cytoscape is first arg to ext
  33695. ext.apply(null, args);
  33696. return this;
  33697. };
  33698. cytoscape.warnings = function (bool) {
  33699. return warnings(bool);
  33700. };
  33701. // replaced by build system
  33702. cytoscape.version = version;
  33703. // expose public apis (mostly for extensions)
  33704. cytoscape.stylesheet = cytoscape.Stylesheet = _Stylesheet;
  33705. module.exports = cytoscape;