cytoscape.umd.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599
  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. (function (global, factory) {
  23. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  24. typeof define === 'function' && define.amd ? define(factory) :
  25. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.cytoscape = factory());
  26. })(this, (function () { 'use strict';
  27. function _arrayLikeToArray(r, a) {
  28. (null == a || a > r.length) && (a = r.length);
  29. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  30. return n;
  31. }
  32. function _arrayWithHoles(r) {
  33. if (Array.isArray(r)) return r;
  34. }
  35. function _arrayWithoutHoles(r) {
  36. if (Array.isArray(r)) return _arrayLikeToArray(r);
  37. }
  38. function _classCallCheck(a, n) {
  39. if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
  40. }
  41. function _defineProperties(e, r) {
  42. for (var t = 0; t < r.length; t++) {
  43. var o = r[t];
  44. o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  45. }
  46. }
  47. function _createClass(e, r, t) {
  48. return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
  49. writable: false
  50. }), e;
  51. }
  52. function _createForOfIteratorHelper(r, e) {
  53. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  54. if (!t) {
  55. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
  56. t && (r = t);
  57. var n = 0,
  58. F = function () {};
  59. return {
  60. s: F,
  61. n: function () {
  62. return n >= r.length ? {
  63. done: true
  64. } : {
  65. done: false,
  66. value: r[n++]
  67. };
  68. },
  69. e: function (r) {
  70. throw r;
  71. },
  72. f: F
  73. };
  74. }
  75. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  76. }
  77. var o,
  78. a = true,
  79. u = false;
  80. return {
  81. s: function () {
  82. t = t.call(r);
  83. },
  84. n: function () {
  85. var r = t.next();
  86. return a = r.done, r;
  87. },
  88. e: function (r) {
  89. u = true, o = r;
  90. },
  91. f: function () {
  92. try {
  93. a || null == t.return || t.return();
  94. } finally {
  95. if (u) throw o;
  96. }
  97. }
  98. };
  99. }
  100. function _defineProperty$1(e, r, t) {
  101. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  102. value: t,
  103. enumerable: true,
  104. configurable: true,
  105. writable: true
  106. }) : e[r] = t, e;
  107. }
  108. function _iterableToArray(r) {
  109. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  110. }
  111. function _iterableToArrayLimit(r, l) {
  112. var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  113. if (null != t) {
  114. var e,
  115. n,
  116. i,
  117. u,
  118. a = [],
  119. f = true,
  120. o = false;
  121. try {
  122. if (i = (t = t.call(r)).next, 0 === l) {
  123. if (Object(t) !== t) return;
  124. f = !1;
  125. } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
  126. } catch (r) {
  127. o = true, n = r;
  128. } finally {
  129. try {
  130. if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
  131. } finally {
  132. if (o) throw n;
  133. }
  134. }
  135. return a;
  136. }
  137. }
  138. function _nonIterableRest() {
  139. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  140. }
  141. function _nonIterableSpread() {
  142. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  143. }
  144. function _slicedToArray(r, e) {
  145. return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
  146. }
  147. function _toConsumableArray(r) {
  148. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  149. }
  150. function _toPrimitive(t, r) {
  151. if ("object" != typeof t || !t) return t;
  152. var e = t[Symbol.toPrimitive];
  153. if (undefined !== e) {
  154. var i = e.call(t, r);
  155. if ("object" != typeof i) return i;
  156. throw new TypeError("@@toPrimitive must return a primitive value.");
  157. }
  158. return (String )(t);
  159. }
  160. function _toPropertyKey(t) {
  161. var i = _toPrimitive(t, "string");
  162. return "symbol" == typeof i ? i : i + "";
  163. }
  164. function _typeof(o) {
  165. "@babel/helpers - typeof";
  166. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  167. return typeof o;
  168. } : function (o) {
  169. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  170. }, _typeof(o);
  171. }
  172. function _unsupportedIterableToArray(r, a) {
  173. if (r) {
  174. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  175. var t = {}.toString.call(r).slice(8, -1);
  176. 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;
  177. }
  178. }
  179. var _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef
  180. var navigator = _window ? _window.navigator : null;
  181. _window ? _window.document : null;
  182. var typeofstr = _typeof('');
  183. var typeofobj = _typeof({});
  184. var typeoffn = _typeof(function () {});
  185. var typeofhtmlele = typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement);
  186. var instanceStr = function instanceStr(obj) {
  187. return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;
  188. };
  189. var string = function string(obj) {
  190. return obj != null && _typeof(obj) == typeofstr;
  191. };
  192. var fn$6 = function fn(obj) {
  193. return obj != null && _typeof(obj) === typeoffn;
  194. };
  195. var array = function array(obj) {
  196. return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);
  197. };
  198. var plainObject = function plainObject(obj) {
  199. return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;
  200. };
  201. var object = function object(obj) {
  202. return obj != null && _typeof(obj) === typeofobj;
  203. };
  204. var number$1 = function number(obj) {
  205. return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);
  206. };
  207. var integer = function integer(obj) {
  208. return number$1(obj) && Math.floor(obj) === obj;
  209. };
  210. var htmlElement = function htmlElement(obj) {
  211. if ('undefined' === typeofhtmlele) {
  212. return undefined;
  213. } else {
  214. return null != obj && obj instanceof HTMLElement;
  215. }
  216. };
  217. var elementOrCollection = function elementOrCollection(obj) {
  218. return element(obj) || collection(obj);
  219. };
  220. var element = function element(obj) {
  221. return instanceStr(obj) === 'collection' && obj._private.single;
  222. };
  223. var collection = function collection(obj) {
  224. return instanceStr(obj) === 'collection' && !obj._private.single;
  225. };
  226. var core = function core(obj) {
  227. return instanceStr(obj) === 'core';
  228. };
  229. var stylesheet = function stylesheet(obj) {
  230. return instanceStr(obj) === 'stylesheet';
  231. };
  232. var event = function event(obj) {
  233. return instanceStr(obj) === 'event';
  234. };
  235. var emptyString = function emptyString(obj) {
  236. if (obj === undefined || obj === null) {
  237. // null is empty
  238. return true;
  239. } else if (obj === '' || obj.match(/^\s+$/)) {
  240. return true; // empty string is empty
  241. }
  242. return false; // otherwise, we don't know what we've got
  243. };
  244. var domElement = function domElement(obj) {
  245. if (typeof HTMLElement === 'undefined') {
  246. return false; // we're not in a browser so it doesn't matter
  247. } else {
  248. return obj instanceof HTMLElement;
  249. }
  250. };
  251. var boundingBox = function boundingBox(obj) {
  252. return plainObject(obj) && number$1(obj.x1) && number$1(obj.x2) && number$1(obj.y1) && number$1(obj.y2);
  253. };
  254. var promise = function promise(obj) {
  255. return object(obj) && fn$6(obj.then);
  256. };
  257. var ms = function ms() {
  258. return navigator && navigator.userAgent.match(/msie|trident|edge/i);
  259. }; // probably a better way to detect this...
  260. var memoize = function memoize(fn, keyFn) {
  261. if (!keyFn) {
  262. keyFn = function keyFn() {
  263. if (arguments.length === 1) {
  264. return arguments[0];
  265. } else if (arguments.length === 0) {
  266. return 'undefined';
  267. }
  268. var args = [];
  269. for (var i = 0; i < arguments.length; i++) {
  270. args.push(arguments[i]);
  271. }
  272. return args.join('$');
  273. };
  274. }
  275. var _memoizedFn = function memoizedFn() {
  276. var self = this;
  277. var args = arguments;
  278. var ret;
  279. var k = keyFn.apply(self, args);
  280. var cache = _memoizedFn.cache;
  281. if (!(ret = cache[k])) {
  282. ret = cache[k] = fn.apply(self, args);
  283. }
  284. return ret;
  285. };
  286. _memoizedFn.cache = {};
  287. return _memoizedFn;
  288. };
  289. var camel2dash = memoize(function (str) {
  290. return str.replace(/([A-Z])/g, function (v) {
  291. return '-' + v.toLowerCase();
  292. });
  293. });
  294. var dash2camel = memoize(function (str) {
  295. return str.replace(/(-\w)/g, function (v) {
  296. return v[1].toUpperCase();
  297. });
  298. });
  299. var prependCamel = memoize(function (prefix, str) {
  300. return prefix + str[0].toUpperCase() + str.substring(1);
  301. }, function (prefix, str) {
  302. return prefix + '$' + str;
  303. });
  304. var capitalize = function capitalize(str) {
  305. if (emptyString(str)) {
  306. return str;
  307. }
  308. return str.charAt(0).toUpperCase() + str.substring(1);
  309. };
  310. var endsWith = function endsWith(string, suffix) {
  311. return string.slice(-1 * suffix.length) === suffix;
  312. };
  313. var number = '(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))';
  314. var rgba = 'rgb[a]?\\((' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)(?:\\s*,\\s*(' + number + '))?\\)';
  315. var rgbaNoBackRefs = 'rgb[a]?\\((?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)(?:\\s*,\\s*(?:' + number + '))?\\)';
  316. var hsla = 'hsl[a]?\\((' + number + ')\\s*,\\s*(' + number + '[%])\\s*,\\s*(' + number + '[%])(?:\\s*,\\s*(' + number + '))?\\)';
  317. var hslaNoBackRefs = 'hsl[a]?\\((?:' + number + ')\\s*,\\s*(?:' + number + '[%])\\s*,\\s*(?:' + number + '[%])(?:\\s*,\\s*(?:' + number + '))?\\)';
  318. var hex3 = '\\#[0-9a-fA-F]{3}';
  319. var hex6 = '\\#[0-9a-fA-F]{6}';
  320. var ascending = function ascending(a, b) {
  321. if (a < b) {
  322. return -1;
  323. } else if (a > b) {
  324. return 1;
  325. } else {
  326. return 0;
  327. }
  328. };
  329. var descending = function descending(a, b) {
  330. return -1 * ascending(a, b);
  331. };
  332. var extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
  333. var args = arguments;
  334. for (var i = 1; i < args.length; i++) {
  335. var obj = args[i];
  336. if (obj == null) {
  337. continue;
  338. }
  339. var keys = Object.keys(obj);
  340. for (var j = 0; j < keys.length; j++) {
  341. var k = keys[j];
  342. tgt[k] = obj[k];
  343. }
  344. }
  345. return tgt;
  346. };
  347. // get [r, g, b] from #abc or #aabbcc
  348. var hex2tuple = function hex2tuple(hex) {
  349. if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {
  350. return;
  351. }
  352. var shortHex = hex.length === 4;
  353. var r, g, b;
  354. var base = 16;
  355. if (shortHex) {
  356. r = parseInt(hex[1] + hex[1], base);
  357. g = parseInt(hex[2] + hex[2], base);
  358. b = parseInt(hex[3] + hex[3], base);
  359. } else {
  360. r = parseInt(hex[1] + hex[2], base);
  361. g = parseInt(hex[3] + hex[4], base);
  362. b = parseInt(hex[5] + hex[6], base);
  363. }
  364. return [r, g, b];
  365. };
  366. // get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)
  367. var hsl2tuple = function hsl2tuple(hsl) {
  368. var ret;
  369. var h, s, l, a, r, g, b;
  370. function hue2rgb(p, q, t) {
  371. if (t < 0) t += 1;
  372. if (t > 1) t -= 1;
  373. if (t < 1 / 6) return p + (q - p) * 6 * t;
  374. if (t < 1 / 2) return q;
  375. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  376. return p;
  377. }
  378. var m = new RegExp('^' + hsla + '$').exec(hsl);
  379. if (m) {
  380. // get hue
  381. h = parseInt(m[1]);
  382. if (h < 0) {
  383. h = (360 - -1 * h % 360) % 360;
  384. } else if (h > 360) {
  385. h = h % 360;
  386. }
  387. h /= 360; // normalise on [0, 1]
  388. s = parseFloat(m[2]);
  389. if (s < 0 || s > 100) {
  390. return;
  391. } // saturation is [0, 100]
  392. s = s / 100; // normalise on [0, 1]
  393. l = parseFloat(m[3]);
  394. if (l < 0 || l > 100) {
  395. return;
  396. } // lightness is [0, 100]
  397. l = l / 100; // normalise on [0, 1]
  398. a = m[4];
  399. if (a !== undefined) {
  400. a = parseFloat(a);
  401. if (a < 0 || a > 1) {
  402. return;
  403. } // alpha is [0, 1]
  404. }
  405. // now, convert to rgb
  406. // code from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  407. if (s === 0) {
  408. r = g = b = Math.round(l * 255); // achromatic
  409. } else {
  410. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  411. var p = 2 * l - q;
  412. r = Math.round(255 * hue2rgb(p, q, h + 1 / 3));
  413. g = Math.round(255 * hue2rgb(p, q, h));
  414. b = Math.round(255 * hue2rgb(p, q, h - 1 / 3));
  415. }
  416. ret = [r, g, b, a];
  417. }
  418. return ret;
  419. };
  420. // get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)
  421. var rgb2tuple = function rgb2tuple(rgb) {
  422. var ret;
  423. var m = new RegExp('^' + rgba + '$').exec(rgb);
  424. if (m) {
  425. ret = [];
  426. var isPct = [];
  427. for (var i = 1; i <= 3; i++) {
  428. var channel = m[i];
  429. if (channel[channel.length - 1] === '%') {
  430. isPct[i] = true;
  431. }
  432. channel = parseFloat(channel);
  433. if (isPct[i]) {
  434. channel = channel / 100 * 255; // normalise to [0, 255]
  435. }
  436. if (channel < 0 || channel > 255) {
  437. return;
  438. } // invalid channel value
  439. ret.push(Math.floor(channel));
  440. }
  441. var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];
  442. var allArePct = isPct[1] && isPct[2] && isPct[3];
  443. if (atLeastOneIsPct && !allArePct) {
  444. return;
  445. } // must all be percent values if one is
  446. var alpha = m[4];
  447. if (alpha !== undefined) {
  448. alpha = parseFloat(alpha);
  449. if (alpha < 0 || alpha > 1) {
  450. return;
  451. } // invalid alpha value
  452. ret.push(alpha);
  453. }
  454. }
  455. return ret;
  456. };
  457. var colorname2tuple = function colorname2tuple(color) {
  458. return colors[color.toLowerCase()];
  459. };
  460. var color2tuple = function color2tuple(color) {
  461. return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);
  462. };
  463. var colors = {
  464. // special colour names
  465. transparent: [0, 0, 0, 0],
  466. // NB alpha === 0
  467. // regular colours
  468. aliceblue: [240, 248, 255],
  469. antiquewhite: [250, 235, 215],
  470. aqua: [0, 255, 255],
  471. aquamarine: [127, 255, 212],
  472. azure: [240, 255, 255],
  473. beige: [245, 245, 220],
  474. bisque: [255, 228, 196],
  475. black: [0, 0, 0],
  476. blanchedalmond: [255, 235, 205],
  477. blue: [0, 0, 255],
  478. blueviolet: [138, 43, 226],
  479. brown: [165, 42, 42],
  480. burlywood: [222, 184, 135],
  481. cadetblue: [95, 158, 160],
  482. chartreuse: [127, 255, 0],
  483. chocolate: [210, 105, 30],
  484. coral: [255, 127, 80],
  485. cornflowerblue: [100, 149, 237],
  486. cornsilk: [255, 248, 220],
  487. crimson: [220, 20, 60],
  488. cyan: [0, 255, 255],
  489. darkblue: [0, 0, 139],
  490. darkcyan: [0, 139, 139],
  491. darkgoldenrod: [184, 134, 11],
  492. darkgray: [169, 169, 169],
  493. darkgreen: [0, 100, 0],
  494. darkgrey: [169, 169, 169],
  495. darkkhaki: [189, 183, 107],
  496. darkmagenta: [139, 0, 139],
  497. darkolivegreen: [85, 107, 47],
  498. darkorange: [255, 140, 0],
  499. darkorchid: [153, 50, 204],
  500. darkred: [139, 0, 0],
  501. darksalmon: [233, 150, 122],
  502. darkseagreen: [143, 188, 143],
  503. darkslateblue: [72, 61, 139],
  504. darkslategray: [47, 79, 79],
  505. darkslategrey: [47, 79, 79],
  506. darkturquoise: [0, 206, 209],
  507. darkviolet: [148, 0, 211],
  508. deeppink: [255, 20, 147],
  509. deepskyblue: [0, 191, 255],
  510. dimgray: [105, 105, 105],
  511. dimgrey: [105, 105, 105],
  512. dodgerblue: [30, 144, 255],
  513. firebrick: [178, 34, 34],
  514. floralwhite: [255, 250, 240],
  515. forestgreen: [34, 139, 34],
  516. fuchsia: [255, 0, 255],
  517. gainsboro: [220, 220, 220],
  518. ghostwhite: [248, 248, 255],
  519. gold: [255, 215, 0],
  520. goldenrod: [218, 165, 32],
  521. gray: [128, 128, 128],
  522. grey: [128, 128, 128],
  523. green: [0, 128, 0],
  524. greenyellow: [173, 255, 47],
  525. honeydew: [240, 255, 240],
  526. hotpink: [255, 105, 180],
  527. indianred: [205, 92, 92],
  528. indigo: [75, 0, 130],
  529. ivory: [255, 255, 240],
  530. khaki: [240, 230, 140],
  531. lavender: [230, 230, 250],
  532. lavenderblush: [255, 240, 245],
  533. lawngreen: [124, 252, 0],
  534. lemonchiffon: [255, 250, 205],
  535. lightblue: [173, 216, 230],
  536. lightcoral: [240, 128, 128],
  537. lightcyan: [224, 255, 255],
  538. lightgoldenrodyellow: [250, 250, 210],
  539. lightgray: [211, 211, 211],
  540. lightgreen: [144, 238, 144],
  541. lightgrey: [211, 211, 211],
  542. lightpink: [255, 182, 193],
  543. lightsalmon: [255, 160, 122],
  544. lightseagreen: [32, 178, 170],
  545. lightskyblue: [135, 206, 250],
  546. lightslategray: [119, 136, 153],
  547. lightslategrey: [119, 136, 153],
  548. lightsteelblue: [176, 196, 222],
  549. lightyellow: [255, 255, 224],
  550. lime: [0, 255, 0],
  551. limegreen: [50, 205, 50],
  552. linen: [250, 240, 230],
  553. magenta: [255, 0, 255],
  554. maroon: [128, 0, 0],
  555. mediumaquamarine: [102, 205, 170],
  556. mediumblue: [0, 0, 205],
  557. mediumorchid: [186, 85, 211],
  558. mediumpurple: [147, 112, 219],
  559. mediumseagreen: [60, 179, 113],
  560. mediumslateblue: [123, 104, 238],
  561. mediumspringgreen: [0, 250, 154],
  562. mediumturquoise: [72, 209, 204],
  563. mediumvioletred: [199, 21, 133],
  564. midnightblue: [25, 25, 112],
  565. mintcream: [245, 255, 250],
  566. mistyrose: [255, 228, 225],
  567. moccasin: [255, 228, 181],
  568. navajowhite: [255, 222, 173],
  569. navy: [0, 0, 128],
  570. oldlace: [253, 245, 230],
  571. olive: [128, 128, 0],
  572. olivedrab: [107, 142, 35],
  573. orange: [255, 165, 0],
  574. orangered: [255, 69, 0],
  575. orchid: [218, 112, 214],
  576. palegoldenrod: [238, 232, 170],
  577. palegreen: [152, 251, 152],
  578. paleturquoise: [175, 238, 238],
  579. palevioletred: [219, 112, 147],
  580. papayawhip: [255, 239, 213],
  581. peachpuff: [255, 218, 185],
  582. peru: [205, 133, 63],
  583. pink: [255, 192, 203],
  584. plum: [221, 160, 221],
  585. powderblue: [176, 224, 230],
  586. purple: [128, 0, 128],
  587. red: [255, 0, 0],
  588. rosybrown: [188, 143, 143],
  589. royalblue: [65, 105, 225],
  590. saddlebrown: [139, 69, 19],
  591. salmon: [250, 128, 114],
  592. sandybrown: [244, 164, 96],
  593. seagreen: [46, 139, 87],
  594. seashell: [255, 245, 238],
  595. sienna: [160, 82, 45],
  596. silver: [192, 192, 192],
  597. skyblue: [135, 206, 235],
  598. slateblue: [106, 90, 205],
  599. slategray: [112, 128, 144],
  600. slategrey: [112, 128, 144],
  601. snow: [255, 250, 250],
  602. springgreen: [0, 255, 127],
  603. steelblue: [70, 130, 180],
  604. tan: [210, 180, 140],
  605. teal: [0, 128, 128],
  606. thistle: [216, 191, 216],
  607. tomato: [255, 99, 71],
  608. turquoise: [64, 224, 208],
  609. violet: [238, 130, 238],
  610. wheat: [245, 222, 179],
  611. white: [255, 255, 255],
  612. whitesmoke: [245, 245, 245],
  613. yellow: [255, 255, 0],
  614. yellowgreen: [154, 205, 50]
  615. };
  616. // sets the value in a map (map may not be built)
  617. var setMap = function setMap(options) {
  618. var obj = options.map;
  619. var keys = options.keys;
  620. var l = keys.length;
  621. for (var i = 0; i < l; i++) {
  622. var key = keys[i];
  623. if (plainObject(key)) {
  624. throw Error('Tried to set map with object key');
  625. }
  626. if (i < keys.length - 1) {
  627. // extend the map if necessary
  628. if (obj[key] == null) {
  629. obj[key] = {};
  630. }
  631. obj = obj[key];
  632. } else {
  633. // set the value
  634. obj[key] = options.value;
  635. }
  636. }
  637. };
  638. // gets the value in a map even if it's not built in places
  639. var getMap = function getMap(options) {
  640. var obj = options.map;
  641. var keys = options.keys;
  642. var l = keys.length;
  643. for (var i = 0; i < l; i++) {
  644. var key = keys[i];
  645. if (plainObject(key)) {
  646. throw Error('Tried to get map with object key');
  647. }
  648. obj = obj[key];
  649. if (obj == null) {
  650. return obj;
  651. }
  652. }
  653. return obj;
  654. };
  655. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  656. function getDefaultExportFromCjs (x) {
  657. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  658. }
  659. /**
  660. * Checks if `value` is the
  661. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  662. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  663. *
  664. * @static
  665. * @memberOf _
  666. * @since 0.1.0
  667. * @category Lang
  668. * @param {*} value The value to check.
  669. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  670. * @example
  671. *
  672. * _.isObject({});
  673. * // => true
  674. *
  675. * _.isObject([1, 2, 3]);
  676. * // => true
  677. *
  678. * _.isObject(_.noop);
  679. * // => true
  680. *
  681. * _.isObject(null);
  682. * // => false
  683. */
  684. var isObject_1;
  685. var hasRequiredIsObject;
  686. function requireIsObject () {
  687. if (hasRequiredIsObject) return isObject_1;
  688. hasRequiredIsObject = 1;
  689. function isObject(value) {
  690. var type = typeof value;
  691. return value != null && (type == 'object' || type == 'function');
  692. }
  693. isObject_1 = isObject;
  694. return isObject_1;
  695. }
  696. /** Detect free variable `global` from Node.js. */
  697. var _freeGlobal;
  698. var hasRequired_freeGlobal;
  699. function require_freeGlobal () {
  700. if (hasRequired_freeGlobal) return _freeGlobal;
  701. hasRequired_freeGlobal = 1;
  702. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  703. _freeGlobal = freeGlobal;
  704. return _freeGlobal;
  705. }
  706. var _root;
  707. var hasRequired_root;
  708. function require_root () {
  709. if (hasRequired_root) return _root;
  710. hasRequired_root = 1;
  711. var freeGlobal = require_freeGlobal();
  712. /** Detect free variable `self`. */
  713. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  714. /** Used as a reference to the global object. */
  715. var root = freeGlobal || freeSelf || Function('return this')();
  716. _root = root;
  717. return _root;
  718. }
  719. var now_1;
  720. var hasRequiredNow;
  721. function requireNow () {
  722. if (hasRequiredNow) return now_1;
  723. hasRequiredNow = 1;
  724. var root = require_root();
  725. /**
  726. * Gets the timestamp of the number of milliseconds that have elapsed since
  727. * the Unix epoch (1 January 1970 00:00:00 UTC).
  728. *
  729. * @static
  730. * @memberOf _
  731. * @since 2.4.0
  732. * @category Date
  733. * @returns {number} Returns the timestamp.
  734. * @example
  735. *
  736. * _.defer(function(stamp) {
  737. * console.log(_.now() - stamp);
  738. * }, _.now());
  739. * // => Logs the number of milliseconds it took for the deferred invocation.
  740. */
  741. var now = function() {
  742. return root.Date.now();
  743. };
  744. now_1 = now;
  745. return now_1;
  746. }
  747. /** Used to match a single whitespace character. */
  748. var _trimmedEndIndex;
  749. var hasRequired_trimmedEndIndex;
  750. function require_trimmedEndIndex () {
  751. if (hasRequired_trimmedEndIndex) return _trimmedEndIndex;
  752. hasRequired_trimmedEndIndex = 1;
  753. var reWhitespace = /\s/;
  754. /**
  755. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  756. * character of `string`.
  757. *
  758. * @private
  759. * @param {string} string The string to inspect.
  760. * @returns {number} Returns the index of the last non-whitespace character.
  761. */
  762. function trimmedEndIndex(string) {
  763. var index = string.length;
  764. while (index-- && reWhitespace.test(string.charAt(index))) {}
  765. return index;
  766. }
  767. _trimmedEndIndex = trimmedEndIndex;
  768. return _trimmedEndIndex;
  769. }
  770. var _baseTrim;
  771. var hasRequired_baseTrim;
  772. function require_baseTrim () {
  773. if (hasRequired_baseTrim) return _baseTrim;
  774. hasRequired_baseTrim = 1;
  775. var trimmedEndIndex = require_trimmedEndIndex();
  776. /** Used to match leading whitespace. */
  777. var reTrimStart = /^\s+/;
  778. /**
  779. * The base implementation of `_.trim`.
  780. *
  781. * @private
  782. * @param {string} string The string to trim.
  783. * @returns {string} Returns the trimmed string.
  784. */
  785. function baseTrim(string) {
  786. return string
  787. ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  788. : string;
  789. }
  790. _baseTrim = baseTrim;
  791. return _baseTrim;
  792. }
  793. var _Symbol;
  794. var hasRequired_Symbol;
  795. function require_Symbol () {
  796. if (hasRequired_Symbol) return _Symbol;
  797. hasRequired_Symbol = 1;
  798. var root = require_root();
  799. /** Built-in value references. */
  800. var Symbol = root.Symbol;
  801. _Symbol = Symbol;
  802. return _Symbol;
  803. }
  804. var _getRawTag;
  805. var hasRequired_getRawTag;
  806. function require_getRawTag () {
  807. if (hasRequired_getRawTag) return _getRawTag;
  808. hasRequired_getRawTag = 1;
  809. var Symbol = require_Symbol();
  810. /** Used for built-in method references. */
  811. var objectProto = Object.prototype;
  812. /** Used to check objects for own properties. */
  813. var hasOwnProperty = objectProto.hasOwnProperty;
  814. /**
  815. * Used to resolve the
  816. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  817. * of values.
  818. */
  819. var nativeObjectToString = objectProto.toString;
  820. /** Built-in value references. */
  821. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  822. /**
  823. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  824. *
  825. * @private
  826. * @param {*} value The value to query.
  827. * @returns {string} Returns the raw `toStringTag`.
  828. */
  829. function getRawTag(value) {
  830. var isOwn = hasOwnProperty.call(value, symToStringTag),
  831. tag = value[symToStringTag];
  832. try {
  833. value[symToStringTag] = undefined;
  834. var unmasked = true;
  835. } catch (e) {}
  836. var result = nativeObjectToString.call(value);
  837. if (unmasked) {
  838. if (isOwn) {
  839. value[symToStringTag] = tag;
  840. } else {
  841. delete value[symToStringTag];
  842. }
  843. }
  844. return result;
  845. }
  846. _getRawTag = getRawTag;
  847. return _getRawTag;
  848. }
  849. /** Used for built-in method references. */
  850. var _objectToString;
  851. var hasRequired_objectToString;
  852. function require_objectToString () {
  853. if (hasRequired_objectToString) return _objectToString;
  854. hasRequired_objectToString = 1;
  855. var objectProto = Object.prototype;
  856. /**
  857. * Used to resolve the
  858. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  859. * of values.
  860. */
  861. var nativeObjectToString = objectProto.toString;
  862. /**
  863. * Converts `value` to a string using `Object.prototype.toString`.
  864. *
  865. * @private
  866. * @param {*} value The value to convert.
  867. * @returns {string} Returns the converted string.
  868. */
  869. function objectToString(value) {
  870. return nativeObjectToString.call(value);
  871. }
  872. _objectToString = objectToString;
  873. return _objectToString;
  874. }
  875. var _baseGetTag;
  876. var hasRequired_baseGetTag;
  877. function require_baseGetTag () {
  878. if (hasRequired_baseGetTag) return _baseGetTag;
  879. hasRequired_baseGetTag = 1;
  880. var Symbol = require_Symbol(),
  881. getRawTag = require_getRawTag(),
  882. objectToString = require_objectToString();
  883. /** `Object#toString` result references. */
  884. var nullTag = '[object Null]',
  885. undefinedTag = '[object Undefined]';
  886. /** Built-in value references. */
  887. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  888. /**
  889. * The base implementation of `getTag` without fallbacks for buggy environments.
  890. *
  891. * @private
  892. * @param {*} value The value to query.
  893. * @returns {string} Returns the `toStringTag`.
  894. */
  895. function baseGetTag(value) {
  896. if (value == null) {
  897. return value === undefined ? undefinedTag : nullTag;
  898. }
  899. return (symToStringTag && symToStringTag in Object(value))
  900. ? getRawTag(value)
  901. : objectToString(value);
  902. }
  903. _baseGetTag = baseGetTag;
  904. return _baseGetTag;
  905. }
  906. /**
  907. * Checks if `value` is object-like. A value is object-like if it's not `null`
  908. * and has a `typeof` result of "object".
  909. *
  910. * @static
  911. * @memberOf _
  912. * @since 4.0.0
  913. * @category Lang
  914. * @param {*} value The value to check.
  915. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  916. * @example
  917. *
  918. * _.isObjectLike({});
  919. * // => true
  920. *
  921. * _.isObjectLike([1, 2, 3]);
  922. * // => true
  923. *
  924. * _.isObjectLike(_.noop);
  925. * // => false
  926. *
  927. * _.isObjectLike(null);
  928. * // => false
  929. */
  930. var isObjectLike_1;
  931. var hasRequiredIsObjectLike;
  932. function requireIsObjectLike () {
  933. if (hasRequiredIsObjectLike) return isObjectLike_1;
  934. hasRequiredIsObjectLike = 1;
  935. function isObjectLike(value) {
  936. return value != null && typeof value == 'object';
  937. }
  938. isObjectLike_1 = isObjectLike;
  939. return isObjectLike_1;
  940. }
  941. var isSymbol_1;
  942. var hasRequiredIsSymbol;
  943. function requireIsSymbol () {
  944. if (hasRequiredIsSymbol) return isSymbol_1;
  945. hasRequiredIsSymbol = 1;
  946. var baseGetTag = require_baseGetTag(),
  947. isObjectLike = requireIsObjectLike();
  948. /** `Object#toString` result references. */
  949. var symbolTag = '[object Symbol]';
  950. /**
  951. * Checks if `value` is classified as a `Symbol` primitive or object.
  952. *
  953. * @static
  954. * @memberOf _
  955. * @since 4.0.0
  956. * @category Lang
  957. * @param {*} value The value to check.
  958. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  959. * @example
  960. *
  961. * _.isSymbol(Symbol.iterator);
  962. * // => true
  963. *
  964. * _.isSymbol('abc');
  965. * // => false
  966. */
  967. function isSymbol(value) {
  968. return typeof value == 'symbol' ||
  969. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  970. }
  971. isSymbol_1 = isSymbol;
  972. return isSymbol_1;
  973. }
  974. var toNumber_1;
  975. var hasRequiredToNumber;
  976. function requireToNumber () {
  977. if (hasRequiredToNumber) return toNumber_1;
  978. hasRequiredToNumber = 1;
  979. var baseTrim = require_baseTrim(),
  980. isObject = requireIsObject(),
  981. isSymbol = requireIsSymbol();
  982. /** Used as references for various `Number` constants. */
  983. var NAN = 0 / 0;
  984. /** Used to detect bad signed hexadecimal string values. */
  985. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  986. /** Used to detect binary string values. */
  987. var reIsBinary = /^0b[01]+$/i;
  988. /** Used to detect octal string values. */
  989. var reIsOctal = /^0o[0-7]+$/i;
  990. /** Built-in method references without a dependency on `root`. */
  991. var freeParseInt = parseInt;
  992. /**
  993. * Converts `value` to a number.
  994. *
  995. * @static
  996. * @memberOf _
  997. * @since 4.0.0
  998. * @category Lang
  999. * @param {*} value The value to process.
  1000. * @returns {number} Returns the number.
  1001. * @example
  1002. *
  1003. * _.toNumber(3.2);
  1004. * // => 3.2
  1005. *
  1006. * _.toNumber(Number.MIN_VALUE);
  1007. * // => 5e-324
  1008. *
  1009. * _.toNumber(Infinity);
  1010. * // => Infinity
  1011. *
  1012. * _.toNumber('3.2');
  1013. * // => 3.2
  1014. */
  1015. function toNumber(value) {
  1016. if (typeof value == 'number') {
  1017. return value;
  1018. }
  1019. if (isSymbol(value)) {
  1020. return NAN;
  1021. }
  1022. if (isObject(value)) {
  1023. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1024. value = isObject(other) ? (other + '') : other;
  1025. }
  1026. if (typeof value != 'string') {
  1027. return value === 0 ? value : +value;
  1028. }
  1029. value = baseTrim(value);
  1030. var isBinary = reIsBinary.test(value);
  1031. return (isBinary || reIsOctal.test(value))
  1032. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1033. : (reIsBadHex.test(value) ? NAN : +value);
  1034. }
  1035. toNumber_1 = toNumber;
  1036. return toNumber_1;
  1037. }
  1038. var debounce_1;
  1039. var hasRequiredDebounce;
  1040. function requireDebounce () {
  1041. if (hasRequiredDebounce) return debounce_1;
  1042. hasRequiredDebounce = 1;
  1043. var isObject = requireIsObject(),
  1044. now = requireNow(),
  1045. toNumber = requireToNumber();
  1046. /** Error message constants. */
  1047. var FUNC_ERROR_TEXT = 'Expected a function';
  1048. /* Built-in method references for those with the same name as other `lodash` methods. */
  1049. var nativeMax = Math.max,
  1050. nativeMin = Math.min;
  1051. /**
  1052. * Creates a debounced function that delays invoking `func` until after `wait`
  1053. * milliseconds have elapsed since the last time the debounced function was
  1054. * invoked. The debounced function comes with a `cancel` method to cancel
  1055. * delayed `func` invocations and a `flush` method to immediately invoke them.
  1056. * Provide `options` to indicate whether `func` should be invoked on the
  1057. * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
  1058. * with the last arguments provided to the debounced function. Subsequent
  1059. * calls to the debounced function return the result of the last `func`
  1060. * invocation.
  1061. *
  1062. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  1063. * invoked on the trailing edge of the timeout only if the debounced function
  1064. * is invoked more than once during the `wait` timeout.
  1065. *
  1066. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  1067. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  1068. *
  1069. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  1070. * for details over the differences between `_.debounce` and `_.throttle`.
  1071. *
  1072. * @static
  1073. * @memberOf _
  1074. * @since 0.1.0
  1075. * @category Function
  1076. * @param {Function} func The function to debounce.
  1077. * @param {number} [wait=0] The number of milliseconds to delay.
  1078. * @param {Object} [options={}] The options object.
  1079. * @param {boolean} [options.leading=false]
  1080. * Specify invoking on the leading edge of the timeout.
  1081. * @param {number} [options.maxWait]
  1082. * The maximum time `func` is allowed to be delayed before it's invoked.
  1083. * @param {boolean} [options.trailing=true]
  1084. * Specify invoking on the trailing edge of the timeout.
  1085. * @returns {Function} Returns the new debounced function.
  1086. * @example
  1087. *
  1088. * // Avoid costly calculations while the window size is in flux.
  1089. * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  1090. *
  1091. * // Invoke `sendMail` when clicked, debouncing subsequent calls.
  1092. * jQuery(element).on('click', _.debounce(sendMail, 300, {
  1093. * 'leading': true,
  1094. * 'trailing': false
  1095. * }));
  1096. *
  1097. * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
  1098. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
  1099. * var source = new EventSource('/stream');
  1100. * jQuery(source).on('message', debounced);
  1101. *
  1102. * // Cancel the trailing debounced invocation.
  1103. * jQuery(window).on('popstate', debounced.cancel);
  1104. */
  1105. function debounce(func, wait, options) {
  1106. var lastArgs,
  1107. lastThis,
  1108. maxWait,
  1109. result,
  1110. timerId,
  1111. lastCallTime,
  1112. lastInvokeTime = 0,
  1113. leading = false,
  1114. maxing = false,
  1115. trailing = true;
  1116. if (typeof func != 'function') {
  1117. throw new TypeError(FUNC_ERROR_TEXT);
  1118. }
  1119. wait = toNumber(wait) || 0;
  1120. if (isObject(options)) {
  1121. leading = !!options.leading;
  1122. maxing = 'maxWait' in options;
  1123. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  1124. trailing = 'trailing' in options ? !!options.trailing : trailing;
  1125. }
  1126. function invokeFunc(time) {
  1127. var args = lastArgs,
  1128. thisArg = lastThis;
  1129. lastArgs = lastThis = undefined;
  1130. lastInvokeTime = time;
  1131. result = func.apply(thisArg, args);
  1132. return result;
  1133. }
  1134. function leadingEdge(time) {
  1135. // Reset any `maxWait` timer.
  1136. lastInvokeTime = time;
  1137. // Start the timer for the trailing edge.
  1138. timerId = setTimeout(timerExpired, wait);
  1139. // Invoke the leading edge.
  1140. return leading ? invokeFunc(time) : result;
  1141. }
  1142. function remainingWait(time) {
  1143. var timeSinceLastCall = time - lastCallTime,
  1144. timeSinceLastInvoke = time - lastInvokeTime,
  1145. timeWaiting = wait - timeSinceLastCall;
  1146. return maxing
  1147. ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
  1148. : timeWaiting;
  1149. }
  1150. function shouldInvoke(time) {
  1151. var timeSinceLastCall = time - lastCallTime,
  1152. timeSinceLastInvoke = time - lastInvokeTime;
  1153. // Either this is the first call, activity has stopped and we're at the
  1154. // trailing edge, the system time has gone backwards and we're treating
  1155. // it as the trailing edge, or we've hit the `maxWait` limit.
  1156. return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
  1157. (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  1158. }
  1159. function timerExpired() {
  1160. var time = now();
  1161. if (shouldInvoke(time)) {
  1162. return trailingEdge(time);
  1163. }
  1164. // Restart the timer.
  1165. timerId = setTimeout(timerExpired, remainingWait(time));
  1166. }
  1167. function trailingEdge(time) {
  1168. timerId = undefined;
  1169. // Only invoke if we have `lastArgs` which means `func` has been
  1170. // debounced at least once.
  1171. if (trailing && lastArgs) {
  1172. return invokeFunc(time);
  1173. }
  1174. lastArgs = lastThis = undefined;
  1175. return result;
  1176. }
  1177. function cancel() {
  1178. if (timerId !== undefined) {
  1179. clearTimeout(timerId);
  1180. }
  1181. lastInvokeTime = 0;
  1182. lastArgs = lastCallTime = lastThis = timerId = undefined;
  1183. }
  1184. function flush() {
  1185. return timerId === undefined ? result : trailingEdge(now());
  1186. }
  1187. function debounced() {
  1188. var time = now(),
  1189. isInvoking = shouldInvoke(time);
  1190. lastArgs = arguments;
  1191. lastThis = this;
  1192. lastCallTime = time;
  1193. if (isInvoking) {
  1194. if (timerId === undefined) {
  1195. return leadingEdge(lastCallTime);
  1196. }
  1197. if (maxing) {
  1198. // Handle invocations in a tight loop.
  1199. clearTimeout(timerId);
  1200. timerId = setTimeout(timerExpired, wait);
  1201. return invokeFunc(lastCallTime);
  1202. }
  1203. }
  1204. if (timerId === undefined) {
  1205. timerId = setTimeout(timerExpired, wait);
  1206. }
  1207. return result;
  1208. }
  1209. debounced.cancel = cancel;
  1210. debounced.flush = flush;
  1211. return debounced;
  1212. }
  1213. debounce_1 = debounce;
  1214. return debounce_1;
  1215. }
  1216. var debounceExports = requireDebounce();
  1217. var debounce = /*@__PURE__*/getDefaultExportFromCjs(debounceExports);
  1218. var performance$1 = _window ? _window.performance : null;
  1219. var pnow = performance$1 && performance$1.now ? function () {
  1220. return performance$1.now();
  1221. } : function () {
  1222. return Date.now();
  1223. };
  1224. var raf = function () {
  1225. if (_window) {
  1226. if (_window.requestAnimationFrame) {
  1227. return function (fn) {
  1228. _window.requestAnimationFrame(fn);
  1229. };
  1230. } else if (_window.mozRequestAnimationFrame) {
  1231. return function (fn) {
  1232. _window.mozRequestAnimationFrame(fn);
  1233. };
  1234. } else if (_window.webkitRequestAnimationFrame) {
  1235. return function (fn) {
  1236. _window.webkitRequestAnimationFrame(fn);
  1237. };
  1238. } else if (_window.msRequestAnimationFrame) {
  1239. return function (fn) {
  1240. _window.msRequestAnimationFrame(fn);
  1241. };
  1242. }
  1243. }
  1244. return function (fn) {
  1245. if (fn) {
  1246. setTimeout(function () {
  1247. fn(pnow());
  1248. }, 1000 / 60);
  1249. }
  1250. };
  1251. }();
  1252. var requestAnimationFrame = function requestAnimationFrame(fn) {
  1253. return raf(fn);
  1254. };
  1255. var performanceNow = pnow;
  1256. var DEFAULT_HASH_SEED = 9261;
  1257. var K = 65599; // 37 also works pretty well
  1258. var DEFAULT_HASH_SEED_ALT = 5381;
  1259. var hashIterableInts = function hashIterableInts(iterator) {
  1260. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  1261. // sdbm/string-hash
  1262. var hash = seed;
  1263. var entry;
  1264. for (;;) {
  1265. entry = iterator.next();
  1266. if (entry.done) {
  1267. break;
  1268. }
  1269. hash = hash * K + entry.value | 0;
  1270. }
  1271. return hash;
  1272. };
  1273. var hashInt = function hashInt(num) {
  1274. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  1275. // sdbm/string-hash
  1276. return seed * K + num | 0;
  1277. };
  1278. var hashIntAlt = function hashIntAlt(num) {
  1279. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED_ALT;
  1280. // djb2/string-hash
  1281. return (seed << 5) + seed + num | 0;
  1282. };
  1283. var combineHashes = function combineHashes(hash1, hash2) {
  1284. return hash1 * 0x200000 + hash2;
  1285. };
  1286. var combineHashesArray = function combineHashesArray(hashes) {
  1287. return hashes[0] * 0x200000 + hashes[1];
  1288. };
  1289. var hashArrays = function hashArrays(hashes1, hashes2) {
  1290. return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];
  1291. };
  1292. var hashIntsArray = function hashIntsArray(ints, seed) {
  1293. var entry = {
  1294. value: 0,
  1295. done: false
  1296. };
  1297. var i = 0;
  1298. var length = ints.length;
  1299. var iterator = {
  1300. next: function next() {
  1301. if (i < length) {
  1302. entry.value = ints[i++];
  1303. } else {
  1304. entry.done = true;
  1305. }
  1306. return entry;
  1307. }
  1308. };
  1309. return hashIterableInts(iterator, seed);
  1310. };
  1311. var hashString = function hashString(str, seed) {
  1312. var entry = {
  1313. value: 0,
  1314. done: false
  1315. };
  1316. var i = 0;
  1317. var length = str.length;
  1318. var iterator = {
  1319. next: function next() {
  1320. if (i < length) {
  1321. entry.value = str.charCodeAt(i++);
  1322. } else {
  1323. entry.done = true;
  1324. }
  1325. return entry;
  1326. }
  1327. };
  1328. return hashIterableInts(iterator, seed);
  1329. };
  1330. var hashStrings = function hashStrings() {
  1331. return hashStringsArray(arguments);
  1332. };
  1333. var hashStringsArray = function hashStringsArray(strs) {
  1334. var hash;
  1335. for (var i = 0; i < strs.length; i++) {
  1336. var str = strs[i];
  1337. if (i === 0) {
  1338. hash = hashString(str);
  1339. } else {
  1340. hash = hashString(str, hash);
  1341. }
  1342. }
  1343. return hash;
  1344. };
  1345. function rotatePoint(x, y, centerX, centerY, angleDegrees) {
  1346. var angleRadians = angleDegrees * Math.PI / 180;
  1347. var rotatedX = Math.cos(angleRadians) * (x - centerX) - Math.sin(angleRadians) * (y - centerY) + centerX;
  1348. var rotatedY = Math.sin(angleRadians) * (x - centerX) + Math.cos(angleRadians) * (y - centerY) + centerY;
  1349. return {
  1350. x: rotatedX,
  1351. y: rotatedY
  1352. };
  1353. }
  1354. var movePointByBoxAspect = function movePointByBoxAspect(x, y, boxX, boxY, skewX, skewY) {
  1355. return {
  1356. x: (x - boxX) * skewX + boxX,
  1357. y: (y - boxY) * skewY + boxY
  1358. };
  1359. };
  1360. function rotatePosAndSkewByBox(pos, box, angleDegrees) {
  1361. if (angleDegrees === 0) return pos;
  1362. var centerX = (box.x1 + box.x2) / 2;
  1363. var centerY = (box.y1 + box.y2) / 2;
  1364. var skewX = box.w / box.h;
  1365. var skewY = 1 / skewX;
  1366. var rotated = rotatePoint(pos.x, pos.y, centerX, centerY, angleDegrees);
  1367. var skewed = movePointByBoxAspect(rotated.x, rotated.y, centerX, centerY, skewX, skewY);
  1368. return {
  1369. x: skewed.x,
  1370. y: skewed.y
  1371. };
  1372. }
  1373. var warningsEnabled = true;
  1374. var warnSupported = console.warn != null;
  1375. var traceSupported = console.trace != null;
  1376. var MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;
  1377. var trueify = function trueify() {
  1378. return true;
  1379. };
  1380. var falsify = function falsify() {
  1381. return false;
  1382. };
  1383. var zeroify = function zeroify() {
  1384. return 0;
  1385. };
  1386. var noop$1 = function noop() {};
  1387. var error = function error(msg) {
  1388. throw new Error(msg);
  1389. };
  1390. var warnings = function warnings(enabled) {
  1391. if (enabled !== undefined) {
  1392. warningsEnabled = !!enabled;
  1393. } else {
  1394. return warningsEnabled;
  1395. }
  1396. };
  1397. var warn = function warn(msg) {
  1398. if (!warnings()) {
  1399. return;
  1400. }
  1401. if (warnSupported) {
  1402. console.warn(msg);
  1403. } else {
  1404. console.log(msg);
  1405. if (traceSupported) {
  1406. console.trace();
  1407. }
  1408. }
  1409. };
  1410. var clone = function clone(obj) {
  1411. return extend({}, obj);
  1412. };
  1413. // gets a shallow copy of the argument
  1414. var copy = function copy(obj) {
  1415. if (obj == null) {
  1416. return obj;
  1417. }
  1418. if (array(obj)) {
  1419. return obj.slice();
  1420. } else if (plainObject(obj)) {
  1421. return clone(obj);
  1422. } else {
  1423. return obj;
  1424. }
  1425. };
  1426. var copyArray = function copyArray(arr) {
  1427. return arr.slice();
  1428. };
  1429. var uuid = function uuid(a, b /* placeholders */) {
  1430. for (
  1431. // loop :)
  1432. b = a = '';
  1433. // b - result , a - numeric letiable
  1434. a++ < 36;
  1435. //
  1436. b += a * 51 & 52 // if "a" is not 9 or 14 or 19 or 24
  1437. ?
  1438. // return a random number or 4
  1439. (a ^ 15 // if "a" is not 15
  1440. ?
  1441. // generate a random number from 0 to 15
  1442. 8 ^ Math.random() * (a ^ 20 ? 16 : 4) // unless "a" is 20, in which case a random number from 8 to 11
  1443. : 4 // otherwise 4
  1444. ).toString(16) : '-' // in other cases (if "a" is 9,14,19,24) insert "-"
  1445. );
  1446. return b;
  1447. };
  1448. var _staticEmptyObject = {};
  1449. var staticEmptyObject = function staticEmptyObject() {
  1450. return _staticEmptyObject;
  1451. };
  1452. var defaults$g = function defaults(_defaults) {
  1453. var keys = Object.keys(_defaults);
  1454. return function (opts) {
  1455. var filledOpts = {};
  1456. for (var i = 0; i < keys.length; i++) {
  1457. var key = keys[i];
  1458. var optVal = opts == null ? undefined : opts[key];
  1459. filledOpts[key] = optVal === undefined ? _defaults[key] : optVal;
  1460. }
  1461. return filledOpts;
  1462. };
  1463. };
  1464. var removeFromArray = function removeFromArray(arr, ele, oneCopy) {
  1465. for (var i = arr.length - 1; i >= 0; i--) {
  1466. if (arr[i] === ele) {
  1467. arr.splice(i, 1);
  1468. }
  1469. }
  1470. };
  1471. var clearArray = function clearArray(arr) {
  1472. arr.splice(0, arr.length);
  1473. };
  1474. var push = function push(arr, otherArr) {
  1475. for (var i = 0; i < otherArr.length; i++) {
  1476. var el = otherArr[i];
  1477. arr.push(el);
  1478. }
  1479. };
  1480. var getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {
  1481. if (prefix) {
  1482. propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  1483. }
  1484. return obj[propName];
  1485. };
  1486. var setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {
  1487. if (prefix) {
  1488. propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  1489. }
  1490. obj[propName] = value;
  1491. };
  1492. /* global Map */
  1493. var ObjectMap = /*#__PURE__*/function () {
  1494. function ObjectMap() {
  1495. _classCallCheck(this, ObjectMap);
  1496. this._obj = {};
  1497. }
  1498. return _createClass(ObjectMap, [{
  1499. key: "set",
  1500. value: function set(key, val) {
  1501. this._obj[key] = val;
  1502. return this;
  1503. }
  1504. }, {
  1505. key: "delete",
  1506. value: function _delete(key) {
  1507. this._obj[key] = undefined;
  1508. return this;
  1509. }
  1510. }, {
  1511. key: "clear",
  1512. value: function clear() {
  1513. this._obj = {};
  1514. }
  1515. }, {
  1516. key: "has",
  1517. value: function has(key) {
  1518. return this._obj[key] !== undefined;
  1519. }
  1520. }, {
  1521. key: "get",
  1522. value: function get(key) {
  1523. return this._obj[key];
  1524. }
  1525. }]);
  1526. }();
  1527. var Map$1 = typeof Map !== 'undefined' ? Map : ObjectMap;
  1528. /* global Set */
  1529. var undef = "undefined" ;
  1530. var ObjectSet = /*#__PURE__*/function () {
  1531. function ObjectSet(arrayOrObjectSet) {
  1532. _classCallCheck(this, ObjectSet);
  1533. this._obj = Object.create(null);
  1534. this.size = 0;
  1535. if (arrayOrObjectSet != null) {
  1536. var arr;
  1537. if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {
  1538. arr = arrayOrObjectSet.toArray();
  1539. } else {
  1540. arr = arrayOrObjectSet;
  1541. }
  1542. for (var i = 0; i < arr.length; i++) {
  1543. this.add(arr[i]);
  1544. }
  1545. }
  1546. }
  1547. return _createClass(ObjectSet, [{
  1548. key: "instanceString",
  1549. value: function instanceString() {
  1550. return 'set';
  1551. }
  1552. }, {
  1553. key: "add",
  1554. value: function add(val) {
  1555. var o = this._obj;
  1556. if (o[val] !== 1) {
  1557. o[val] = 1;
  1558. this.size++;
  1559. }
  1560. }
  1561. }, {
  1562. key: "delete",
  1563. value: function _delete(val) {
  1564. var o = this._obj;
  1565. if (o[val] === 1) {
  1566. o[val] = 0;
  1567. this.size--;
  1568. }
  1569. }
  1570. }, {
  1571. key: "clear",
  1572. value: function clear() {
  1573. this._obj = Object.create(null);
  1574. }
  1575. }, {
  1576. key: "has",
  1577. value: function has(val) {
  1578. return this._obj[val] === 1;
  1579. }
  1580. }, {
  1581. key: "toArray",
  1582. value: function toArray() {
  1583. var _this = this;
  1584. return Object.keys(this._obj).filter(function (key) {
  1585. return _this.has(key);
  1586. });
  1587. }
  1588. }, {
  1589. key: "forEach",
  1590. value: function forEach(callback, thisArg) {
  1591. return this.toArray().forEach(callback, thisArg);
  1592. }
  1593. }]);
  1594. }();
  1595. var Set$1 = (typeof Set === "undefined" ? "undefined" : _typeof(Set)) !== undef ? Set : ObjectSet;
  1596. // represents a node or an edge
  1597. var Element = function Element(cy, params) {
  1598. var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  1599. if (cy === undefined || params === undefined || !core(cy)) {
  1600. error('An element must have a core reference and parameters set');
  1601. return;
  1602. }
  1603. var group = params.group;
  1604. // try to automatically infer the group if unspecified
  1605. if (group == null) {
  1606. if (params.data && params.data.source != null && params.data.target != null) {
  1607. group = 'edges';
  1608. } else {
  1609. group = 'nodes';
  1610. }
  1611. }
  1612. // validate group
  1613. if (group !== 'nodes' && group !== 'edges') {
  1614. error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');
  1615. return;
  1616. }
  1617. // make the element array-like, just like a collection
  1618. this.length = 1;
  1619. this[0] = this;
  1620. // NOTE: when something is added here, add also to ele.json()
  1621. var _p = this._private = {
  1622. cy: cy,
  1623. single: true,
  1624. // indicates this is an element
  1625. data: params.data || {},
  1626. // data object
  1627. position: params.position || {
  1628. x: 0,
  1629. y: 0
  1630. },
  1631. // (x, y) position pair
  1632. autoWidth: undefined,
  1633. // width and height of nodes calculated by the renderer when set to special 'auto' value
  1634. autoHeight: undefined,
  1635. autoPadding: undefined,
  1636. compoundBoundsClean: false,
  1637. // whether the compound dimensions need to be recalculated the next time dimensions are read
  1638. listeners: [],
  1639. // array of bound listeners
  1640. group: group,
  1641. // string; 'nodes' or 'edges'
  1642. style: {},
  1643. // properties as set by the style
  1644. rstyle: {},
  1645. // properties for style sent from the renderer to the core
  1646. styleCxts: [],
  1647. // applied style contexts from the styler
  1648. styleKeys: {},
  1649. // per-group keys of style property values
  1650. removed: true,
  1651. // whether it's inside the vis; true if removed (set true here since we call restore)
  1652. selected: params.selected ? true : false,
  1653. // whether it's selected
  1654. selectable: params.selectable === undefined ? true : params.selectable ? true : false,
  1655. // whether it's selectable
  1656. locked: params.locked ? true : false,
  1657. // whether the element is locked (cannot be moved)
  1658. grabbed: false,
  1659. // whether the element is grabbed by the mouse; renderer sets this privately
  1660. grabbable: params.grabbable === undefined ? true : params.grabbable ? true : false,
  1661. // whether the element can be grabbed
  1662. pannable: params.pannable === undefined ? group === 'edges' ? true : false : params.pannable ? true : false,
  1663. // whether the element has passthrough panning enabled
  1664. active: false,
  1665. // whether the element is active from user interaction
  1666. classes: new Set$1(),
  1667. // map ( className => true )
  1668. animation: {
  1669. // object for currently-running animations
  1670. current: [],
  1671. queue: []
  1672. },
  1673. rscratch: {},
  1674. // object in which the renderer can store information
  1675. scratch: params.scratch || {},
  1676. // scratch objects
  1677. edges: [],
  1678. // array of connected edges
  1679. children: [],
  1680. // array of children
  1681. parent: params.parent && params.parent.isNode() ? params.parent : null,
  1682. // parent ref
  1683. traversalCache: {},
  1684. // cache of output of traversal functions
  1685. backgrounding: false,
  1686. // whether background images are loading
  1687. bbCache: null,
  1688. // cache of the current bounding box
  1689. bbCacheShift: {
  1690. x: 0,
  1691. y: 0
  1692. },
  1693. // shift applied to cached bb to be applied on next get
  1694. bodyBounds: null,
  1695. // bounds cache of element body, w/o overlay
  1696. overlayBounds: null,
  1697. // bounds cache of element body, including overlay
  1698. labelBounds: {
  1699. // bounds cache of labels
  1700. all: null,
  1701. source: null,
  1702. target: null,
  1703. main: null
  1704. },
  1705. arrowBounds: {
  1706. // bounds cache of edge arrows
  1707. source: null,
  1708. target: null,
  1709. 'mid-source': null,
  1710. 'mid-target': null
  1711. }
  1712. };
  1713. if (_p.position.x == null) {
  1714. _p.position.x = 0;
  1715. }
  1716. if (_p.position.y == null) {
  1717. _p.position.y = 0;
  1718. }
  1719. // renderedPosition overrides if specified
  1720. if (params.renderedPosition) {
  1721. var rpos = params.renderedPosition;
  1722. var pan = cy.pan();
  1723. var zoom = cy.zoom();
  1724. _p.position = {
  1725. x: (rpos.x - pan.x) / zoom,
  1726. y: (rpos.y - pan.y) / zoom
  1727. };
  1728. }
  1729. var classes = [];
  1730. if (array(params.classes)) {
  1731. classes = params.classes;
  1732. } else if (string(params.classes)) {
  1733. classes = params.classes.split(/\s+/);
  1734. }
  1735. for (var i = 0, l = classes.length; i < l; i++) {
  1736. var cls = classes[i];
  1737. if (!cls || cls === '') {
  1738. continue;
  1739. }
  1740. _p.classes.add(cls);
  1741. }
  1742. this.createEmitter();
  1743. if (restore === undefined || restore) {
  1744. this.restore();
  1745. }
  1746. var bypass = params.style || params.css;
  1747. if (bypass) {
  1748. warn('Setting a `style` bypass at element creation should be done only when absolutely necessary. Try to use the stylesheet instead.');
  1749. this.style(bypass);
  1750. }
  1751. };
  1752. var defineSearch = function defineSearch(params) {
  1753. params = {
  1754. bfs: params.bfs || !params.dfs,
  1755. dfs: params.dfs || !params.bfs
  1756. };
  1757. // from pseudocode on wikipedia
  1758. return function searchFn(roots, fn, directed) {
  1759. var options;
  1760. if (plainObject(roots) && !elementOrCollection(roots)) {
  1761. options = roots;
  1762. roots = options.roots || options.root;
  1763. fn = options.visit;
  1764. directed = options.directed;
  1765. }
  1766. directed = arguments.length === 2 && !fn$6(fn) ? fn : directed;
  1767. fn = fn$6(fn) ? fn : function () {};
  1768. var cy = this._private.cy;
  1769. var v = roots = string(roots) ? this.filter(roots) : roots;
  1770. var Q = [];
  1771. var connectedNodes = [];
  1772. var connectedBy = {};
  1773. var id2depth = {};
  1774. var V = {};
  1775. var j = 0;
  1776. var found;
  1777. var _this$byGroup = this.byGroup(),
  1778. nodes = _this$byGroup.nodes,
  1779. edges = _this$byGroup.edges;
  1780. // enqueue v
  1781. for (var i = 0; i < v.length; i++) {
  1782. var vi = v[i];
  1783. var viId = vi.id();
  1784. if (vi.isNode()) {
  1785. Q.unshift(vi);
  1786. if (params.bfs) {
  1787. V[viId] = true;
  1788. connectedNodes.push(vi);
  1789. }
  1790. id2depth[viId] = 0;
  1791. }
  1792. }
  1793. var _loop = function _loop() {
  1794. var v = params.bfs ? Q.shift() : Q.pop();
  1795. var vId = v.id();
  1796. if (params.dfs) {
  1797. if (V[vId]) {
  1798. return 0; // continue
  1799. }
  1800. V[vId] = true;
  1801. connectedNodes.push(v);
  1802. }
  1803. var depth = id2depth[vId];
  1804. var prevEdge = connectedBy[vId];
  1805. var src = prevEdge != null ? prevEdge.source() : null;
  1806. var tgt = prevEdge != null ? prevEdge.target() : null;
  1807. var prevNode = prevEdge == null ? undefined : v.same(src) ? tgt[0] : src[0];
  1808. var ret;
  1809. ret = fn(v, prevEdge, prevNode, j++, depth);
  1810. if (ret === true) {
  1811. found = v;
  1812. return 1; // break
  1813. }
  1814. if (ret === false) {
  1815. return 1; // break
  1816. }
  1817. var vwEdges = v.connectedEdges().filter(function (e) {
  1818. return (!directed || e.source().same(v)) && edges.has(e);
  1819. });
  1820. for (var _i2 = 0; _i2 < vwEdges.length; _i2++) {
  1821. var e = vwEdges[_i2];
  1822. var w = e.connectedNodes().filter(function (n) {
  1823. return !n.same(v) && nodes.has(n);
  1824. });
  1825. var wId = w.id();
  1826. if (w.length !== 0 && !V[wId]) {
  1827. w = w[0];
  1828. Q.push(w);
  1829. if (params.bfs) {
  1830. V[wId] = true;
  1831. connectedNodes.push(w);
  1832. }
  1833. connectedBy[wId] = e;
  1834. id2depth[wId] = id2depth[vId] + 1;
  1835. }
  1836. }
  1837. },
  1838. _ret;
  1839. while (Q.length !== 0) {
  1840. _ret = _loop();
  1841. if (_ret === 0) continue;
  1842. if (_ret === 1) break;
  1843. }
  1844. var connectedEles = cy.collection();
  1845. for (var _i = 0; _i < connectedNodes.length; _i++) {
  1846. var node = connectedNodes[_i];
  1847. var edge = connectedBy[node.id()];
  1848. if (edge != null) {
  1849. connectedEles.push(edge);
  1850. }
  1851. connectedEles.push(node);
  1852. }
  1853. return {
  1854. path: cy.collection(connectedEles),
  1855. found: cy.collection(found)
  1856. };
  1857. };
  1858. };
  1859. // search, spanning trees, etc
  1860. var elesfn$v = {
  1861. breadthFirstSearch: defineSearch({
  1862. bfs: true
  1863. }),
  1864. depthFirstSearch: defineSearch({
  1865. dfs: true
  1866. })
  1867. };
  1868. // nice, short mathematical alias
  1869. elesfn$v.bfs = elesfn$v.breadthFirstSearch;
  1870. elesfn$v.dfs = elesfn$v.depthFirstSearch;
  1871. var heap$2 = {exports: {}};
  1872. var heap$1 = heap$2.exports;
  1873. var hasRequiredHeap$1;
  1874. function requireHeap$1 () {
  1875. if (hasRequiredHeap$1) return heap$2.exports;
  1876. hasRequiredHeap$1 = 1;
  1877. (function (module, exports) {
  1878. // Generated by CoffeeScript 1.8.0
  1879. (function() {
  1880. var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
  1881. floor = Math.floor, min = Math.min;
  1882. /*
  1883. Default comparison function to be used
  1884. */
  1885. defaultCmp = function(x, y) {
  1886. if (x < y) {
  1887. return -1;
  1888. }
  1889. if (x > y) {
  1890. return 1;
  1891. }
  1892. return 0;
  1893. };
  1894. /*
  1895. Insert item x in list a, and keep it sorted assuming a is sorted.
  1896. If x is already in a, insert it to the right of the rightmost x.
  1897. Optional args lo (default 0) and hi (default a.length) bound the slice
  1898. of a to be searched.
  1899. */
  1900. insort = function(a, x, lo, hi, cmp) {
  1901. var mid;
  1902. if (lo == null) {
  1903. lo = 0;
  1904. }
  1905. if (cmp == null) {
  1906. cmp = defaultCmp;
  1907. }
  1908. if (lo < 0) {
  1909. throw new Error('lo must be non-negative');
  1910. }
  1911. if (hi == null) {
  1912. hi = a.length;
  1913. }
  1914. while (lo < hi) {
  1915. mid = floor((lo + hi) / 2);
  1916. if (cmp(x, a[mid]) < 0) {
  1917. hi = mid;
  1918. } else {
  1919. lo = mid + 1;
  1920. }
  1921. }
  1922. return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
  1923. };
  1924. /*
  1925. Push item onto heap, maintaining the heap invariant.
  1926. */
  1927. heappush = function(array, item, cmp) {
  1928. if (cmp == null) {
  1929. cmp = defaultCmp;
  1930. }
  1931. array.push(item);
  1932. return _siftdown(array, 0, array.length - 1, cmp);
  1933. };
  1934. /*
  1935. Pop the smallest item off the heap, maintaining the heap invariant.
  1936. */
  1937. heappop = function(array, cmp) {
  1938. var lastelt, returnitem;
  1939. if (cmp == null) {
  1940. cmp = defaultCmp;
  1941. }
  1942. lastelt = array.pop();
  1943. if (array.length) {
  1944. returnitem = array[0];
  1945. array[0] = lastelt;
  1946. _siftup(array, 0, cmp);
  1947. } else {
  1948. returnitem = lastelt;
  1949. }
  1950. return returnitem;
  1951. };
  1952. /*
  1953. Pop and return the current smallest value, and add the new item.
  1954. This is more efficient than heappop() followed by heappush(), and can be
  1955. more appropriate when using a fixed size heap. Note that the value
  1956. returned may be larger than item! That constrains reasonable use of
  1957. this routine unless written as part of a conditional replacement:
  1958. if item > array[0]
  1959. item = heapreplace(array, item)
  1960. */
  1961. heapreplace = function(array, item, cmp) {
  1962. var returnitem;
  1963. if (cmp == null) {
  1964. cmp = defaultCmp;
  1965. }
  1966. returnitem = array[0];
  1967. array[0] = item;
  1968. _siftup(array, 0, cmp);
  1969. return returnitem;
  1970. };
  1971. /*
  1972. Fast version of a heappush followed by a heappop.
  1973. */
  1974. heappushpop = function(array, item, cmp) {
  1975. var _ref;
  1976. if (cmp == null) {
  1977. cmp = defaultCmp;
  1978. }
  1979. if (array.length && cmp(array[0], item) < 0) {
  1980. _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
  1981. _siftup(array, 0, cmp);
  1982. }
  1983. return item;
  1984. };
  1985. /*
  1986. Transform list into a heap, in-place, in O(array.length) time.
  1987. */
  1988. heapify = function(array, cmp) {
  1989. var i, _i, _len, _ref1, _results, _results1;
  1990. if (cmp == null) {
  1991. cmp = defaultCmp;
  1992. }
  1993. _ref1 = (function() {
  1994. _results1 = [];
  1995. for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
  1996. return _results1;
  1997. }).apply(this).reverse();
  1998. _results = [];
  1999. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  2000. i = _ref1[_i];
  2001. _results.push(_siftup(array, i, cmp));
  2002. }
  2003. return _results;
  2004. };
  2005. /*
  2006. Update the position of the given item in the heap.
  2007. This function should be called every time the item is being modified.
  2008. */
  2009. updateItem = function(array, item, cmp) {
  2010. var pos;
  2011. if (cmp == null) {
  2012. cmp = defaultCmp;
  2013. }
  2014. pos = array.indexOf(item);
  2015. if (pos === -1) {
  2016. return;
  2017. }
  2018. _siftdown(array, 0, pos, cmp);
  2019. return _siftup(array, pos, cmp);
  2020. };
  2021. /*
  2022. Find the n largest elements in a dataset.
  2023. */
  2024. nlargest = function(array, n, cmp) {
  2025. var elem, result, _i, _len, _ref;
  2026. if (cmp == null) {
  2027. cmp = defaultCmp;
  2028. }
  2029. result = array.slice(0, n);
  2030. if (!result.length) {
  2031. return result;
  2032. }
  2033. heapify(result, cmp);
  2034. _ref = array.slice(n);
  2035. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2036. elem = _ref[_i];
  2037. heappushpop(result, elem, cmp);
  2038. }
  2039. return result.sort(cmp).reverse();
  2040. };
  2041. /*
  2042. Find the n smallest elements in a dataset.
  2043. */
  2044. nsmallest = function(array, n, cmp) {
  2045. var elem, los, result, _i, _j, _len, _ref, _ref1, _results;
  2046. if (cmp == null) {
  2047. cmp = defaultCmp;
  2048. }
  2049. if (n * 10 <= array.length) {
  2050. result = array.slice(0, n).sort(cmp);
  2051. if (!result.length) {
  2052. return result;
  2053. }
  2054. los = result[result.length - 1];
  2055. _ref = array.slice(n);
  2056. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2057. elem = _ref[_i];
  2058. if (cmp(elem, los) < 0) {
  2059. insort(result, elem, 0, null, cmp);
  2060. result.pop();
  2061. los = result[result.length - 1];
  2062. }
  2063. }
  2064. return result;
  2065. }
  2066. heapify(array, cmp);
  2067. _results = [];
  2068. for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {
  2069. _results.push(heappop(array, cmp));
  2070. }
  2071. return _results;
  2072. };
  2073. _siftdown = function(array, startpos, pos, cmp) {
  2074. var newitem, parent, parentpos;
  2075. if (cmp == null) {
  2076. cmp = defaultCmp;
  2077. }
  2078. newitem = array[pos];
  2079. while (pos > startpos) {
  2080. parentpos = (pos - 1) >> 1;
  2081. parent = array[parentpos];
  2082. if (cmp(newitem, parent) < 0) {
  2083. array[pos] = parent;
  2084. pos = parentpos;
  2085. continue;
  2086. }
  2087. break;
  2088. }
  2089. return array[pos] = newitem;
  2090. };
  2091. _siftup = function(array, pos, cmp) {
  2092. var childpos, endpos, newitem, rightpos, startpos;
  2093. if (cmp == null) {
  2094. cmp = defaultCmp;
  2095. }
  2096. endpos = array.length;
  2097. startpos = pos;
  2098. newitem = array[pos];
  2099. childpos = 2 * pos + 1;
  2100. while (childpos < endpos) {
  2101. rightpos = childpos + 1;
  2102. if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
  2103. childpos = rightpos;
  2104. }
  2105. array[pos] = array[childpos];
  2106. pos = childpos;
  2107. childpos = 2 * pos + 1;
  2108. }
  2109. array[pos] = newitem;
  2110. return _siftdown(array, startpos, pos, cmp);
  2111. };
  2112. Heap = (function() {
  2113. Heap.push = heappush;
  2114. Heap.pop = heappop;
  2115. Heap.replace = heapreplace;
  2116. Heap.pushpop = heappushpop;
  2117. Heap.heapify = heapify;
  2118. Heap.updateItem = updateItem;
  2119. Heap.nlargest = nlargest;
  2120. Heap.nsmallest = nsmallest;
  2121. function Heap(cmp) {
  2122. this.cmp = cmp != null ? cmp : defaultCmp;
  2123. this.nodes = [];
  2124. }
  2125. Heap.prototype.push = function(x) {
  2126. return heappush(this.nodes, x, this.cmp);
  2127. };
  2128. Heap.prototype.pop = function() {
  2129. return heappop(this.nodes, this.cmp);
  2130. };
  2131. Heap.prototype.peek = function() {
  2132. return this.nodes[0];
  2133. };
  2134. Heap.prototype.contains = function(x) {
  2135. return this.nodes.indexOf(x) !== -1;
  2136. };
  2137. Heap.prototype.replace = function(x) {
  2138. return heapreplace(this.nodes, x, this.cmp);
  2139. };
  2140. Heap.prototype.pushpop = function(x) {
  2141. return heappushpop(this.nodes, x, this.cmp);
  2142. };
  2143. Heap.prototype.heapify = function() {
  2144. return heapify(this.nodes, this.cmp);
  2145. };
  2146. Heap.prototype.updateItem = function(x) {
  2147. return updateItem(this.nodes, x, this.cmp);
  2148. };
  2149. Heap.prototype.clear = function() {
  2150. return this.nodes = [];
  2151. };
  2152. Heap.prototype.empty = function() {
  2153. return this.nodes.length === 0;
  2154. };
  2155. Heap.prototype.size = function() {
  2156. return this.nodes.length;
  2157. };
  2158. Heap.prototype.clone = function() {
  2159. var heap;
  2160. heap = new Heap();
  2161. heap.nodes = this.nodes.slice(0);
  2162. return heap;
  2163. };
  2164. Heap.prototype.toArray = function() {
  2165. return this.nodes.slice(0);
  2166. };
  2167. Heap.prototype.insert = Heap.prototype.push;
  2168. Heap.prototype.top = Heap.prototype.peek;
  2169. Heap.prototype.front = Heap.prototype.peek;
  2170. Heap.prototype.has = Heap.prototype.contains;
  2171. Heap.prototype.copy = Heap.prototype.clone;
  2172. return Heap;
  2173. })();
  2174. (function(root, factory) {
  2175. {
  2176. return module.exports = factory();
  2177. }
  2178. })(this, function() {
  2179. return Heap;
  2180. });
  2181. }).call(heap$1);
  2182. } (heap$2));
  2183. return heap$2.exports;
  2184. }
  2185. var heap;
  2186. var hasRequiredHeap;
  2187. function requireHeap () {
  2188. if (hasRequiredHeap) return heap;
  2189. hasRequiredHeap = 1;
  2190. heap = requireHeap$1();
  2191. return heap;
  2192. }
  2193. var heapExports = requireHeap();
  2194. var Heap = /*@__PURE__*/getDefaultExportFromCjs(heapExports);
  2195. var dijkstraDefaults = defaults$g({
  2196. root: null,
  2197. weight: function weight(edge) {
  2198. return 1;
  2199. },
  2200. directed: false
  2201. });
  2202. var elesfn$u = {
  2203. dijkstra: function dijkstra(options) {
  2204. if (!plainObject(options)) {
  2205. var args = arguments;
  2206. options = {
  2207. root: args[0],
  2208. weight: args[1],
  2209. directed: args[2]
  2210. };
  2211. }
  2212. var _dijkstraDefaults = dijkstraDefaults(options),
  2213. root = _dijkstraDefaults.root,
  2214. weight = _dijkstraDefaults.weight,
  2215. directed = _dijkstraDefaults.directed;
  2216. var eles = this;
  2217. var weightFn = weight;
  2218. var source = string(root) ? this.filter(root)[0] : root[0];
  2219. var dist = {};
  2220. var prev = {};
  2221. var knownDist = {};
  2222. var _this$byGroup = this.byGroup(),
  2223. nodes = _this$byGroup.nodes,
  2224. edges = _this$byGroup.edges;
  2225. edges.unmergeBy(function (ele) {
  2226. return ele.isLoop();
  2227. });
  2228. var getDist = function getDist(node) {
  2229. return dist[node.id()];
  2230. };
  2231. var setDist = function setDist(node, d) {
  2232. dist[node.id()] = d;
  2233. Q.updateItem(node);
  2234. };
  2235. var Q = new Heap(function (a, b) {
  2236. return getDist(a) - getDist(b);
  2237. });
  2238. for (var i = 0; i < nodes.length; i++) {
  2239. var node = nodes[i];
  2240. dist[node.id()] = node.same(source) ? 0 : Infinity;
  2241. Q.push(node);
  2242. }
  2243. var distBetween = function distBetween(u, v) {
  2244. var uvs = (directed ? u.edgesTo(v) : u.edgesWith(v)).intersect(edges);
  2245. var smallestDistance = Infinity;
  2246. var smallestEdge;
  2247. for (var _i = 0; _i < uvs.length; _i++) {
  2248. var edge = uvs[_i];
  2249. var _weight = weightFn(edge);
  2250. if (_weight < smallestDistance || !smallestEdge) {
  2251. smallestDistance = _weight;
  2252. smallestEdge = edge;
  2253. }
  2254. }
  2255. return {
  2256. edge: smallestEdge,
  2257. dist: smallestDistance
  2258. };
  2259. };
  2260. while (Q.size() > 0) {
  2261. var u = Q.pop();
  2262. var smalletsDist = getDist(u);
  2263. var uid = u.id();
  2264. knownDist[uid] = smalletsDist;
  2265. if (smalletsDist === Infinity) {
  2266. continue;
  2267. }
  2268. var neighbors = u.neighborhood().intersect(nodes);
  2269. for (var _i2 = 0; _i2 < neighbors.length; _i2++) {
  2270. var v = neighbors[_i2];
  2271. var vid = v.id();
  2272. var vDist = distBetween(u, v);
  2273. var alt = smalletsDist + vDist.dist;
  2274. if (alt < getDist(v)) {
  2275. setDist(v, alt);
  2276. prev[vid] = {
  2277. node: u,
  2278. edge: vDist.edge
  2279. };
  2280. }
  2281. } // for
  2282. } // while
  2283. return {
  2284. distanceTo: function distanceTo(node) {
  2285. var target = string(node) ? nodes.filter(node)[0] : node[0];
  2286. return knownDist[target.id()];
  2287. },
  2288. pathTo: function pathTo(node) {
  2289. var target = string(node) ? nodes.filter(node)[0] : node[0];
  2290. var S = [];
  2291. var u = target;
  2292. var uid = u.id();
  2293. if (target.length > 0) {
  2294. S.unshift(target);
  2295. while (prev[uid]) {
  2296. var p = prev[uid];
  2297. S.unshift(p.edge);
  2298. S.unshift(p.node);
  2299. u = p.node;
  2300. uid = u.id();
  2301. }
  2302. }
  2303. return eles.spawn(S);
  2304. }
  2305. };
  2306. }
  2307. };
  2308. var elesfn$t = {
  2309. // kruskal's algorithm (finds min spanning tree, assuming undirected graph)
  2310. // implemented from pseudocode from wikipedia
  2311. kruskal: function kruskal(weightFn) {
  2312. weightFn = weightFn || function (edge) {
  2313. return 1;
  2314. };
  2315. var _this$byGroup = this.byGroup(),
  2316. nodes = _this$byGroup.nodes,
  2317. edges = _this$byGroup.edges;
  2318. var numNodes = nodes.length;
  2319. var forest = new Array(numNodes);
  2320. var A = nodes; // assumes byGroup() creates new collections that can be safely mutated
  2321. var findSetIndex = function findSetIndex(ele) {
  2322. for (var i = 0; i < forest.length; i++) {
  2323. var eles = forest[i];
  2324. if (eles.has(ele)) {
  2325. return i;
  2326. }
  2327. }
  2328. };
  2329. // start with one forest per node
  2330. for (var i = 0; i < numNodes; i++) {
  2331. forest[i] = this.spawn(nodes[i]);
  2332. }
  2333. var S = edges.sort(function (a, b) {
  2334. return weightFn(a) - weightFn(b);
  2335. });
  2336. for (var _i = 0; _i < S.length; _i++) {
  2337. var edge = S[_i];
  2338. var u = edge.source()[0];
  2339. var v = edge.target()[0];
  2340. var setUIndex = findSetIndex(u);
  2341. var setVIndex = findSetIndex(v);
  2342. var setU = forest[setUIndex];
  2343. var setV = forest[setVIndex];
  2344. if (setUIndex !== setVIndex) {
  2345. A.merge(edge);
  2346. // combine forests for u and v
  2347. setU.merge(setV);
  2348. forest.splice(setVIndex, 1);
  2349. }
  2350. }
  2351. return A;
  2352. }
  2353. };
  2354. var aStarDefaults = defaults$g({
  2355. root: null,
  2356. goal: null,
  2357. weight: function weight(edge) {
  2358. return 1;
  2359. },
  2360. heuristic: function heuristic(edge) {
  2361. return 0;
  2362. },
  2363. directed: false
  2364. });
  2365. var elesfn$s = {
  2366. // Implemented from pseudocode from wikipedia
  2367. aStar: function aStar(options) {
  2368. var cy = this.cy();
  2369. var _aStarDefaults = aStarDefaults(options),
  2370. root = _aStarDefaults.root,
  2371. goal = _aStarDefaults.goal,
  2372. heuristic = _aStarDefaults.heuristic,
  2373. directed = _aStarDefaults.directed,
  2374. weight = _aStarDefaults.weight;
  2375. root = cy.collection(root)[0];
  2376. goal = cy.collection(goal)[0];
  2377. var sid = root.id();
  2378. var tid = goal.id();
  2379. var gScore = {};
  2380. var fScore = {};
  2381. var closedSetIds = {};
  2382. var openSet = new Heap(function (a, b) {
  2383. return fScore[a.id()] - fScore[b.id()];
  2384. });
  2385. var openSetIds = new Set$1();
  2386. var cameFrom = {};
  2387. var cameFromEdge = {};
  2388. var addToOpenSet = function addToOpenSet(ele, id) {
  2389. openSet.push(ele);
  2390. openSetIds.add(id);
  2391. };
  2392. var cMin, cMinId;
  2393. var popFromOpenSet = function popFromOpenSet() {
  2394. cMin = openSet.pop();
  2395. cMinId = cMin.id();
  2396. openSetIds["delete"](cMinId);
  2397. };
  2398. var isInOpenSet = function isInOpenSet(id) {
  2399. return openSetIds.has(id);
  2400. };
  2401. addToOpenSet(root, sid);
  2402. gScore[sid] = 0;
  2403. fScore[sid] = heuristic(root);
  2404. // Counter
  2405. var steps = 0;
  2406. // Main loop
  2407. while (openSet.size() > 0) {
  2408. popFromOpenSet();
  2409. steps++;
  2410. // If we've found our goal, then we are done
  2411. if (cMinId === tid) {
  2412. var path = [];
  2413. var pathNode = goal;
  2414. var pathNodeId = tid;
  2415. var pathEdge = cameFromEdge[pathNodeId];
  2416. for (;;) {
  2417. path.unshift(pathNode);
  2418. if (pathEdge != null) {
  2419. path.unshift(pathEdge);
  2420. }
  2421. pathNode = cameFrom[pathNodeId];
  2422. if (pathNode == null) {
  2423. break;
  2424. }
  2425. pathNodeId = pathNode.id();
  2426. pathEdge = cameFromEdge[pathNodeId];
  2427. }
  2428. return {
  2429. found: true,
  2430. distance: gScore[cMinId],
  2431. path: this.spawn(path),
  2432. steps: steps
  2433. };
  2434. }
  2435. // Add cMin to processed nodes
  2436. closedSetIds[cMinId] = true;
  2437. // Update scores for neighbors of cMin
  2438. // Take into account if graph is directed or not
  2439. var vwEdges = cMin._private.edges;
  2440. for (var i = 0; i < vwEdges.length; i++) {
  2441. var e = vwEdges[i];
  2442. // edge must be in set of calling eles
  2443. if (!this.hasElementWithId(e.id())) {
  2444. continue;
  2445. }
  2446. // cMin must be the source of edge if directed
  2447. if (directed && e.data('source') !== cMinId) {
  2448. continue;
  2449. }
  2450. var wSrc = e.source();
  2451. var wTgt = e.target();
  2452. var w = wSrc.id() !== cMinId ? wSrc : wTgt;
  2453. var wid = w.id();
  2454. // node must be in set of calling eles
  2455. if (!this.hasElementWithId(wid)) {
  2456. continue;
  2457. }
  2458. // if node is in closedSet, ignore it
  2459. if (closedSetIds[wid]) {
  2460. continue;
  2461. }
  2462. // New tentative score for node w
  2463. var tempScore = gScore[cMinId] + weight(e);
  2464. // Update gScore for node w if:
  2465. // w not present in openSet
  2466. // OR
  2467. // tentative gScore is less than previous value
  2468. // w not in openSet
  2469. if (!isInOpenSet(wid)) {
  2470. gScore[wid] = tempScore;
  2471. fScore[wid] = tempScore + heuristic(w);
  2472. addToOpenSet(w, wid);
  2473. cameFrom[wid] = cMin;
  2474. cameFromEdge[wid] = e;
  2475. continue;
  2476. }
  2477. // w already in openSet, but with greater gScore
  2478. if (tempScore < gScore[wid]) {
  2479. gScore[wid] = tempScore;
  2480. fScore[wid] = tempScore + heuristic(w);
  2481. cameFrom[wid] = cMin;
  2482. cameFromEdge[wid] = e;
  2483. }
  2484. } // End of neighbors update
  2485. } // End of main loop
  2486. // If we've reached here, then we've not reached our goal
  2487. return {
  2488. found: false,
  2489. distance: undefined,
  2490. path: undefined,
  2491. steps: steps
  2492. };
  2493. }
  2494. }; // elesfn
  2495. var floydWarshallDefaults = defaults$g({
  2496. weight: function weight(edge) {
  2497. return 1;
  2498. },
  2499. directed: false
  2500. });
  2501. var elesfn$r = {
  2502. // Implemented from pseudocode from wikipedia
  2503. floydWarshall: function floydWarshall(options) {
  2504. var cy = this.cy();
  2505. var _floydWarshallDefault = floydWarshallDefaults(options),
  2506. weight = _floydWarshallDefault.weight,
  2507. directed = _floydWarshallDefault.directed;
  2508. var weightFn = weight;
  2509. var _this$byGroup = this.byGroup(),
  2510. nodes = _this$byGroup.nodes,
  2511. edges = _this$byGroup.edges;
  2512. var N = nodes.length;
  2513. var Nsq = N * N;
  2514. var indexOf = function indexOf(node) {
  2515. return nodes.indexOf(node);
  2516. };
  2517. var atIndex = function atIndex(i) {
  2518. return nodes[i];
  2519. };
  2520. // Initialize distance matrix
  2521. var dist = new Array(Nsq);
  2522. for (var n = 0; n < Nsq; n++) {
  2523. var j = n % N;
  2524. var i = (n - j) / N;
  2525. if (i === j) {
  2526. dist[n] = 0;
  2527. } else {
  2528. dist[n] = Infinity;
  2529. }
  2530. }
  2531. // Initialize matrix used for path reconstruction
  2532. // Initialize distance matrix
  2533. var next = new Array(Nsq);
  2534. var edgeNext = new Array(Nsq);
  2535. // Process edges
  2536. for (var _i = 0; _i < edges.length; _i++) {
  2537. var edge = edges[_i];
  2538. var src = edge.source()[0];
  2539. var tgt = edge.target()[0];
  2540. if (src === tgt) {
  2541. continue;
  2542. } // exclude loops
  2543. var s = indexOf(src);
  2544. var t = indexOf(tgt);
  2545. var st = s * N + t; // source to target index
  2546. var _weight = weightFn(edge);
  2547. // Check if already process another edge between same 2 nodes
  2548. if (dist[st] > _weight) {
  2549. dist[st] = _weight;
  2550. next[st] = t;
  2551. edgeNext[st] = edge;
  2552. }
  2553. // If undirected graph, process 'reversed' edge
  2554. if (!directed) {
  2555. var ts = t * N + s; // target to source index
  2556. if (!directed && dist[ts] > _weight) {
  2557. dist[ts] = _weight;
  2558. next[ts] = s;
  2559. edgeNext[ts] = edge;
  2560. }
  2561. }
  2562. }
  2563. // Main loop
  2564. for (var k = 0; k < N; k++) {
  2565. for (var _i2 = 0; _i2 < N; _i2++) {
  2566. var ik = _i2 * N + k;
  2567. for (var _j = 0; _j < N; _j++) {
  2568. var ij = _i2 * N + _j;
  2569. var kj = k * N + _j;
  2570. if (dist[ik] + dist[kj] < dist[ij]) {
  2571. dist[ij] = dist[ik] + dist[kj];
  2572. next[ij] = next[ik];
  2573. }
  2574. }
  2575. }
  2576. }
  2577. var getArgEle = function getArgEle(ele) {
  2578. return (string(ele) ? cy.filter(ele) : ele)[0];
  2579. };
  2580. var indexOfArgEle = function indexOfArgEle(ele) {
  2581. return indexOf(getArgEle(ele));
  2582. };
  2583. var res = {
  2584. distance: function distance(from, to) {
  2585. var i = indexOfArgEle(from);
  2586. var j = indexOfArgEle(to);
  2587. return dist[i * N + j];
  2588. },
  2589. path: function path(from, to) {
  2590. var i = indexOfArgEle(from);
  2591. var j = indexOfArgEle(to);
  2592. var fromNode = atIndex(i);
  2593. if (i === j) {
  2594. return fromNode.collection();
  2595. }
  2596. if (next[i * N + j] == null) {
  2597. return cy.collection();
  2598. }
  2599. var path = cy.collection();
  2600. var prev = i;
  2601. var edge;
  2602. path.merge(fromNode);
  2603. while (i !== j) {
  2604. prev = i;
  2605. i = next[i * N + j];
  2606. edge = edgeNext[prev * N + i];
  2607. path.merge(edge);
  2608. path.merge(atIndex(i));
  2609. }
  2610. return path;
  2611. }
  2612. };
  2613. return res;
  2614. } // floydWarshall
  2615. }; // elesfn
  2616. var bellmanFordDefaults = defaults$g({
  2617. weight: function weight(edge) {
  2618. return 1;
  2619. },
  2620. directed: false,
  2621. root: null
  2622. });
  2623. var elesfn$q = {
  2624. // Implemented from pseudocode from wikipedia
  2625. bellmanFord: function bellmanFord(options) {
  2626. var _this = this;
  2627. var _bellmanFordDefaults = bellmanFordDefaults(options),
  2628. weight = _bellmanFordDefaults.weight,
  2629. directed = _bellmanFordDefaults.directed,
  2630. root = _bellmanFordDefaults.root;
  2631. var weightFn = weight;
  2632. var eles = this;
  2633. var cy = this.cy();
  2634. var _this$byGroup = this.byGroup(),
  2635. edges = _this$byGroup.edges,
  2636. nodes = _this$byGroup.nodes;
  2637. var numNodes = nodes.length;
  2638. var infoMap = new Map$1();
  2639. var hasNegativeWeightCycle = false;
  2640. var negativeWeightCycles = [];
  2641. root = cy.collection(root)[0]; // in case selector passed
  2642. edges.unmergeBy(function (edge) {
  2643. return edge.isLoop();
  2644. });
  2645. var numEdges = edges.length;
  2646. var getInfo = function getInfo(node) {
  2647. var obj = infoMap.get(node.id());
  2648. if (!obj) {
  2649. obj = {};
  2650. infoMap.set(node.id(), obj);
  2651. }
  2652. return obj;
  2653. };
  2654. var getNodeFromTo = function getNodeFromTo(to) {
  2655. return (string(to) ? cy.$(to) : to)[0];
  2656. };
  2657. var distanceTo = function distanceTo(to) {
  2658. return getInfo(getNodeFromTo(to)).dist;
  2659. };
  2660. var pathTo = function pathTo(to) {
  2661. var thisStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;
  2662. var end = getNodeFromTo(to);
  2663. var path = [];
  2664. var node = end;
  2665. for (;;) {
  2666. if (node == null) {
  2667. return _this.spawn();
  2668. }
  2669. var _getInfo = getInfo(node),
  2670. edge = _getInfo.edge,
  2671. pred = _getInfo.pred;
  2672. path.unshift(node[0]);
  2673. if (node.same(thisStart) && path.length > 0) {
  2674. break;
  2675. }
  2676. if (edge != null) {
  2677. path.unshift(edge);
  2678. }
  2679. node = pred;
  2680. }
  2681. return eles.spawn(path);
  2682. };
  2683. // Initializations { dist, pred, edge }
  2684. for (var i = 0; i < numNodes; i++) {
  2685. var node = nodes[i];
  2686. var info = getInfo(node);
  2687. if (node.same(root)) {
  2688. info.dist = 0;
  2689. } else {
  2690. info.dist = Infinity;
  2691. }
  2692. info.pred = null;
  2693. info.edge = null;
  2694. }
  2695. // Edges relaxation
  2696. var replacedEdge = false;
  2697. var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {
  2698. var dist = info1.dist + weight;
  2699. if (dist < info2.dist && !edge.same(info1.edge)) {
  2700. info2.dist = dist;
  2701. info2.pred = node1;
  2702. info2.edge = edge;
  2703. replacedEdge = true;
  2704. }
  2705. };
  2706. for (var _i = 1; _i < numNodes; _i++) {
  2707. replacedEdge = false;
  2708. for (var e = 0; e < numEdges; e++) {
  2709. var edge = edges[e];
  2710. var src = edge.source();
  2711. var tgt = edge.target();
  2712. var _weight = weightFn(edge);
  2713. var srcInfo = getInfo(src);
  2714. var tgtInfo = getInfo(tgt);
  2715. checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight);
  2716. // If undirected graph, we need to take into account the 'reverse' edge
  2717. if (!directed) {
  2718. checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);
  2719. }
  2720. }
  2721. if (!replacedEdge) {
  2722. break;
  2723. }
  2724. }
  2725. if (replacedEdge) {
  2726. // Check for negative weight cycles
  2727. var negativeWeightCycleIds = [];
  2728. for (var _e = 0; _e < numEdges; _e++) {
  2729. var _edge = edges[_e];
  2730. var _src = _edge.source();
  2731. var _tgt = _edge.target();
  2732. var _weight2 = weightFn(_edge);
  2733. var srcDist = getInfo(_src).dist;
  2734. var tgtDist = getInfo(_tgt).dist;
  2735. if (srcDist + _weight2 < tgtDist || !directed && tgtDist + _weight2 < srcDist) {
  2736. if (!hasNegativeWeightCycle) {
  2737. warn('Graph contains a negative weight cycle for Bellman-Ford');
  2738. hasNegativeWeightCycle = true;
  2739. }
  2740. if (options.findNegativeWeightCycles !== false) {
  2741. var negativeNodes = [];
  2742. if (srcDist + _weight2 < tgtDist) {
  2743. negativeNodes.push(_src);
  2744. }
  2745. if (!directed && tgtDist + _weight2 < srcDist) {
  2746. negativeNodes.push(_tgt);
  2747. }
  2748. var numNegativeNodes = negativeNodes.length;
  2749. for (var n = 0; n < numNegativeNodes; n++) {
  2750. var start = negativeNodes[n];
  2751. var cycle = [start];
  2752. cycle.push(getInfo(start).edge);
  2753. var _node = getInfo(start).pred;
  2754. while (cycle.indexOf(_node) === -1) {
  2755. cycle.push(_node);
  2756. cycle.push(getInfo(_node).edge);
  2757. _node = getInfo(_node).pred;
  2758. }
  2759. cycle = cycle.slice(cycle.indexOf(_node));
  2760. var smallestId = cycle[0].id();
  2761. var smallestIndex = 0;
  2762. for (var c = 2; c < cycle.length; c += 2) {
  2763. if (cycle[c].id() < smallestId) {
  2764. smallestId = cycle[c].id();
  2765. smallestIndex = c;
  2766. }
  2767. }
  2768. cycle = cycle.slice(smallestIndex).concat(cycle.slice(0, smallestIndex));
  2769. cycle.push(cycle[0]);
  2770. var cycleId = cycle.map(function (el) {
  2771. return el.id();
  2772. }).join(",");
  2773. if (negativeWeightCycleIds.indexOf(cycleId) === -1) {
  2774. negativeWeightCycles.push(eles.spawn(cycle));
  2775. negativeWeightCycleIds.push(cycleId);
  2776. }
  2777. }
  2778. } else {
  2779. break;
  2780. }
  2781. }
  2782. }
  2783. }
  2784. return {
  2785. distanceTo: distanceTo,
  2786. pathTo: pathTo,
  2787. hasNegativeWeightCycle: hasNegativeWeightCycle,
  2788. negativeWeightCycles: negativeWeightCycles
  2789. };
  2790. } // bellmanFord
  2791. }; // elesfn
  2792. var sqrt2 = Math.sqrt(2);
  2793. // Function which colapses 2 (meta) nodes into one
  2794. // Updates the remaining edge lists
  2795. // Receives as a paramater the edge which causes the collapse
  2796. var collapse = function collapse(edgeIndex, nodeMap, remainingEdges) {
  2797. if (remainingEdges.length === 0) {
  2798. error("Karger-Stein must be run on a connected (sub)graph");
  2799. }
  2800. var edgeInfo = remainingEdges[edgeIndex];
  2801. var sourceIn = edgeInfo[1];
  2802. var targetIn = edgeInfo[2];
  2803. var partition1 = nodeMap[sourceIn];
  2804. var partition2 = nodeMap[targetIn];
  2805. var newEdges = remainingEdges; // re-use array
  2806. // Delete all edges between partition1 and partition2
  2807. for (var i = newEdges.length - 1; i >= 0; i--) {
  2808. var edge = newEdges[i];
  2809. var src = edge[1];
  2810. var tgt = edge[2];
  2811. if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {
  2812. newEdges.splice(i, 1);
  2813. }
  2814. }
  2815. // All edges pointing to partition2 should now point to partition1
  2816. for (var _i = 0; _i < newEdges.length; _i++) {
  2817. var _edge = newEdges[_i];
  2818. if (_edge[1] === partition2) {
  2819. // Check source
  2820. newEdges[_i] = _edge.slice(); // copy
  2821. newEdges[_i][1] = partition1;
  2822. } else if (_edge[2] === partition2) {
  2823. // Check target
  2824. newEdges[_i] = _edge.slice(); // copy
  2825. newEdges[_i][2] = partition1;
  2826. }
  2827. }
  2828. // Move all nodes from partition2 to partition1
  2829. for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {
  2830. if (nodeMap[_i2] === partition2) {
  2831. nodeMap[_i2] = partition1;
  2832. }
  2833. }
  2834. return newEdges;
  2835. };
  2836. // Contracts a graph until we reach a certain number of meta nodes
  2837. var contractUntil = function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {
  2838. while (size > sizeLimit) {
  2839. // Choose an edge randomly
  2840. var edgeIndex = Math.floor(Math.random() * remainingEdges.length);
  2841. // Collapse graph based on edge
  2842. remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);
  2843. size--;
  2844. }
  2845. return remainingEdges;
  2846. };
  2847. var elesfn$p = {
  2848. // Computes the minimum cut of an undirected graph
  2849. // Returns the correct answer with high probability
  2850. kargerStein: function kargerStein() {
  2851. var _this = this;
  2852. var _this$byGroup = this.byGroup(),
  2853. nodes = _this$byGroup.nodes,
  2854. edges = _this$byGroup.edges;
  2855. edges.unmergeBy(function (edge) {
  2856. return edge.isLoop();
  2857. });
  2858. var numNodes = nodes.length;
  2859. var numEdges = edges.length;
  2860. var numIter = Math.ceil(Math.pow(Math.log(numNodes) / Math.LN2, 2));
  2861. var stopSize = Math.floor(numNodes / sqrt2);
  2862. if (numNodes < 2) {
  2863. error('At least 2 nodes are required for Karger-Stein algorithm');
  2864. return undefined;
  2865. }
  2866. // Now store edge destination as indexes
  2867. // Format for each edge (edge index, source node index, target node index)
  2868. var edgeIndexes = [];
  2869. for (var i = 0; i < numEdges; i++) {
  2870. var e = edges[i];
  2871. edgeIndexes.push([i, nodes.indexOf(e.source()), nodes.indexOf(e.target())]);
  2872. }
  2873. // We will store the best cut found here
  2874. var minCutSize = Infinity;
  2875. var minCutEdgeIndexes = [];
  2876. var minCutNodeMap = new Array(numNodes);
  2877. // Initial meta node partition
  2878. var metaNodeMap = new Array(numNodes);
  2879. var metaNodeMap2 = new Array(numNodes);
  2880. var copyNodesMap = function copyNodesMap(from, to) {
  2881. for (var _i3 = 0; _i3 < numNodes; _i3++) {
  2882. to[_i3] = from[_i3];
  2883. }
  2884. };
  2885. // Main loop
  2886. for (var iter = 0; iter <= numIter; iter++) {
  2887. // Reset meta node partition
  2888. for (var _i4 = 0; _i4 < numNodes; _i4++) {
  2889. metaNodeMap[_i4] = _i4;
  2890. }
  2891. // Contract until stop point (stopSize nodes)
  2892. var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);
  2893. var edgesState2 = edgesState.slice(); // copy
  2894. // Create a copy of the colapsed nodes state
  2895. copyNodesMap(metaNodeMap, metaNodeMap2);
  2896. // Run 2 iterations starting in the stop state
  2897. var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);
  2898. var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2);
  2899. // Is any of the 2 results the best cut so far?
  2900. if (res1.length <= res2.length && res1.length < minCutSize) {
  2901. minCutSize = res1.length;
  2902. minCutEdgeIndexes = res1;
  2903. copyNodesMap(metaNodeMap, minCutNodeMap);
  2904. } else if (res2.length <= res1.length && res2.length < minCutSize) {
  2905. minCutSize = res2.length;
  2906. minCutEdgeIndexes = res2;
  2907. copyNodesMap(metaNodeMap2, minCutNodeMap);
  2908. }
  2909. } // end of main loop
  2910. // Construct result
  2911. var cut = this.spawn(minCutEdgeIndexes.map(function (e) {
  2912. return edges[e[0]];
  2913. }));
  2914. var partition1 = this.spawn();
  2915. var partition2 = this.spawn();
  2916. // traverse metaNodeMap for best cut
  2917. var witnessNodePartition = minCutNodeMap[0];
  2918. for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {
  2919. var partitionId = minCutNodeMap[_i5];
  2920. var node = nodes[_i5];
  2921. if (partitionId === witnessNodePartition) {
  2922. partition1.merge(node);
  2923. } else {
  2924. partition2.merge(node);
  2925. }
  2926. }
  2927. // construct components corresponding to each disjoint subset of nodes
  2928. var constructComponent = function constructComponent(subset) {
  2929. var component = _this.spawn();
  2930. subset.forEach(function (node) {
  2931. component.merge(node);
  2932. node.connectedEdges().forEach(function (edge) {
  2933. // ensure edge is within calling collection and edge is not in cut
  2934. if (_this.contains(edge) && !cut.contains(edge)) {
  2935. component.merge(edge);
  2936. }
  2937. });
  2938. });
  2939. return component;
  2940. };
  2941. var components = [constructComponent(partition1), constructComponent(partition2)];
  2942. var ret = {
  2943. cut: cut,
  2944. components: components,
  2945. // n.b. partitions are included to be compatible with the old api spec
  2946. // (could be removed in a future major version)
  2947. partition1: partition1,
  2948. partition2: partition2
  2949. };
  2950. return ret;
  2951. }
  2952. }; // elesfn
  2953. var _Math$hypot;
  2954. var copyPosition = function copyPosition(p) {
  2955. return {
  2956. x: p.x,
  2957. y: p.y
  2958. };
  2959. };
  2960. var modelToRenderedPosition$1 = function modelToRenderedPosition(p, zoom, pan) {
  2961. return {
  2962. x: p.x * zoom + pan.x,
  2963. y: p.y * zoom + pan.y
  2964. };
  2965. };
  2966. var renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {
  2967. return {
  2968. x: (p.x - pan.x) / zoom,
  2969. y: (p.y - pan.y) / zoom
  2970. };
  2971. };
  2972. var array2point = function array2point(arr) {
  2973. return {
  2974. x: arr[0],
  2975. y: arr[1]
  2976. };
  2977. };
  2978. var min = function min(arr) {
  2979. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2980. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  2981. var min = Infinity;
  2982. for (var i = begin; i < end; i++) {
  2983. var val = arr[i];
  2984. if (isFinite(val)) {
  2985. min = Math.min(val, min);
  2986. }
  2987. }
  2988. return min;
  2989. };
  2990. var max = function max(arr) {
  2991. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2992. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  2993. var max = -Infinity;
  2994. for (var i = begin; i < end; i++) {
  2995. var val = arr[i];
  2996. if (isFinite(val)) {
  2997. max = Math.max(val, max);
  2998. }
  2999. }
  3000. return max;
  3001. };
  3002. var mean = function mean(arr) {
  3003. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3004. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  3005. var total = 0;
  3006. var n = 0;
  3007. for (var i = begin; i < end; i++) {
  3008. var val = arr[i];
  3009. if (isFinite(val)) {
  3010. total += val;
  3011. n++;
  3012. }
  3013. }
  3014. return total / n;
  3015. };
  3016. var median = function median(arr) {
  3017. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3018. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  3019. var copy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  3020. var sort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  3021. var includeHoles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  3022. if (copy) {
  3023. arr = arr.slice(begin, end);
  3024. } else {
  3025. if (end < arr.length) {
  3026. arr.splice(end, arr.length - end);
  3027. }
  3028. if (begin > 0) {
  3029. arr.splice(0, begin);
  3030. }
  3031. }
  3032. // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start
  3033. var off = 0; // offset from non-finite values
  3034. for (var i = arr.length - 1; i >= 0; i--) {
  3035. var v = arr[i];
  3036. if (includeHoles) {
  3037. if (!isFinite(v)) {
  3038. arr[i] = -Infinity;
  3039. off++;
  3040. }
  3041. } else {
  3042. // just remove it if we don't want to consider holes
  3043. arr.splice(i, 1);
  3044. }
  3045. }
  3046. if (sort) {
  3047. arr.sort(function (a, b) {
  3048. return a - b;
  3049. }); // requires copy = true if you don't want to change the orig
  3050. }
  3051. var len = arr.length;
  3052. var mid = Math.floor(len / 2);
  3053. if (len % 2 !== 0) {
  3054. return arr[mid + 1 + off];
  3055. } else {
  3056. return (arr[mid - 1 + off] + arr[mid + off]) / 2;
  3057. }
  3058. };
  3059. var deg2rad = function deg2rad(deg) {
  3060. return Math.PI * deg / 180;
  3061. };
  3062. var getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {
  3063. return Math.atan2(dispY, dispX) - Math.PI / 2;
  3064. };
  3065. var log2 = Math.log2 || function (n) {
  3066. return Math.log(n) / Math.log(2);
  3067. };
  3068. var signum = function signum(x) {
  3069. if (x > 0) {
  3070. return 1;
  3071. } else if (x < 0) {
  3072. return -1;
  3073. } else {
  3074. return 0;
  3075. }
  3076. };
  3077. var dist = function dist(p1, p2) {
  3078. return Math.sqrt(sqdist(p1, p2));
  3079. };
  3080. var sqdist = function sqdist(p1, p2) {
  3081. var dx = p2.x - p1.x;
  3082. var dy = p2.y - p1.y;
  3083. return dx * dx + dy * dy;
  3084. };
  3085. var inPlaceSumNormalize = function inPlaceSumNormalize(v) {
  3086. var length = v.length;
  3087. // First, get sum of all elements
  3088. var total = 0;
  3089. for (var i = 0; i < length; i++) {
  3090. total += v[i];
  3091. }
  3092. // Now, divide each by the sum of all elements
  3093. for (var _i = 0; _i < length; _i++) {
  3094. v[_i] = v[_i] / total;
  3095. }
  3096. return v;
  3097. };
  3098. // from http://en.wikipedia.org/wiki/Bézier_curve#Quadratic_curves
  3099. var qbezierAt = function qbezierAt(p0, p1, p2, t) {
  3100. return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;
  3101. };
  3102. var qbezierPtAt = function qbezierPtAt(p0, p1, p2, t) {
  3103. return {
  3104. x: qbezierAt(p0.x, p1.x, p2.x, t),
  3105. y: qbezierAt(p0.y, p1.y, p2.y, t)
  3106. };
  3107. };
  3108. var lineAt = function lineAt(p0, p1, t, d) {
  3109. var vec = {
  3110. x: p1.x - p0.x,
  3111. y: p1.y - p0.y
  3112. };
  3113. var vecDist = dist(p0, p1);
  3114. var normVec = {
  3115. x: vec.x / vecDist,
  3116. y: vec.y / vecDist
  3117. };
  3118. t = t == null ? 0 : t;
  3119. d = d != null ? d : t * vecDist;
  3120. return {
  3121. x: p0.x + normVec.x * d,
  3122. y: p0.y + normVec.y * d
  3123. };
  3124. };
  3125. var bound = function bound(min, val, max) {
  3126. return Math.max(min, Math.min(max, val));
  3127. };
  3128. // makes a full bb (x1, y1, x2, y2, w, h) from implicit params
  3129. var makeBoundingBox = function makeBoundingBox(bb) {
  3130. if (bb == null) {
  3131. return {
  3132. x1: Infinity,
  3133. y1: Infinity,
  3134. x2: -Infinity,
  3135. y2: -Infinity,
  3136. w: 0,
  3137. h: 0
  3138. };
  3139. } else if (bb.x1 != null && bb.y1 != null) {
  3140. if (bb.x2 != null && bb.y2 != null && bb.x2 >= bb.x1 && bb.y2 >= bb.y1) {
  3141. return {
  3142. x1: bb.x1,
  3143. y1: bb.y1,
  3144. x2: bb.x2,
  3145. y2: bb.y2,
  3146. w: bb.x2 - bb.x1,
  3147. h: bb.y2 - bb.y1
  3148. };
  3149. } else if (bb.w != null && bb.h != null && bb.w >= 0 && bb.h >= 0) {
  3150. return {
  3151. x1: bb.x1,
  3152. y1: bb.y1,
  3153. x2: bb.x1 + bb.w,
  3154. y2: bb.y1 + bb.h,
  3155. w: bb.w,
  3156. h: bb.h
  3157. };
  3158. }
  3159. }
  3160. };
  3161. var copyBoundingBox = function copyBoundingBox(bb) {
  3162. return {
  3163. x1: bb.x1,
  3164. x2: bb.x2,
  3165. w: bb.w,
  3166. y1: bb.y1,
  3167. y2: bb.y2,
  3168. h: bb.h
  3169. };
  3170. };
  3171. var clearBoundingBox = function clearBoundingBox(bb) {
  3172. bb.x1 = Infinity;
  3173. bb.y1 = Infinity;
  3174. bb.x2 = -Infinity;
  3175. bb.y2 = -Infinity;
  3176. bb.w = 0;
  3177. bb.h = 0;
  3178. };
  3179. var updateBoundingBox = function updateBoundingBox(bb1, bb2) {
  3180. // update bb1 with bb2 bounds
  3181. bb1.x1 = Math.min(bb1.x1, bb2.x1);
  3182. bb1.x2 = Math.max(bb1.x2, bb2.x2);
  3183. bb1.w = bb1.x2 - bb1.x1;
  3184. bb1.y1 = Math.min(bb1.y1, bb2.y1);
  3185. bb1.y2 = Math.max(bb1.y2, bb2.y2);
  3186. bb1.h = bb1.y2 - bb1.y1;
  3187. };
  3188. var expandBoundingBoxByPoint = function expandBoundingBoxByPoint(bb, x, y) {
  3189. bb.x1 = Math.min(bb.x1, x);
  3190. bb.x2 = Math.max(bb.x2, x);
  3191. bb.w = bb.x2 - bb.x1;
  3192. bb.y1 = Math.min(bb.y1, y);
  3193. bb.y2 = Math.max(bb.y2, y);
  3194. bb.h = bb.y2 - bb.y1;
  3195. };
  3196. var expandBoundingBox = function expandBoundingBox(bb) {
  3197. var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3198. bb.x1 -= padding;
  3199. bb.x2 += padding;
  3200. bb.y1 -= padding;
  3201. bb.y2 += padding;
  3202. bb.w = bb.x2 - bb.x1;
  3203. bb.h = bb.y2 - bb.y1;
  3204. return bb;
  3205. };
  3206. var expandBoundingBoxSides = function expandBoundingBoxSides(bb) {
  3207. var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];
  3208. var top, right, bottom, left;
  3209. if (padding.length === 1) {
  3210. top = right = bottom = left = padding[0];
  3211. } else if (padding.length === 2) {
  3212. top = bottom = padding[0];
  3213. left = right = padding[1];
  3214. } else if (padding.length === 4) {
  3215. var _padding = _slicedToArray(padding, 4);
  3216. top = _padding[0];
  3217. right = _padding[1];
  3218. bottom = _padding[2];
  3219. left = _padding[3];
  3220. }
  3221. bb.x1 -= left;
  3222. bb.x2 += right;
  3223. bb.y1 -= top;
  3224. bb.y2 += bottom;
  3225. bb.w = bb.x2 - bb.x1;
  3226. bb.h = bb.y2 - bb.y1;
  3227. return bb;
  3228. };
  3229. // assign the values of bb2 into bb1
  3230. var assignBoundingBox = function assignBoundingBox(bb1, bb2) {
  3231. bb1.x1 = bb2.x1;
  3232. bb1.y1 = bb2.y1;
  3233. bb1.x2 = bb2.x2;
  3234. bb1.y2 = bb2.y2;
  3235. bb1.w = bb1.x2 - bb1.x1;
  3236. bb1.h = bb1.y2 - bb1.y1;
  3237. };
  3238. var boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {
  3239. // case: one bb to right of other
  3240. if (bb1.x1 > bb2.x2) {
  3241. return false;
  3242. }
  3243. if (bb2.x1 > bb1.x2) {
  3244. return false;
  3245. }
  3246. // case: one bb to left of other
  3247. if (bb1.x2 < bb2.x1) {
  3248. return false;
  3249. }
  3250. if (bb2.x2 < bb1.x1) {
  3251. return false;
  3252. }
  3253. // case: one bb above other
  3254. if (bb1.y2 < bb2.y1) {
  3255. return false;
  3256. }
  3257. if (bb2.y2 < bb1.y1) {
  3258. return false;
  3259. }
  3260. // case: one bb below other
  3261. if (bb1.y1 > bb2.y2) {
  3262. return false;
  3263. }
  3264. if (bb2.y1 > bb1.y2) {
  3265. return false;
  3266. }
  3267. // otherwise, must have some overlap
  3268. return true;
  3269. };
  3270. var inBoundingBox = function inBoundingBox(bb, x, y) {
  3271. return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;
  3272. };
  3273. var pointInBoundingBox = function pointInBoundingBox(bb, pt) {
  3274. return inBoundingBox(bb, pt.x, pt.y);
  3275. };
  3276. var boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {
  3277. return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);
  3278. };
  3279. var hypot = (_Math$hypot = Math.hypot) !== null && _Math$hypot !== undefined ? _Math$hypot : function (x, y) {
  3280. return Math.sqrt(x * x + y * y);
  3281. };
  3282. function inflatePolygon(polygon, d) {
  3283. if (polygon.length < 3) {
  3284. throw new Error('Need at least 3 vertices');
  3285. }
  3286. // Helpers
  3287. var add = function add(a, b) {
  3288. return {
  3289. x: a.x + b.x,
  3290. y: a.y + b.y
  3291. };
  3292. };
  3293. var sub = function sub(a, b) {
  3294. return {
  3295. x: a.x - b.x,
  3296. y: a.y - b.y
  3297. };
  3298. };
  3299. var scale = function scale(v, s) {
  3300. return {
  3301. x: v.x * s,
  3302. y: v.y * s
  3303. };
  3304. };
  3305. var cross = function cross(u, v) {
  3306. return u.x * v.y - u.y * v.x;
  3307. };
  3308. var normalize = function normalize(v) {
  3309. var len = hypot(v.x, v.y);
  3310. return len === 0 ? {
  3311. x: 0,
  3312. y: 0
  3313. } : {
  3314. x: v.x / len,
  3315. y: v.y / len
  3316. };
  3317. };
  3318. // Signed area (positive = CCW)
  3319. var signedArea = function signedArea(pts) {
  3320. var A = 0;
  3321. for (var i = 0; i < pts.length; i++) {
  3322. var p = pts[i],
  3323. q = pts[(i + 1) % pts.length];
  3324. A += p.x * q.y - q.x * p.y;
  3325. }
  3326. return A / 2;
  3327. };
  3328. // Line–line intersection (infinite lines)
  3329. var intersectLines = function intersectLines(p1, p2, p3, p4) {
  3330. var r = sub(p2, p1);
  3331. var s = sub(p4, p3);
  3332. var denom = cross(r, s);
  3333. if (Math.abs(denom) < 1e-9) {
  3334. // Parallel or nearly so — fallback to midpoint
  3335. return add(p1, scale(r, 0.5));
  3336. }
  3337. var t = cross(sub(p3, p1), s) / denom;
  3338. return add(p1, scale(r, t));
  3339. };
  3340. // Make a shallow copy and enforce CCW
  3341. var pts = polygon.map(function (p) {
  3342. return {
  3343. x: p.x,
  3344. y: p.y
  3345. };
  3346. });
  3347. if (signedArea(pts) < 0) pts.reverse();
  3348. var n = pts.length;
  3349. // Compute outward normals for each edge
  3350. var normals = [];
  3351. for (var i = 0; i < n; i++) {
  3352. var p = pts[i],
  3353. q = pts[(i + 1) % n];
  3354. var edge = sub(q, p);
  3355. // For CCW polygon, inward normal = (-edge.y, edge.x)
  3356. // so outward normal = (edge.y, -edge.x)
  3357. var out = normalize({
  3358. x: edge.y,
  3359. y: -edge.x
  3360. });
  3361. normals.push(out);
  3362. }
  3363. // Build offset edges
  3364. var offsetEdges = normals.map(function (nrm, i) {
  3365. var p1 = add(pts[i], scale(nrm, d));
  3366. var p2 = add(pts[(i + 1) % n], scale(nrm, d));
  3367. return {
  3368. p1: p1,
  3369. p2: p2
  3370. };
  3371. });
  3372. // Intersect consecutive offset edges
  3373. var inflated = [];
  3374. for (var _i2 = 0; _i2 < n; _i2++) {
  3375. var prevEdge = offsetEdges[(_i2 - 1 + n) % n];
  3376. var currEdge = offsetEdges[_i2];
  3377. var ip = intersectLines(prevEdge.p1, prevEdge.p2, currEdge.p1, currEdge.p2);
  3378. inflated.push(ip);
  3379. }
  3380. return inflated;
  3381. }
  3382. function miterBox(pts, centerX, centerY, width, height, strokeWidth) {
  3383. var tpts = transformPoints(pts, centerX, centerY, width, height);
  3384. var offsetPoints = inflatePolygon(tpts, strokeWidth);
  3385. var bb = makeBoundingBox();
  3386. offsetPoints.forEach(function (pt) {
  3387. return expandBoundingBoxByPoint(bb, pt.x, pt.y);
  3388. });
  3389. return bb;
  3390. }
  3391. var roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {
  3392. var radius = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'auto';
  3393. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  3394. var halfWidth = width / 2;
  3395. var halfHeight = height / 2;
  3396. cornerRadius = Math.min(cornerRadius, halfWidth, halfHeight);
  3397. var doWidth = cornerRadius !== halfWidth,
  3398. doHeight = cornerRadius !== halfHeight;
  3399. // Check intersections with straight line segments
  3400. var straightLineIntersections;
  3401. // Top segment, left to right
  3402. if (doWidth) {
  3403. var topStartX = nodeX - halfWidth + cornerRadius - padding;
  3404. var topStartY = nodeY - halfHeight - padding;
  3405. var topEndX = nodeX + halfWidth - cornerRadius + padding;
  3406. var topEndY = topStartY;
  3407. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
  3408. if (straightLineIntersections.length > 0) {
  3409. return straightLineIntersections;
  3410. }
  3411. }
  3412. // Right segment, top to bottom
  3413. if (doHeight) {
  3414. var rightStartX = nodeX + halfWidth + padding;
  3415. var rightStartY = nodeY - halfHeight + cornerRadius - padding;
  3416. var rightEndX = rightStartX;
  3417. var rightEndY = nodeY + halfHeight - cornerRadius + padding;
  3418. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, rightStartX, rightStartY, rightEndX, rightEndY, false);
  3419. if (straightLineIntersections.length > 0) {
  3420. return straightLineIntersections;
  3421. }
  3422. }
  3423. // Bottom segment, left to right
  3424. if (doWidth) {
  3425. var bottomStartX = nodeX - halfWidth + cornerRadius - padding;
  3426. var bottomStartY = nodeY + halfHeight + padding;
  3427. var bottomEndX = nodeX + halfWidth - cornerRadius + padding;
  3428. var bottomEndY = bottomStartY;
  3429. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, bottomStartX, bottomStartY, bottomEndX, bottomEndY, false);
  3430. if (straightLineIntersections.length > 0) {
  3431. return straightLineIntersections;
  3432. }
  3433. }
  3434. // Left segment, top to bottom
  3435. if (doHeight) {
  3436. var leftStartX = nodeX - halfWidth - padding;
  3437. var leftStartY = nodeY - halfHeight + cornerRadius - padding;
  3438. var leftEndX = leftStartX;
  3439. var leftEndY = nodeY + halfHeight - cornerRadius + padding;
  3440. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, leftStartX, leftStartY, leftEndX, leftEndY, false);
  3441. if (straightLineIntersections.length > 0) {
  3442. return straightLineIntersections;
  3443. }
  3444. }
  3445. // Check intersections with arc segments
  3446. var arcIntersections;
  3447. // Top Left
  3448. {
  3449. var topLeftCenterX = nodeX - halfWidth + cornerRadius;
  3450. var topLeftCenterY = nodeY - halfHeight + cornerRadius;
  3451. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding);
  3452. // Ensure the intersection is on the desired quarter of the circle
  3453. if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {
  3454. return [arcIntersections[0], arcIntersections[1]];
  3455. }
  3456. }
  3457. // Top Right
  3458. {
  3459. var topRightCenterX = nodeX + halfWidth - cornerRadius;
  3460. var topRightCenterY = nodeY - halfHeight + cornerRadius;
  3461. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding);
  3462. // Ensure the intersection is on the desired quarter of the circle
  3463. if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {
  3464. return [arcIntersections[0], arcIntersections[1]];
  3465. }
  3466. }
  3467. // Bottom Right
  3468. {
  3469. var bottomRightCenterX = nodeX + halfWidth - cornerRadius;
  3470. var bottomRightCenterY = nodeY + halfHeight - cornerRadius;
  3471. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding);
  3472. // Ensure the intersection is on the desired quarter of the circle
  3473. if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {
  3474. return [arcIntersections[0], arcIntersections[1]];
  3475. }
  3476. }
  3477. // Bottom Left
  3478. {
  3479. var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;
  3480. var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;
  3481. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding);
  3482. // Ensure the intersection is on the desired quarter of the circle
  3483. if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {
  3484. return [arcIntersections[0], arcIntersections[1]];
  3485. }
  3486. }
  3487. return []; // if nothing
  3488. };
  3489. var inLineVicinity = function inLineVicinity(x, y, lx1, ly1, lx2, ly2, tolerance) {
  3490. var t = tolerance;
  3491. var x1 = Math.min(lx1, lx2);
  3492. var x2 = Math.max(lx1, lx2);
  3493. var y1 = Math.min(ly1, ly2);
  3494. var y2 = Math.max(ly1, ly2);
  3495. return x1 - t <= x && x <= x2 + t && y1 - t <= y && y <= y2 + t;
  3496. };
  3497. var inBezierVicinity = function inBezierVicinity(x, y, x1, y1, x2, y2, x3, y3, tolerance) {
  3498. var bb = {
  3499. x1: Math.min(x1, x3, x2) - tolerance,
  3500. x2: Math.max(x1, x3, x2) + tolerance,
  3501. y1: Math.min(y1, y3, y2) - tolerance,
  3502. y2: Math.max(y1, y3, y2) + tolerance
  3503. };
  3504. // if outside the rough bounding box for the bezier, then it can't be a hit
  3505. if (x < bb.x1 || x > bb.x2 || y < bb.y1 || y > bb.y2) {
  3506. // console.log('bezier out of rough bb')
  3507. return false;
  3508. } else {
  3509. // console.log('do more expensive check');
  3510. return true;
  3511. }
  3512. };
  3513. var solveQuadratic = function solveQuadratic(a, b, c, val) {
  3514. c -= val;
  3515. var r = b * b - 4 * a * c;
  3516. if (r < 0) {
  3517. return [];
  3518. }
  3519. var sqrtR = Math.sqrt(r);
  3520. var denom = 2 * a;
  3521. var root1 = (-b + sqrtR) / denom;
  3522. var root2 = (-b - sqrtR) / denom;
  3523. return [root1, root2];
  3524. };
  3525. var solveCubic = function solveCubic(a, b, c, d, result) {
  3526. // Solves a cubic function, returns root in form [r1, i1, r2, i2, r3, i3], where
  3527. // r is the real component, i is the imaginary component
  3528. // An implementation of the Cardano method from the year 1545
  3529. // http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots
  3530. var epsilon = 0.00001;
  3531. // avoid division by zero while keeping the overall expression close in value
  3532. if (a === 0) {
  3533. a = epsilon;
  3534. }
  3535. b /= a;
  3536. c /= a;
  3537. d /= a;
  3538. var discriminant, q, r, dum1, s, t, term1, r13;
  3539. q = (3.0 * c - b * b) / 9.0;
  3540. r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b));
  3541. r /= 54.0;
  3542. discriminant = q * q * q + r * r;
  3543. result[1] = 0;
  3544. term1 = b / 3.0;
  3545. if (discriminant > 0) {
  3546. s = r + Math.sqrt(discriminant);
  3547. s = s < 0 ? -Math.pow(-s, 1.0 / 3.0) : Math.pow(s, 1.0 / 3.0);
  3548. t = r - Math.sqrt(discriminant);
  3549. t = t < 0 ? -Math.pow(-t, 1.0 / 3.0) : Math.pow(t, 1.0 / 3.0);
  3550. result[0] = -term1 + s + t;
  3551. term1 += (s + t) / 2.0;
  3552. result[4] = result[2] = -term1;
  3553. term1 = Math.sqrt(3.0) * (-t + s) / 2;
  3554. result[3] = term1;
  3555. result[5] = -term1;
  3556. return;
  3557. }
  3558. result[5] = result[3] = 0;
  3559. if (discriminant === 0) {
  3560. r13 = r < 0 ? -Math.pow(-r, 1.0 / 3.0) : Math.pow(r, 1.0 / 3.0);
  3561. result[0] = -term1 + 2.0 * r13;
  3562. result[4] = result[2] = -(r13 + term1);
  3563. return;
  3564. }
  3565. q = -q;
  3566. dum1 = q * q * q;
  3567. dum1 = Math.acos(r / Math.sqrt(dum1));
  3568. r13 = 2.0 * Math.sqrt(q);
  3569. result[0] = -term1 + r13 * Math.cos(dum1 / 3.0);
  3570. result[2] = -term1 + r13 * Math.cos((dum1 + 2.0 * Math.PI) / 3.0);
  3571. result[4] = -term1 + r13 * Math.cos((dum1 + 4.0 * Math.PI) / 3.0);
  3572. return;
  3573. };
  3574. var sqdistToQuadraticBezier = function sqdistToQuadraticBezier(x, y, x1, y1, x2, y2, x3, y3) {
  3575. // Find minimum distance by using the minimum of the distance
  3576. // function between the given point and the curve
  3577. // This gives the coefficients of the resulting cubic equation
  3578. // whose roots tell us where a possible minimum is
  3579. // (Coefficients are divided by 4)
  3580. 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;
  3581. 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;
  3582. 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;
  3583. var d = 1.0 * x1 * x2 - x1 * x1 + x1 * x - x2 * x + y1 * y2 - y1 * y1 + y1 * y - y2 * y;
  3584. // debug("coefficients: " + a / a + ", " + b / a + ", " + c / a + ", " + d / a);
  3585. var roots = [];
  3586. // Use the cubic solving algorithm
  3587. solveCubic(a, b, c, d, roots);
  3588. var zeroThreshold = 0.0000001;
  3589. var params = [];
  3590. for (var index = 0; index < 6; index += 2) {
  3591. if (Math.abs(roots[index + 1]) < zeroThreshold && roots[index] >= 0 && roots[index] <= 1.0) {
  3592. params.push(roots[index]);
  3593. }
  3594. }
  3595. params.push(1.0);
  3596. params.push(0.0);
  3597. var minDistanceSquared = -1;
  3598. var curX, curY, distSquared;
  3599. for (var i = 0; i < params.length; i++) {
  3600. curX = Math.pow(1.0 - params[i], 2.0) * x1 + 2.0 * (1 - params[i]) * params[i] * x2 + params[i] * params[i] * x3;
  3601. curY = Math.pow(1 - params[i], 2.0) * y1 + 2 * (1.0 - params[i]) * params[i] * y2 + params[i] * params[i] * y3;
  3602. distSquared = Math.pow(curX - x, 2) + Math.pow(curY - y, 2);
  3603. // debug('distance for param ' + params[i] + ": " + Math.sqrt(distSquared));
  3604. if (minDistanceSquared >= 0) {
  3605. if (distSquared < minDistanceSquared) {
  3606. minDistanceSquared = distSquared;
  3607. }
  3608. } else {
  3609. minDistanceSquared = distSquared;
  3610. }
  3611. }
  3612. return minDistanceSquared;
  3613. };
  3614. var sqdistToFiniteLine = function sqdistToFiniteLine(x, y, x1, y1, x2, y2) {
  3615. var offset = [x - x1, y - y1];
  3616. var line = [x2 - x1, y2 - y1];
  3617. var lineSq = line[0] * line[0] + line[1] * line[1];
  3618. var hypSq = offset[0] * offset[0] + offset[1] * offset[1];
  3619. var dotProduct = offset[0] * line[0] + offset[1] * line[1];
  3620. var adjSq = dotProduct * dotProduct / lineSq;
  3621. if (dotProduct < 0) {
  3622. return hypSq;
  3623. }
  3624. if (adjSq > lineSq) {
  3625. return (x - x2) * (x - x2) + (y - y2) * (y - y2);
  3626. }
  3627. return hypSq - adjSq;
  3628. };
  3629. var pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {
  3630. var x1, y1, x2, y2;
  3631. var y3;
  3632. // Intersect with vertical line through (x, y)
  3633. var up = 0;
  3634. // let down = 0;
  3635. for (var i = 0; i < points.length / 2; i++) {
  3636. x1 = points[i * 2];
  3637. y1 = points[i * 2 + 1];
  3638. if (i + 1 < points.length / 2) {
  3639. x2 = points[(i + 1) * 2];
  3640. y2 = points[(i + 1) * 2 + 1];
  3641. } else {
  3642. x2 = points[(i + 1 - points.length / 2) * 2];
  3643. y2 = points[(i + 1 - points.length / 2) * 2 + 1];
  3644. }
  3645. if (x1 == x && x2 == x) ; else if (x1 >= x && x >= x2 || x1 <= x && x <= x2) {
  3646. y3 = (x - x1) / (x2 - x1) * (y2 - y1) + y1;
  3647. if (y3 > y) {
  3648. up++;
  3649. }
  3650. // if( y3 < y ){
  3651. // down++;
  3652. // }
  3653. } else {
  3654. continue;
  3655. }
  3656. }
  3657. if (up % 2 === 0) {
  3658. return false;
  3659. } else {
  3660. return true;
  3661. }
  3662. };
  3663. var pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {
  3664. var transformedPoints = new Array(basePoints.length);
  3665. // Gives negative angle
  3666. var angle;
  3667. if (direction[0] != null) {
  3668. angle = Math.atan(direction[1] / direction[0]);
  3669. if (direction[0] < 0) {
  3670. angle = angle + Math.PI / 2;
  3671. } else {
  3672. angle = -angle - Math.PI / 2;
  3673. }
  3674. } else {
  3675. angle = direction;
  3676. }
  3677. var cos = Math.cos(-angle);
  3678. var sin = Math.sin(-angle);
  3679. // console.log("base: " + basePoints);
  3680. for (var i = 0; i < transformedPoints.length / 2; i++) {
  3681. transformedPoints[i * 2] = width / 2 * (basePoints[i * 2] * cos - basePoints[i * 2 + 1] * sin);
  3682. transformedPoints[i * 2 + 1] = height / 2 * (basePoints[i * 2 + 1] * cos + basePoints[i * 2] * sin);
  3683. transformedPoints[i * 2] += centerX;
  3684. transformedPoints[i * 2 + 1] += centerY;
  3685. }
  3686. var points;
  3687. if (padding > 0) {
  3688. var expandedLineSet = expandPolygon(transformedPoints, -padding);
  3689. points = joinLines(expandedLineSet);
  3690. } else {
  3691. points = transformedPoints;
  3692. }
  3693. return pointInsidePolygonPoints(x, y, points);
  3694. };
  3695. var pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height, corners) {
  3696. var cutPolygonPoints = new Array(basePoints.length * 2);
  3697. for (var i = 0; i < corners.length; i++) {
  3698. var corner = corners[i];
  3699. cutPolygonPoints[i * 4 + 0] = corner.startX;
  3700. cutPolygonPoints[i * 4 + 1] = corner.startY;
  3701. cutPolygonPoints[i * 4 + 2] = corner.stopX;
  3702. cutPolygonPoints[i * 4 + 3] = corner.stopY;
  3703. var squaredDistance = Math.pow(corner.cx - x, 2) + Math.pow(corner.cy - y, 2);
  3704. if (squaredDistance <= Math.pow(corner.radius, 2)) {
  3705. return true;
  3706. }
  3707. }
  3708. return pointInsidePolygonPoints(x, y, cutPolygonPoints);
  3709. };
  3710. var joinLines = function joinLines(lineSet) {
  3711. var vertices = new Array(lineSet.length / 2);
  3712. var currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY;
  3713. var nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY;
  3714. for (var i = 0; i < lineSet.length / 4; i++) {
  3715. currentLineStartX = lineSet[i * 4];
  3716. currentLineStartY = lineSet[i * 4 + 1];
  3717. currentLineEndX = lineSet[i * 4 + 2];
  3718. currentLineEndY = lineSet[i * 4 + 3];
  3719. if (i < lineSet.length / 4 - 1) {
  3720. nextLineStartX = lineSet[(i + 1) * 4];
  3721. nextLineStartY = lineSet[(i + 1) * 4 + 1];
  3722. nextLineEndX = lineSet[(i + 1) * 4 + 2];
  3723. nextLineEndY = lineSet[(i + 1) * 4 + 3];
  3724. } else {
  3725. nextLineStartX = lineSet[0];
  3726. nextLineStartY = lineSet[1];
  3727. nextLineEndX = lineSet[2];
  3728. nextLineEndY = lineSet[3];
  3729. }
  3730. var intersection = finiteLinesIntersect(currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY, nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY, true);
  3731. vertices[i * 2] = intersection[0];
  3732. vertices[i * 2 + 1] = intersection[1];
  3733. }
  3734. return vertices;
  3735. };
  3736. var expandPolygon = function expandPolygon(points, pad) {
  3737. var expandedLineSet = new Array(points.length * 2);
  3738. var currentPointX, currentPointY, nextPointX, nextPointY;
  3739. for (var i = 0; i < points.length / 2; i++) {
  3740. currentPointX = points[i * 2];
  3741. currentPointY = points[i * 2 + 1];
  3742. if (i < points.length / 2 - 1) {
  3743. nextPointX = points[(i + 1) * 2];
  3744. nextPointY = points[(i + 1) * 2 + 1];
  3745. } else {
  3746. nextPointX = points[0];
  3747. nextPointY = points[1];
  3748. }
  3749. // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]
  3750. // Assume CCW polygon winding
  3751. var offsetX = nextPointY - currentPointY;
  3752. var offsetY = -(nextPointX - currentPointX);
  3753. // Normalize
  3754. var offsetLength = Math.sqrt(offsetX * offsetX + offsetY * offsetY);
  3755. var normalizedOffsetX = offsetX / offsetLength;
  3756. var normalizedOffsetY = offsetY / offsetLength;
  3757. expandedLineSet[i * 4] = currentPointX + normalizedOffsetX * pad;
  3758. expandedLineSet[i * 4 + 1] = currentPointY + normalizedOffsetY * pad;
  3759. expandedLineSet[i * 4 + 2] = nextPointX + normalizedOffsetX * pad;
  3760. expandedLineSet[i * 4 + 3] = nextPointY + normalizedOffsetY * pad;
  3761. }
  3762. return expandedLineSet;
  3763. };
  3764. var intersectLineEllipse = function intersectLineEllipse(x, y, centerX, centerY, ellipseWradius, ellipseHradius) {
  3765. var dispX = centerX - x;
  3766. var dispY = centerY - y;
  3767. dispX /= ellipseWradius;
  3768. dispY /= ellipseHradius;
  3769. var len = Math.sqrt(dispX * dispX + dispY * dispY);
  3770. var newLength = len - 1;
  3771. if (newLength < 0) {
  3772. return [];
  3773. }
  3774. var lenProportion = newLength / len;
  3775. return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];
  3776. };
  3777. var checkInEllipse = function checkInEllipse(x, y, width, height, centerX, centerY, padding) {
  3778. x -= centerX;
  3779. y -= centerY;
  3780. x /= width / 2 + padding;
  3781. y /= height / 2 + padding;
  3782. return x * x + y * y <= 1;
  3783. };
  3784. // Returns intersections of increasing distance from line's start point
  3785. var intersectLineCircle = function intersectLineCircle(x1, y1, x2, y2, centerX, centerY, radius) {
  3786. // Calculate d, direction vector of line
  3787. var d = [x2 - x1, y2 - y1]; // Direction vector of line
  3788. var f = [x1 - centerX, y1 - centerY];
  3789. var a = d[0] * d[0] + d[1] * d[1];
  3790. var b = 2 * (f[0] * d[0] + f[1] * d[1]);
  3791. var c = f[0] * f[0] + f[1] * f[1] - radius * radius;
  3792. var discriminant = b * b - 4 * a * c;
  3793. if (discriminant < 0) {
  3794. return [];
  3795. }
  3796. var t1 = (-b + Math.sqrt(discriminant)) / (2 * a);
  3797. var t2 = (-b - Math.sqrt(discriminant)) / (2 * a);
  3798. var tMin = Math.min(t1, t2);
  3799. var tMax = Math.max(t1, t2);
  3800. var inRangeParams = [];
  3801. if (tMin >= 0 && tMin <= 1) {
  3802. inRangeParams.push(tMin);
  3803. }
  3804. if (tMax >= 0 && tMax <= 1) {
  3805. inRangeParams.push(tMax);
  3806. }
  3807. if (inRangeParams.length === 0) {
  3808. return [];
  3809. }
  3810. var nearIntersectionX = inRangeParams[0] * d[0] + x1;
  3811. var nearIntersectionY = inRangeParams[0] * d[1] + y1;
  3812. if (inRangeParams.length > 1) {
  3813. if (inRangeParams[0] == inRangeParams[1]) {
  3814. return [nearIntersectionX, nearIntersectionY];
  3815. } else {
  3816. var farIntersectionX = inRangeParams[1] * d[0] + x1;
  3817. var farIntersectionY = inRangeParams[1] * d[1] + y1;
  3818. return [nearIntersectionX, nearIntersectionY, farIntersectionX, farIntersectionY];
  3819. }
  3820. } else {
  3821. return [nearIntersectionX, nearIntersectionY];
  3822. }
  3823. };
  3824. var midOfThree = function midOfThree(a, b, c) {
  3825. if (b <= a && a <= c || c <= a && a <= b) {
  3826. return a;
  3827. } else if (a <= b && b <= c || c <= b && b <= a) {
  3828. return b;
  3829. } else {
  3830. return c;
  3831. }
  3832. };
  3833. // (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)
  3834. var finiteLinesIntersect = function finiteLinesIntersect(x1, y1, x2, y2, x3, y3, x4, y4, infiniteLines) {
  3835. var dx13 = x1 - x3;
  3836. var dx21 = x2 - x1;
  3837. var dx43 = x4 - x3;
  3838. var dy13 = y1 - y3;
  3839. var dy21 = y2 - y1;
  3840. var dy43 = y4 - y3;
  3841. var ua_t = dx43 * dy13 - dy43 * dx13;
  3842. var ub_t = dx21 * dy13 - dy21 * dx13;
  3843. var u_b = dy43 * dx21 - dx43 * dy21;
  3844. if (u_b !== 0) {
  3845. var ua = ua_t / u_b;
  3846. var ub = ub_t / u_b;
  3847. var flptThreshold = 0.001;
  3848. var _min = 0 - flptThreshold;
  3849. var _max = 1 + flptThreshold;
  3850. if (_min <= ua && ua <= _max && _min <= ub && ub <= _max) {
  3851. return [x1 + ua * dx21, y1 + ua * dy21];
  3852. } else {
  3853. if (!infiniteLines) {
  3854. return [];
  3855. } else {
  3856. return [x1 + ua * dx21, y1 + ua * dy21];
  3857. }
  3858. }
  3859. } else {
  3860. if (ua_t === 0 || ub_t === 0) {
  3861. // Parallel, coincident lines. Check if overlap
  3862. // Check endpoint of second line
  3863. if (midOfThree(x1, x2, x4) === x4) {
  3864. return [x4, y4];
  3865. }
  3866. // Check start point of second line
  3867. if (midOfThree(x1, x2, x3) === x3) {
  3868. return [x3, y3];
  3869. }
  3870. // Endpoint of first line
  3871. if (midOfThree(x3, x4, x2) === x2) {
  3872. return [x2, y2];
  3873. }
  3874. return [];
  3875. } else {
  3876. // Parallel, non-coincident
  3877. return [];
  3878. }
  3879. }
  3880. };
  3881. var transformPoints = function transformPoints(points, centerX, centerY, width, height) {
  3882. var ret = [];
  3883. var halfW = width / 2;
  3884. var halfH = height / 2;
  3885. var x = centerX;
  3886. var y = centerY;
  3887. ret.push({
  3888. x: x + halfW * points[0],
  3889. y: y + halfH * points[1]
  3890. });
  3891. for (var i = 1; i < points.length / 2; i++) {
  3892. ret.push({
  3893. x: x + halfW * points[i * 2],
  3894. y: y + halfH * points[i * 2 + 1]
  3895. });
  3896. }
  3897. return ret;
  3898. };
  3899. // math.polygonIntersectLine( x, y, basePoints, centerX, centerY, width, height, padding )
  3900. // intersect a node polygon (pts transformed)
  3901. //
  3902. // math.polygonIntersectLine( x, y, basePoints, centerX, centerY )
  3903. // intersect the points (no transform)
  3904. var polygonIntersectLine = function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {
  3905. var intersections = [];
  3906. var intersection;
  3907. var transformedPoints = new Array(basePoints.length);
  3908. var doTransform = true;
  3909. if (width == null) {
  3910. doTransform = false;
  3911. }
  3912. var points;
  3913. if (doTransform) {
  3914. for (var i = 0; i < transformedPoints.length / 2; i++) {
  3915. transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;
  3916. transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;
  3917. }
  3918. if (padding > 0) {
  3919. var expandedLineSet = expandPolygon(transformedPoints, -padding);
  3920. points = joinLines(expandedLineSet);
  3921. } else {
  3922. points = transformedPoints;
  3923. }
  3924. } else {
  3925. points = basePoints;
  3926. }
  3927. var currentX, currentY, nextX, nextY;
  3928. for (var _i3 = 0; _i3 < points.length / 2; _i3++) {
  3929. currentX = points[_i3 * 2];
  3930. currentY = points[_i3 * 2 + 1];
  3931. if (_i3 < points.length / 2 - 1) {
  3932. nextX = points[(_i3 + 1) * 2];
  3933. nextY = points[(_i3 + 1) * 2 + 1];
  3934. } else {
  3935. nextX = points[0];
  3936. nextY = points[1];
  3937. }
  3938. intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);
  3939. if (intersection.length !== 0) {
  3940. intersections.push(intersection[0], intersection[1]);
  3941. }
  3942. }
  3943. return intersections;
  3944. };
  3945. var roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding, corners) {
  3946. var intersections = [];
  3947. var intersection;
  3948. var lines = new Array(basePoints.length * 2);
  3949. corners.forEach(function (corner, i) {
  3950. if (i === 0) {
  3951. lines[lines.length - 2] = corner.startX;
  3952. lines[lines.length - 1] = corner.startY;
  3953. } else {
  3954. lines[i * 4 - 2] = corner.startX;
  3955. lines[i * 4 - 1] = corner.startY;
  3956. }
  3957. lines[i * 4] = corner.stopX;
  3958. lines[i * 4 + 1] = corner.stopY;
  3959. intersection = intersectLineCircle(x, y, centerX, centerY, corner.cx, corner.cy, corner.radius);
  3960. if (intersection.length !== 0) {
  3961. intersections.push(intersection[0], intersection[1]);
  3962. }
  3963. });
  3964. for (var i = 0; i < lines.length / 4; i++) {
  3965. intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[i * 4], lines[i * 4 + 1], lines[i * 4 + 2], lines[i * 4 + 3], false);
  3966. if (intersection.length !== 0) {
  3967. intersections.push(intersection[0], intersection[1]);
  3968. }
  3969. }
  3970. if (intersections.length > 2) {
  3971. var lowestIntersection = [intersections[0], intersections[1]];
  3972. var lowestSquaredDistance = Math.pow(lowestIntersection[0] - x, 2) + Math.pow(lowestIntersection[1] - y, 2);
  3973. for (var _i4 = 1; _i4 < intersections.length / 2; _i4++) {
  3974. var squaredDistance = Math.pow(intersections[_i4 * 2] - x, 2) + Math.pow(intersections[_i4 * 2 + 1] - y, 2);
  3975. if (squaredDistance <= lowestSquaredDistance) {
  3976. lowestIntersection[0] = intersections[_i4 * 2];
  3977. lowestIntersection[1] = intersections[_i4 * 2 + 1];
  3978. lowestSquaredDistance = squaredDistance;
  3979. }
  3980. }
  3981. return lowestIntersection;
  3982. }
  3983. return intersections;
  3984. };
  3985. var shortenIntersection = function shortenIntersection(intersection, offset, amount) {
  3986. var disp = [intersection[0] - offset[0], intersection[1] - offset[1]];
  3987. var length = Math.sqrt(disp[0] * disp[0] + disp[1] * disp[1]);
  3988. var lenRatio = (length - amount) / length;
  3989. if (lenRatio < 0) {
  3990. lenRatio = 0.00001;
  3991. }
  3992. return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];
  3993. };
  3994. var generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {
  3995. var points = generateUnitNgonPoints(sides, rotationRadians);
  3996. points = fitPolygonToSquare(points);
  3997. return points;
  3998. };
  3999. var fitPolygonToSquare = function fitPolygonToSquare(points) {
  4000. var x, y;
  4001. var sides = points.length / 2;
  4002. var minX = Infinity,
  4003. minY = Infinity,
  4004. maxX = -Infinity,
  4005. maxY = -Infinity;
  4006. for (var i = 0; i < sides; i++) {
  4007. x = points[2 * i];
  4008. y = points[2 * i + 1];
  4009. minX = Math.min(minX, x);
  4010. maxX = Math.max(maxX, x);
  4011. minY = Math.min(minY, y);
  4012. maxY = Math.max(maxY, y);
  4013. }
  4014. // stretch factors
  4015. var sx = 2 / (maxX - minX);
  4016. var sy = 2 / (maxY - minY);
  4017. for (var _i5 = 0; _i5 < sides; _i5++) {
  4018. x = points[2 * _i5] = points[2 * _i5] * sx;
  4019. y = points[2 * _i5 + 1] = points[2 * _i5 + 1] * sy;
  4020. minX = Math.min(minX, x);
  4021. maxX = Math.max(maxX, x);
  4022. minY = Math.min(minY, y);
  4023. maxY = Math.max(maxY, y);
  4024. }
  4025. if (minY < -1) {
  4026. for (var _i6 = 0; _i6 < sides; _i6++) {
  4027. y = points[2 * _i6 + 1] = points[2 * _i6 + 1] + (-1 - minY);
  4028. }
  4029. }
  4030. return points;
  4031. };
  4032. var generateUnitNgonPoints = function generateUnitNgonPoints(sides, rotationRadians) {
  4033. var increment = 1.0 / sides * 2 * Math.PI;
  4034. var startAngle = sides % 2 === 0 ? Math.PI / 2.0 + increment / 2.0 : Math.PI / 2.0;
  4035. startAngle += rotationRadians;
  4036. var points = new Array(sides * 2);
  4037. var currentAngle;
  4038. for (var i = 0; i < sides; i++) {
  4039. currentAngle = i * increment + startAngle;
  4040. points[2 * i] = Math.cos(currentAngle); // x
  4041. points[2 * i + 1] = Math.sin(-currentAngle); // y
  4042. }
  4043. return points;
  4044. };
  4045. // Set the default radius, unless half of width or height is smaller than default
  4046. var getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {
  4047. return Math.min(width / 4, height / 4, 8);
  4048. };
  4049. // Set the default radius
  4050. var getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {
  4051. return Math.min(width / 10, height / 10, 8);
  4052. };
  4053. var getCutRectangleCornerLength = function getCutRectangleCornerLength() {
  4054. return 8;
  4055. };
  4056. var bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {
  4057. return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];
  4058. };
  4059. // get curve width, height, and control point position offsets as a percentage of node height / width
  4060. var getBarrelCurveConstants = function getBarrelCurveConstants(width, height) {
  4061. return {
  4062. heightOffset: Math.min(15, 0.05 * height),
  4063. widthOffset: Math.min(100, 0.25 * width),
  4064. ctrlPtOffsetPct: 0.05
  4065. };
  4066. };
  4067. // Separating Axis Theorem (SAT) to determine if two polygons intersect.
  4068. // The function takes two polygons as input and returns a boolean value indicating
  4069. // whether the two polygons intersect.
  4070. function satPolygonIntersection(poly1, poly2) {
  4071. function getAxes(polygon) {
  4072. var axes = [];
  4073. for (var i = 0; i < polygon.length; i++) {
  4074. var p1 = polygon[i];
  4075. var p2 = polygon[(i + 1) % polygon.length];
  4076. var edge = {
  4077. x: p2.x - p1.x,
  4078. y: p2.y - p1.y
  4079. };
  4080. var normal = {
  4081. x: -edge.y,
  4082. y: edge.x
  4083. };
  4084. var length = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
  4085. axes.push({
  4086. x: normal.x / length,
  4087. y: normal.y / length
  4088. });
  4089. }
  4090. return axes;
  4091. }
  4092. function project(polygon, axis) {
  4093. var min = Infinity;
  4094. var max = -Infinity;
  4095. var _iterator = _createForOfIteratorHelper(polygon),
  4096. _step;
  4097. try {
  4098. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  4099. var point = _step.value;
  4100. var projection = point.x * axis.x + point.y * axis.y;
  4101. min = Math.min(min, projection);
  4102. max = Math.max(max, projection);
  4103. }
  4104. } catch (err) {
  4105. _iterator.e(err);
  4106. } finally {
  4107. _iterator.f();
  4108. }
  4109. return {
  4110. min: min,
  4111. max: max
  4112. };
  4113. }
  4114. function overlaps(proj1, proj2) {
  4115. return !(proj1.max < proj2.min || proj2.max < proj1.min);
  4116. }
  4117. var axes = [].concat(_toConsumableArray(getAxes(poly1)), _toConsumableArray(getAxes(poly2)));
  4118. var _iterator2 = _createForOfIteratorHelper(axes),
  4119. _step2;
  4120. try {
  4121. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  4122. var axis = _step2.value;
  4123. var proj1 = project(poly1, axis);
  4124. var proj2 = project(poly2, axis);
  4125. if (!overlaps(proj1, proj2)) {
  4126. return false; // No overlap, so the polygons do not intersect
  4127. }
  4128. }
  4129. } catch (err) {
  4130. _iterator2.e(err);
  4131. } finally {
  4132. _iterator2.f();
  4133. }
  4134. return true; // polygons intersect
  4135. }
  4136. var pageRankDefaults = defaults$g({
  4137. dampingFactor: 0.8,
  4138. precision: 0.000001,
  4139. iterations: 200,
  4140. weight: function weight(edge) {
  4141. return 1;
  4142. }
  4143. });
  4144. var elesfn$o = {
  4145. pageRank: function pageRank(options) {
  4146. var _pageRankDefaults = pageRankDefaults(options),
  4147. dampingFactor = _pageRankDefaults.dampingFactor,
  4148. precision = _pageRankDefaults.precision,
  4149. iterations = _pageRankDefaults.iterations,
  4150. weight = _pageRankDefaults.weight;
  4151. var cy = this._private.cy;
  4152. var _this$byGroup = this.byGroup(),
  4153. nodes = _this$byGroup.nodes,
  4154. edges = _this$byGroup.edges;
  4155. var numNodes = nodes.length;
  4156. var numNodesSqd = numNodes * numNodes;
  4157. var numEdges = edges.length;
  4158. // Construct transposed adjacency matrix
  4159. // First lets have a zeroed matrix of the right size
  4160. // We'll also keep track of the sum of each column
  4161. var matrix = new Array(numNodesSqd);
  4162. var columnSum = new Array(numNodes);
  4163. var additionalProb = (1 - dampingFactor) / numNodes;
  4164. // Create null matrix
  4165. for (var i = 0; i < numNodes; i++) {
  4166. for (var j = 0; j < numNodes; j++) {
  4167. var n = i * numNodes + j;
  4168. matrix[n] = 0;
  4169. }
  4170. columnSum[i] = 0;
  4171. }
  4172. // Now, process edges
  4173. for (var _i = 0; _i < numEdges; _i++) {
  4174. var edge = edges[_i];
  4175. var srcId = edge.data('source');
  4176. var tgtId = edge.data('target');
  4177. // Don't include loops in the matrix
  4178. if (srcId === tgtId) {
  4179. continue;
  4180. }
  4181. var s = nodes.indexOfId(srcId);
  4182. var t = nodes.indexOfId(tgtId);
  4183. var w = weight(edge);
  4184. var _n = t * numNodes + s;
  4185. // Update matrix
  4186. matrix[_n] += w;
  4187. // Update column sum
  4188. columnSum[s] += w;
  4189. }
  4190. // Add additional probability based on damping factor
  4191. // Also, take into account columns that have sum = 0
  4192. var p = 1.0 / numNodes + additionalProb; // Shorthand
  4193. // Traverse matrix, column by column
  4194. for (var _j = 0; _j < numNodes; _j++) {
  4195. if (columnSum[_j] === 0) {
  4196. // No 'links' out from node jth, assume equal probability for each possible node
  4197. for (var _i2 = 0; _i2 < numNodes; _i2++) {
  4198. var _n2 = _i2 * numNodes + _j;
  4199. matrix[_n2] = p;
  4200. }
  4201. } else {
  4202. // Node jth has outgoing link, compute normalized probabilities
  4203. for (var _i3 = 0; _i3 < numNodes; _i3++) {
  4204. var _n3 = _i3 * numNodes + _j;
  4205. matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;
  4206. }
  4207. }
  4208. }
  4209. // Compute dominant eigenvector using power method
  4210. var eigenvector = new Array(numNodes);
  4211. var temp = new Array(numNodes);
  4212. var previous;
  4213. // Start with a vector of all 1's
  4214. // Also, initialize a null vector which will be used as shorthand
  4215. for (var _i4 = 0; _i4 < numNodes; _i4++) {
  4216. eigenvector[_i4] = 1;
  4217. }
  4218. for (var iter = 0; iter < iterations; iter++) {
  4219. // Temp array with all 0's
  4220. for (var _i5 = 0; _i5 < numNodes; _i5++) {
  4221. temp[_i5] = 0;
  4222. }
  4223. // Multiply matrix with previous result
  4224. for (var _i6 = 0; _i6 < numNodes; _i6++) {
  4225. for (var _j2 = 0; _j2 < numNodes; _j2++) {
  4226. var _n4 = _i6 * numNodes + _j2;
  4227. temp[_i6] += matrix[_n4] * eigenvector[_j2];
  4228. }
  4229. }
  4230. inPlaceSumNormalize(temp);
  4231. previous = eigenvector;
  4232. eigenvector = temp;
  4233. temp = previous;
  4234. var diff = 0;
  4235. // Compute difference (squared module) of both vectors
  4236. for (var _i7 = 0; _i7 < numNodes; _i7++) {
  4237. var delta = previous[_i7] - eigenvector[_i7];
  4238. diff += delta * delta;
  4239. }
  4240. // If difference is less than the desired threshold, stop iterating
  4241. if (diff < precision) {
  4242. break;
  4243. }
  4244. }
  4245. // Construct result
  4246. var res = {
  4247. rank: function rank(node) {
  4248. node = cy.collection(node)[0];
  4249. return eigenvector[nodes.indexOf(node)];
  4250. }
  4251. };
  4252. return res;
  4253. } // pageRank
  4254. }; // elesfn
  4255. var defaults$f = defaults$g({
  4256. root: null,
  4257. weight: function weight(edge) {
  4258. return 1;
  4259. },
  4260. directed: false,
  4261. alpha: 0
  4262. });
  4263. var elesfn$n = {
  4264. degreeCentralityNormalized: function degreeCentralityNormalized(options) {
  4265. options = defaults$f(options);
  4266. var cy = this.cy();
  4267. var nodes = this.nodes();
  4268. var numNodes = nodes.length;
  4269. if (!options.directed) {
  4270. var degrees = {};
  4271. var maxDegree = 0;
  4272. for (var i = 0; i < numNodes; i++) {
  4273. var node = nodes[i];
  4274. // add current node to the current options object and call degreeCentrality
  4275. options.root = node;
  4276. var currDegree = this.degreeCentrality(options);
  4277. if (maxDegree < currDegree.degree) {
  4278. maxDegree = currDegree.degree;
  4279. }
  4280. degrees[node.id()] = currDegree.degree;
  4281. }
  4282. return {
  4283. degree: function degree(node) {
  4284. if (maxDegree === 0) {
  4285. return 0;
  4286. }
  4287. if (string(node)) {
  4288. // from is a selector string
  4289. node = cy.filter(node);
  4290. }
  4291. return degrees[node.id()] / maxDegree;
  4292. }
  4293. };
  4294. } else {
  4295. var indegrees = {};
  4296. var outdegrees = {};
  4297. var maxIndegree = 0;
  4298. var maxOutdegree = 0;
  4299. for (var _i = 0; _i < numNodes; _i++) {
  4300. var _node = nodes[_i];
  4301. var id = _node.id();
  4302. // add current node to the current options object and call degreeCentrality
  4303. options.root = _node;
  4304. var _currDegree = this.degreeCentrality(options);
  4305. if (maxIndegree < _currDegree.indegree) maxIndegree = _currDegree.indegree;
  4306. if (maxOutdegree < _currDegree.outdegree) maxOutdegree = _currDegree.outdegree;
  4307. indegrees[id] = _currDegree.indegree;
  4308. outdegrees[id] = _currDegree.outdegree;
  4309. }
  4310. return {
  4311. indegree: function indegree(node) {
  4312. if (maxIndegree == 0) {
  4313. return 0;
  4314. }
  4315. if (string(node)) {
  4316. // from is a selector string
  4317. node = cy.filter(node);
  4318. }
  4319. return indegrees[node.id()] / maxIndegree;
  4320. },
  4321. outdegree: function outdegree(node) {
  4322. if (maxOutdegree === 0) {
  4323. return 0;
  4324. }
  4325. if (string(node)) {
  4326. // from is a selector string
  4327. node = cy.filter(node);
  4328. }
  4329. return outdegrees[node.id()] / maxOutdegree;
  4330. }
  4331. };
  4332. }
  4333. },
  4334. // degreeCentralityNormalized
  4335. // Implemented from the algorithm in Opsahl's paper
  4336. // "Node centrality in weighted networks: Generalizing degree and shortest paths"
  4337. // check the heading 2 "Degree"
  4338. degreeCentrality: function degreeCentrality(options) {
  4339. options = defaults$f(options);
  4340. var cy = this.cy();
  4341. var callingEles = this;
  4342. var _options = options,
  4343. root = _options.root,
  4344. weight = _options.weight,
  4345. directed = _options.directed,
  4346. alpha = _options.alpha;
  4347. root = cy.collection(root)[0];
  4348. if (!directed) {
  4349. var connEdges = root.connectedEdges().intersection(callingEles);
  4350. var k = connEdges.length;
  4351. var s = 0;
  4352. // Now, sum edge weights
  4353. for (var i = 0; i < connEdges.length; i++) {
  4354. s += weight(connEdges[i]);
  4355. }
  4356. return {
  4357. degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha)
  4358. };
  4359. } else {
  4360. var edges = root.connectedEdges();
  4361. var incoming = edges.filter(function (edge) {
  4362. return edge.target().same(root) && callingEles.has(edge);
  4363. });
  4364. var outgoing = edges.filter(function (edge) {
  4365. return edge.source().same(root) && callingEles.has(edge);
  4366. });
  4367. var k_in = incoming.length;
  4368. var k_out = outgoing.length;
  4369. var s_in = 0;
  4370. var s_out = 0;
  4371. // Now, sum incoming edge weights
  4372. for (var _i2 = 0; _i2 < incoming.length; _i2++) {
  4373. s_in += weight(incoming[_i2]);
  4374. }
  4375. // Now, sum outgoing edge weights
  4376. for (var _i3 = 0; _i3 < outgoing.length; _i3++) {
  4377. s_out += weight(outgoing[_i3]);
  4378. }
  4379. return {
  4380. indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha),
  4381. outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha)
  4382. };
  4383. }
  4384. } // degreeCentrality
  4385. }; // elesfn
  4386. // nice, short mathematical alias
  4387. elesfn$n.dc = elesfn$n.degreeCentrality;
  4388. elesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;
  4389. var defaults$e = defaults$g({
  4390. harmonic: true,
  4391. weight: function weight() {
  4392. return 1;
  4393. },
  4394. directed: false,
  4395. root: null
  4396. });
  4397. var elesfn$m = {
  4398. closenessCentralityNormalized: function closenessCentralityNormalized(options) {
  4399. var _defaults = defaults$e(options),
  4400. harmonic = _defaults.harmonic,
  4401. weight = _defaults.weight,
  4402. directed = _defaults.directed;
  4403. var cy = this.cy();
  4404. var closenesses = {};
  4405. var maxCloseness = 0;
  4406. var nodes = this.nodes();
  4407. var fw = this.floydWarshall({
  4408. weight: weight,
  4409. directed: directed
  4410. });
  4411. // Compute closeness for every node and find the maximum closeness
  4412. for (var i = 0; i < nodes.length; i++) {
  4413. var currCloseness = 0;
  4414. var node_i = nodes[i];
  4415. for (var j = 0; j < nodes.length; j++) {
  4416. if (i !== j) {
  4417. var d = fw.distance(node_i, nodes[j]);
  4418. if (harmonic) {
  4419. currCloseness += 1 / d;
  4420. } else {
  4421. currCloseness += d;
  4422. }
  4423. }
  4424. }
  4425. if (!harmonic) {
  4426. currCloseness = 1 / currCloseness;
  4427. }
  4428. if (maxCloseness < currCloseness) {
  4429. maxCloseness = currCloseness;
  4430. }
  4431. closenesses[node_i.id()] = currCloseness;
  4432. }
  4433. return {
  4434. closeness: function closeness(node) {
  4435. if (maxCloseness == 0) {
  4436. return 0;
  4437. }
  4438. if (string(node)) {
  4439. // from is a selector string
  4440. node = cy.filter(node)[0].id();
  4441. } else {
  4442. // from is a node
  4443. node = node.id();
  4444. }
  4445. return closenesses[node] / maxCloseness;
  4446. }
  4447. };
  4448. },
  4449. // Implemented from pseudocode from wikipedia
  4450. closenessCentrality: function closenessCentrality(options) {
  4451. var _defaults2 = defaults$e(options),
  4452. root = _defaults2.root,
  4453. weight = _defaults2.weight,
  4454. directed = _defaults2.directed,
  4455. harmonic = _defaults2.harmonic;
  4456. root = this.filter(root)[0];
  4457. // we need distance from this node to every other node
  4458. var dijkstra = this.dijkstra({
  4459. root: root,
  4460. weight: weight,
  4461. directed: directed
  4462. });
  4463. var totalDistance = 0;
  4464. var nodes = this.nodes();
  4465. for (var i = 0; i < nodes.length; i++) {
  4466. var n = nodes[i];
  4467. if (!n.same(root)) {
  4468. var d = dijkstra.distanceTo(n);
  4469. if (harmonic) {
  4470. totalDistance += 1 / d;
  4471. } else {
  4472. totalDistance += d;
  4473. }
  4474. }
  4475. }
  4476. return harmonic ? totalDistance : 1 / totalDistance;
  4477. } // closenessCentrality
  4478. }; // elesfn
  4479. // nice, short mathematical alias
  4480. elesfn$m.cc = elesfn$m.closenessCentrality;
  4481. elesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;
  4482. var defaults$d = defaults$g({
  4483. weight: null,
  4484. directed: false
  4485. });
  4486. var elesfn$l = {
  4487. // Implemented from the algorithm in the paper "On Variants of Shortest-Path Betweenness Centrality and their Generic Computation" by Ulrik Brandes
  4488. betweennessCentrality: function betweennessCentrality(options) {
  4489. var _defaults = defaults$d(options),
  4490. directed = _defaults.directed,
  4491. weight = _defaults.weight;
  4492. var weighted = weight != null;
  4493. var cy = this.cy();
  4494. // starting
  4495. var V = this.nodes();
  4496. var A = {};
  4497. var _C = {};
  4498. var max = 0;
  4499. var C = {
  4500. set: function set(key, val) {
  4501. _C[key] = val;
  4502. if (val > max) {
  4503. max = val;
  4504. }
  4505. },
  4506. get: function get(key) {
  4507. return _C[key];
  4508. }
  4509. };
  4510. // A contains the neighborhoods of every node
  4511. for (var i = 0; i < V.length; i++) {
  4512. var v = V[i];
  4513. var vid = v.id();
  4514. if (directed) {
  4515. A[vid] = v.outgoers().nodes(); // get outgoers of every node
  4516. } else {
  4517. A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node
  4518. }
  4519. C.set(vid, 0);
  4520. }
  4521. var _loop = function _loop() {
  4522. var sid = V[s].id();
  4523. var S = []; // stack
  4524. var P = {};
  4525. var g = {};
  4526. var d = {};
  4527. var Q = new Heap(function (a, b) {
  4528. return d[a] - d[b];
  4529. }); // queue
  4530. // init dictionaries
  4531. for (var _i = 0; _i < V.length; _i++) {
  4532. var _vid = V[_i].id();
  4533. P[_vid] = [];
  4534. g[_vid] = 0;
  4535. d[_vid] = Infinity;
  4536. }
  4537. g[sid] = 1; // sigma
  4538. d[sid] = 0; // distance to s
  4539. Q.push(sid);
  4540. while (!Q.empty()) {
  4541. var _v = Q.pop();
  4542. S.push(_v);
  4543. if (weighted) {
  4544. for (var j = 0; j < A[_v].length; j++) {
  4545. var w = A[_v][j];
  4546. var vEle = cy.getElementById(_v);
  4547. var edge = undefined;
  4548. if (vEle.edgesTo(w).length > 0) {
  4549. edge = vEle.edgesTo(w)[0];
  4550. } else {
  4551. edge = w.edgesTo(vEle)[0];
  4552. }
  4553. var edgeWeight = weight(edge);
  4554. w = w.id();
  4555. if (d[w] > d[_v] + edgeWeight) {
  4556. d[w] = d[_v] + edgeWeight;
  4557. if (Q.nodes.indexOf(w) < 0) {
  4558. //if w is not in Q
  4559. Q.push(w);
  4560. } else {
  4561. // update position if w is in Q
  4562. Q.updateItem(w);
  4563. }
  4564. g[w] = 0;
  4565. P[w] = [];
  4566. }
  4567. if (d[w] == d[_v] + edgeWeight) {
  4568. g[w] = g[w] + g[_v];
  4569. P[w].push(_v);
  4570. }
  4571. }
  4572. } else {
  4573. for (var _j = 0; _j < A[_v].length; _j++) {
  4574. var _w = A[_v][_j].id();
  4575. if (d[_w] == Infinity) {
  4576. Q.push(_w);
  4577. d[_w] = d[_v] + 1;
  4578. }
  4579. if (d[_w] == d[_v] + 1) {
  4580. g[_w] = g[_w] + g[_v];
  4581. P[_w].push(_v);
  4582. }
  4583. }
  4584. }
  4585. }
  4586. var e = {};
  4587. for (var _i2 = 0; _i2 < V.length; _i2++) {
  4588. e[V[_i2].id()] = 0;
  4589. }
  4590. while (S.length > 0) {
  4591. var _w2 = S.pop();
  4592. for (var _j2 = 0; _j2 < P[_w2].length; _j2++) {
  4593. var _v2 = P[_w2][_j2];
  4594. e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]);
  4595. }
  4596. if (_w2 != V[s].id()) {
  4597. C.set(_w2, C.get(_w2) + e[_w2]);
  4598. }
  4599. }
  4600. };
  4601. for (var s = 0; s < V.length; s++) {
  4602. _loop();
  4603. }
  4604. var ret = {
  4605. betweenness: function betweenness(node) {
  4606. var id = cy.collection(node).id();
  4607. return C.get(id);
  4608. },
  4609. betweennessNormalized: function betweennessNormalized(node) {
  4610. if (max == 0) {
  4611. return 0;
  4612. }
  4613. var id = cy.collection(node).id();
  4614. return C.get(id) / max;
  4615. }
  4616. };
  4617. // alias
  4618. ret.betweennessNormalised = ret.betweennessNormalized;
  4619. return ret;
  4620. } // betweennessCentrality
  4621. }; // elesfn
  4622. // nice, short mathematical alias
  4623. elesfn$l.bc = elesfn$l.betweennessCentrality;
  4624. // Implemented by Zoe Xi @zoexi for GSOC 2016
  4625. // https://github.com/cytoscape/cytoscape.js-markov-cluster
  4626. /* eslint-disable no-unused-vars */
  4627. var defaults$c = defaults$g({
  4628. expandFactor: 2,
  4629. // affects time of computation and cluster granularity to some extent: M * M
  4630. inflateFactor: 2,
  4631. // affects cluster granularity (the greater the value, the more clusters): M(i,j) / E(j)
  4632. multFactor: 1,
  4633. // optional self loops for each node. Use a neutral value to improve cluster computations.
  4634. maxIterations: 20,
  4635. // maximum number of iterations of the MCL algorithm in a single run
  4636. attributes: [
  4637. // attributes/features used to group nodes, ie. similarity values between nodes
  4638. function (edge) {
  4639. return 1;
  4640. }]
  4641. });
  4642. /* eslint-enable */
  4643. var setOptions$3 = function setOptions(options) {
  4644. return defaults$c(options);
  4645. };
  4646. /* eslint-enable */
  4647. var getSimilarity$1 = function getSimilarity(edge, attributes) {
  4648. var total = 0;
  4649. for (var i = 0; i < attributes.length; i++) {
  4650. total += attributes[i](edge);
  4651. }
  4652. return total;
  4653. };
  4654. var addLoops = function addLoops(M, n, val) {
  4655. for (var i = 0; i < n; i++) {
  4656. M[i * n + i] = val;
  4657. }
  4658. };
  4659. var normalize = function normalize(M, n) {
  4660. var sum;
  4661. for (var col = 0; col < n; col++) {
  4662. sum = 0;
  4663. for (var row = 0; row < n; row++) {
  4664. sum += M[row * n + col];
  4665. }
  4666. for (var _row = 0; _row < n; _row++) {
  4667. M[_row * n + col] = M[_row * n + col] / sum;
  4668. }
  4669. }
  4670. };
  4671. // TODO: blocked matrix multiplication?
  4672. var mmult = function mmult(A, B, n) {
  4673. var C = new Array(n * n);
  4674. for (var i = 0; i < n; i++) {
  4675. for (var j = 0; j < n; j++) {
  4676. C[i * n + j] = 0;
  4677. }
  4678. for (var k = 0; k < n; k++) {
  4679. for (var _j = 0; _j < n; _j++) {
  4680. C[i * n + _j] += A[i * n + k] * B[k * n + _j];
  4681. }
  4682. }
  4683. }
  4684. return C;
  4685. };
  4686. var expand = function expand(M, n, expandFactor /** power **/) {
  4687. var _M = M.slice(0);
  4688. for (var p = 1; p < expandFactor; p++) {
  4689. M = mmult(M, _M, n);
  4690. }
  4691. return M;
  4692. };
  4693. var inflate = function inflate(M, n, inflateFactor /** r **/) {
  4694. var _M = new Array(n * n);
  4695. // M(i,j) ^ inflatePower
  4696. for (var i = 0; i < n * n; i++) {
  4697. _M[i] = Math.pow(M[i], inflateFactor);
  4698. }
  4699. normalize(_M, n);
  4700. return _M;
  4701. };
  4702. var hasConverged = function hasConverged(M, _M, n2, roundFactor) {
  4703. // Check that both matrices have the same elements (i,j)
  4704. for (var i = 0; i < n2; i++) {
  4705. var v1 = Math.round(M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor); // truncate to 'roundFactor' decimal places
  4706. var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);
  4707. if (v1 !== v2) {
  4708. return false;
  4709. }
  4710. }
  4711. return true;
  4712. };
  4713. var assign$2 = function assign(M, n, nodes, cy) {
  4714. var clusters = [];
  4715. for (var i = 0; i < n; i++) {
  4716. var cluster = [];
  4717. for (var j = 0; j < n; j++) {
  4718. // Row-wise attractors and elements that they attract belong in same cluster
  4719. if (Math.round(M[i * n + j] * 1000) / 1000 > 0) {
  4720. cluster.push(nodes[j]);
  4721. }
  4722. }
  4723. if (cluster.length !== 0) {
  4724. clusters.push(cy.collection(cluster));
  4725. }
  4726. }
  4727. return clusters;
  4728. };
  4729. var isDuplicate = function isDuplicate(c1, c2) {
  4730. for (var i = 0; i < c1.length; i++) {
  4731. if (!c2[i] || c1[i].id() !== c2[i].id()) {
  4732. return false;
  4733. }
  4734. }
  4735. return true;
  4736. };
  4737. var removeDuplicates = function removeDuplicates(clusters) {
  4738. for (var i = 0; i < clusters.length; i++) {
  4739. for (var j = 0; j < clusters.length; j++) {
  4740. if (i != j && isDuplicate(clusters[i], clusters[j])) {
  4741. clusters.splice(j, 1);
  4742. }
  4743. }
  4744. }
  4745. return clusters;
  4746. };
  4747. var markovClustering = function markovClustering(options) {
  4748. var nodes = this.nodes();
  4749. var edges = this.edges();
  4750. var cy = this.cy();
  4751. // Set parameters of algorithm:
  4752. var opts = setOptions$3(options);
  4753. // Map each node to its position in node array
  4754. var id2position = {};
  4755. for (var i = 0; i < nodes.length; i++) {
  4756. id2position[nodes[i].id()] = i;
  4757. }
  4758. // Generate stochastic matrix M from input graph G (should be symmetric/undirected)
  4759. var n = nodes.length,
  4760. n2 = n * n;
  4761. var M = new Array(n2),
  4762. _M;
  4763. for (var _i = 0; _i < n2; _i++) {
  4764. M[_i] = 0;
  4765. }
  4766. for (var e = 0; e < edges.length; e++) {
  4767. var edge = edges[e];
  4768. var _i2 = id2position[edge.source().id()];
  4769. var j = id2position[edge.target().id()];
  4770. var sim = getSimilarity$1(edge, opts.attributes);
  4771. M[_i2 * n + j] += sim; // G should be symmetric and undirected
  4772. M[j * n + _i2] += sim;
  4773. }
  4774. // Begin Markov cluster algorithm
  4775. // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal
  4776. addLoops(M, n, opts.multFactor);
  4777. // Step 2: M = normalize( M );
  4778. normalize(M, n);
  4779. var isStillMoving = true;
  4780. var iterations = 0;
  4781. while (isStillMoving && iterations < opts.maxIterations) {
  4782. isStillMoving = false;
  4783. // Step 3:
  4784. _M = expand(M, n, opts.expandFactor);
  4785. // Step 4:
  4786. M = inflate(_M, n, opts.inflateFactor);
  4787. // Step 5: check to see if ~steady state has been reached
  4788. if (!hasConverged(M, _M, n2, 4)) {
  4789. isStillMoving = true;
  4790. }
  4791. iterations++;
  4792. }
  4793. // Build clusters from matrix
  4794. var clusters = assign$2(M, n, nodes, cy);
  4795. // Remove duplicate clusters due to symmetry of graph and M matrix
  4796. clusters = removeDuplicates(clusters);
  4797. return clusters;
  4798. };
  4799. var markovClustering$1 = {
  4800. markovClustering: markovClustering,
  4801. mcl: markovClustering
  4802. };
  4803. // Common distance metrics for clustering algorithms
  4804. // https://en.wikipedia.org/wiki/Hierarchical_clustering#Metric
  4805. var identity$1 = function identity(x) {
  4806. return x;
  4807. };
  4808. var absDiff = function absDiff(p, q) {
  4809. return Math.abs(q - p);
  4810. };
  4811. var addAbsDiff = function addAbsDiff(total, p, q) {
  4812. return total + absDiff(p, q);
  4813. };
  4814. var addSquaredDiff = function addSquaredDiff(total, p, q) {
  4815. return total + Math.pow(q - p, 2);
  4816. };
  4817. var sqrt = function sqrt(x) {
  4818. return Math.sqrt(x);
  4819. };
  4820. var maxAbsDiff = function maxAbsDiff(currentMax, p, q) {
  4821. return Math.max(currentMax, absDiff(p, q));
  4822. };
  4823. var getDistance = function getDistance(length, getP, getQ, init, visit) {
  4824. var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity$1;
  4825. var ret = init;
  4826. var p, q;
  4827. for (var dim = 0; dim < length; dim++) {
  4828. p = getP(dim);
  4829. q = getQ(dim);
  4830. ret = visit(ret, p, q);
  4831. }
  4832. return post(ret);
  4833. };
  4834. var distances = {
  4835. euclidean: function euclidean(length, getP, getQ) {
  4836. if (length >= 2) {
  4837. return getDistance(length, getP, getQ, 0, addSquaredDiff, sqrt);
  4838. } else {
  4839. // for single attr case, more efficient to avoid sqrt
  4840. return getDistance(length, getP, getQ, 0, addAbsDiff);
  4841. }
  4842. },
  4843. squaredEuclidean: function squaredEuclidean(length, getP, getQ) {
  4844. return getDistance(length, getP, getQ, 0, addSquaredDiff);
  4845. },
  4846. manhattan: function manhattan(length, getP, getQ) {
  4847. return getDistance(length, getP, getQ, 0, addAbsDiff);
  4848. },
  4849. max: function max(length, getP, getQ) {
  4850. return getDistance(length, getP, getQ, -Infinity, maxAbsDiff);
  4851. }
  4852. };
  4853. // in case the user accidentally doesn't use camel case
  4854. distances['squared-euclidean'] = distances['squaredEuclidean'];
  4855. distances['squaredeuclidean'] = distances['squaredEuclidean'];
  4856. function clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {
  4857. var impl;
  4858. if (fn$6(method)) {
  4859. impl = method;
  4860. } else {
  4861. impl = distances[method] || distances.euclidean;
  4862. }
  4863. if (length === 0 && fn$6(method)) {
  4864. return impl(nodeP, nodeQ);
  4865. } else {
  4866. return impl(length, getP, getQ, nodeP, nodeQ);
  4867. }
  4868. }
  4869. var defaults$b = defaults$g({
  4870. k: 2,
  4871. m: 2,
  4872. sensitivityThreshold: 0.0001,
  4873. distance: 'euclidean',
  4874. maxIterations: 10,
  4875. attributes: [],
  4876. testMode: false,
  4877. testCentroids: null
  4878. });
  4879. var setOptions$2 = function setOptions(options) {
  4880. return defaults$b(options);
  4881. };
  4882. var getDist = function getDist(type, node, centroid, attributes, mode) {
  4883. var noNodeP = mode !== 'kMedoids';
  4884. var getP = noNodeP ? function (i) {
  4885. return centroid[i];
  4886. } : function (i) {
  4887. return attributes[i](centroid);
  4888. };
  4889. var getQ = function getQ(i) {
  4890. return attributes[i](node);
  4891. };
  4892. var nodeP = centroid;
  4893. var nodeQ = node;
  4894. return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);
  4895. };
  4896. var randomCentroids = function randomCentroids(nodes, k, attributes) {
  4897. var ndim = attributes.length;
  4898. var min = new Array(ndim);
  4899. var max = new Array(ndim);
  4900. var centroids = new Array(k);
  4901. var centroid = null;
  4902. // Find min, max values for each attribute dimension
  4903. for (var i = 0; i < ndim; i++) {
  4904. min[i] = nodes.min(attributes[i]).value;
  4905. max[i] = nodes.max(attributes[i]).value;
  4906. }
  4907. // Build k centroids, each represented as an n-dim feature vector
  4908. for (var c = 0; c < k; c++) {
  4909. centroid = [];
  4910. for (var _i = 0; _i < ndim; _i++) {
  4911. centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value
  4912. }
  4913. centroids[c] = centroid;
  4914. }
  4915. return centroids;
  4916. };
  4917. var classify = function classify(node, centroids, distance, attributes, type) {
  4918. var min = Infinity;
  4919. var index = 0;
  4920. for (var i = 0; i < centroids.length; i++) {
  4921. var dist = getDist(distance, node, centroids[i], attributes, type);
  4922. if (dist < min) {
  4923. min = dist;
  4924. index = i;
  4925. }
  4926. }
  4927. return index;
  4928. };
  4929. var buildCluster = function buildCluster(centroid, nodes, assignment) {
  4930. var cluster = [];
  4931. var node = null;
  4932. for (var n = 0; n < nodes.length; n++) {
  4933. node = nodes[n];
  4934. if (assignment[node.id()] === centroid) {
  4935. //console.log("Node " + node.id() + " is associated with medoid #: " + m);
  4936. cluster.push(node);
  4937. }
  4938. }
  4939. return cluster;
  4940. };
  4941. var haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {
  4942. return Math.abs(v2 - v1) <= sensitivityThreshold;
  4943. };
  4944. var haveMatricesConverged = function haveMatricesConverged(v1, v2, sensitivityThreshold) {
  4945. for (var i = 0; i < v1.length; i++) {
  4946. for (var j = 0; j < v1[i].length; j++) {
  4947. var diff = Math.abs(v1[i][j] - v2[i][j]);
  4948. if (diff > sensitivityThreshold) {
  4949. return false;
  4950. }
  4951. }
  4952. }
  4953. return true;
  4954. };
  4955. var seenBefore = function seenBefore(node, medoids, n) {
  4956. for (var i = 0; i < n; i++) {
  4957. if (node === medoids[i]) return true;
  4958. }
  4959. return false;
  4960. };
  4961. var randomMedoids = function randomMedoids(nodes, k) {
  4962. var medoids = new Array(k);
  4963. // For small data sets, the probability of medoid conflict is greater,
  4964. // so we need to check to see if we've already seen or chose this node before.
  4965. if (nodes.length < 50) {
  4966. // Randomly select k medoids from the n nodes
  4967. for (var i = 0; i < k; i++) {
  4968. var node = nodes[Math.floor(Math.random() * nodes.length)];
  4969. // If we've already chosen this node to be a medoid, don't choose it again (for small data sets).
  4970. // Instead choose a different random node.
  4971. while (seenBefore(node, medoids, i)) {
  4972. node = nodes[Math.floor(Math.random() * nodes.length)];
  4973. }
  4974. medoids[i] = node;
  4975. }
  4976. } else {
  4977. // Relatively large data set, so pretty safe to not check and just select random nodes
  4978. for (var _i2 = 0; _i2 < k; _i2++) {
  4979. medoids[_i2] = nodes[Math.floor(Math.random() * nodes.length)];
  4980. }
  4981. }
  4982. return medoids;
  4983. };
  4984. var findCost = function findCost(potentialNewMedoid, cluster, attributes) {
  4985. var cost = 0;
  4986. for (var n = 0; n < cluster.length; n++) {
  4987. cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');
  4988. }
  4989. return cost;
  4990. };
  4991. var kMeans = function kMeans(options) {
  4992. var cy = this.cy();
  4993. var nodes = this.nodes();
  4994. var node = null;
  4995. // Set parameters of algorithm: # of clusters, distance metric, etc.
  4996. var opts = setOptions$2(options);
  4997. // Begin k-means algorithm
  4998. var clusters = new Array(opts.k);
  4999. var assignment = {};
  5000. var centroids;
  5001. // Step 1: Initialize centroid positions
  5002. if (opts.testMode) {
  5003. if (typeof opts.testCentroids === 'number') {
  5004. // TODO: implement a seeded random number generator.
  5005. opts.testCentroids;
  5006. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5007. } else if (_typeof(opts.testCentroids) === 'object') {
  5008. centroids = opts.testCentroids;
  5009. } else {
  5010. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5011. }
  5012. } else {
  5013. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5014. }
  5015. var isStillMoving = true;
  5016. var iterations = 0;
  5017. while (isStillMoving && iterations < opts.maxIterations) {
  5018. // Step 2: Assign nodes to the nearest centroid
  5019. for (var n = 0; n < nodes.length; n++) {
  5020. node = nodes[n];
  5021. // Determine which cluster this node belongs to: node id => cluster #
  5022. assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');
  5023. }
  5024. // Step 3: For each of the k clusters, update its centroid
  5025. isStillMoving = false;
  5026. for (var c = 0; c < opts.k; c++) {
  5027. // Get all nodes that belong to this cluster
  5028. var cluster = buildCluster(c, nodes, assignment);
  5029. if (cluster.length === 0) {
  5030. // If cluster is empty, break out early & move to next cluster
  5031. continue;
  5032. }
  5033. // Update centroids by calculating avg of all nodes within the cluster.
  5034. var ndim = opts.attributes.length;
  5035. var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]
  5036. var newCentroid = new Array(ndim);
  5037. var sum = new Array(ndim);
  5038. for (var d = 0; d < ndim; d++) {
  5039. sum[d] = 0.0;
  5040. for (var i = 0; i < cluster.length; i++) {
  5041. node = cluster[i];
  5042. sum[d] += opts.attributes[d](node);
  5043. }
  5044. newCentroid[d] = sum[d] / cluster.length;
  5045. // Check to see if algorithm has converged, i.e. when centroids no longer change
  5046. if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {
  5047. isStillMoving = true;
  5048. }
  5049. }
  5050. centroids[c] = newCentroid;
  5051. clusters[c] = cy.collection(cluster);
  5052. }
  5053. iterations++;
  5054. }
  5055. return clusters;
  5056. };
  5057. var kMedoids = function kMedoids(options) {
  5058. var cy = this.cy();
  5059. var nodes = this.nodes();
  5060. var node = null;
  5061. var opts = setOptions$2(options);
  5062. // Begin k-medoids algorithm
  5063. var clusters = new Array(opts.k);
  5064. var medoids;
  5065. var assignment = {};
  5066. var curCost;
  5067. var minCosts = new Array(opts.k); // minimum cost configuration for each cluster
  5068. // Step 1: Initialize k medoids
  5069. if (opts.testMode) {
  5070. if (typeof opts.testCentroids === 'number') ; else if (_typeof(opts.testCentroids) === 'object') {
  5071. medoids = opts.testCentroids;
  5072. } else {
  5073. medoids = randomMedoids(nodes, opts.k);
  5074. }
  5075. } else {
  5076. medoids = randomMedoids(nodes, opts.k);
  5077. }
  5078. var isStillMoving = true;
  5079. var iterations = 0;
  5080. while (isStillMoving && iterations < opts.maxIterations) {
  5081. // Step 2: Assign nodes to the nearest medoid
  5082. for (var n = 0; n < nodes.length; n++) {
  5083. node = nodes[n];
  5084. // Determine which cluster this node belongs to: node id => cluster #
  5085. assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');
  5086. }
  5087. isStillMoving = false;
  5088. // Step 3: For each medoid m, and for each node associated with mediod m,
  5089. // select the node with the lowest configuration cost as new medoid.
  5090. for (var m = 0; m < medoids.length; m++) {
  5091. // Get all nodes that belong to this medoid
  5092. var cluster = buildCluster(m, nodes, assignment);
  5093. if (cluster.length === 0) {
  5094. // If cluster is empty, break out early & move to next cluster
  5095. continue;
  5096. }
  5097. minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost
  5098. // Select different medoid if its configuration has the lowest cost
  5099. for (var _n = 0; _n < cluster.length; _n++) {
  5100. curCost = findCost(cluster[_n], cluster, opts.attributes);
  5101. if (curCost < minCosts[m]) {
  5102. minCosts[m] = curCost;
  5103. medoids[m] = cluster[_n];
  5104. isStillMoving = true;
  5105. }
  5106. }
  5107. clusters[m] = cy.collection(cluster);
  5108. }
  5109. iterations++;
  5110. }
  5111. return clusters;
  5112. };
  5113. var updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {
  5114. var numerator, denominator;
  5115. for (var n = 0; n < nodes.length; n++) {
  5116. for (var c = 0; c < centroids.length; c++) {
  5117. weight[n][c] = Math.pow(U[n][c], opts.m);
  5118. }
  5119. }
  5120. for (var _c = 0; _c < centroids.length; _c++) {
  5121. for (var dim = 0; dim < opts.attributes.length; dim++) {
  5122. numerator = 0;
  5123. denominator = 0;
  5124. for (var _n2 = 0; _n2 < nodes.length; _n2++) {
  5125. numerator += weight[_n2][_c] * opts.attributes[dim](nodes[_n2]);
  5126. denominator += weight[_n2][_c];
  5127. }
  5128. centroids[_c][dim] = numerator / denominator;
  5129. }
  5130. }
  5131. };
  5132. var updateMembership = function updateMembership(U, _U, centroids, nodes, opts) {
  5133. // Save previous step
  5134. for (var i = 0; i < U.length; i++) {
  5135. _U[i] = U[i].slice();
  5136. }
  5137. var sum, numerator, denominator;
  5138. var pow = 2 / (opts.m - 1);
  5139. for (var c = 0; c < centroids.length; c++) {
  5140. for (var n = 0; n < nodes.length; n++) {
  5141. sum = 0;
  5142. for (var k = 0; k < centroids.length; k++) {
  5143. // against all other centroids
  5144. numerator = getDist(opts.distance, nodes[n], centroids[c], opts.attributes, 'cmeans');
  5145. denominator = getDist(opts.distance, nodes[n], centroids[k], opts.attributes, 'cmeans');
  5146. sum += Math.pow(numerator / denominator, pow);
  5147. }
  5148. U[n][c] = 1 / sum;
  5149. }
  5150. }
  5151. };
  5152. var assign$1 = function assign(nodes, U, opts, cy) {
  5153. var clusters = new Array(opts.k);
  5154. for (var c = 0; c < clusters.length; c++) {
  5155. clusters[c] = [];
  5156. }
  5157. var max;
  5158. var index;
  5159. for (var n = 0; n < U.length; n++) {
  5160. // for each node (U is N x C matrix)
  5161. max = -Infinity;
  5162. index = -1;
  5163. // Determine which cluster the node is most likely to belong in
  5164. for (var _c2 = 0; _c2 < U[0].length; _c2++) {
  5165. if (U[n][_c2] > max) {
  5166. max = U[n][_c2];
  5167. index = _c2;
  5168. }
  5169. }
  5170. clusters[index].push(nodes[n]);
  5171. }
  5172. // Turn every array into a collection of nodes
  5173. for (var _c3 = 0; _c3 < clusters.length; _c3++) {
  5174. clusters[_c3] = cy.collection(clusters[_c3]);
  5175. }
  5176. return clusters;
  5177. };
  5178. var fuzzyCMeans = function fuzzyCMeans(options) {
  5179. var cy = this.cy();
  5180. var nodes = this.nodes();
  5181. var opts = setOptions$2(options);
  5182. // Begin fuzzy c-means algorithm
  5183. var clusters;
  5184. var centroids;
  5185. var U;
  5186. var _U;
  5187. var weight;
  5188. // Step 1: Initialize letiables.
  5189. _U = new Array(nodes.length);
  5190. for (var i = 0; i < nodes.length; i++) {
  5191. // N x C matrix
  5192. _U[i] = new Array(opts.k);
  5193. }
  5194. U = new Array(nodes.length);
  5195. for (var _i3 = 0; _i3 < nodes.length; _i3++) {
  5196. // N x C matrix
  5197. U[_i3] = new Array(opts.k);
  5198. }
  5199. for (var _i4 = 0; _i4 < nodes.length; _i4++) {
  5200. var total = 0;
  5201. for (var j = 0; j < opts.k; j++) {
  5202. U[_i4][j] = Math.random();
  5203. total += U[_i4][j];
  5204. }
  5205. for (var _j = 0; _j < opts.k; _j++) {
  5206. U[_i4][_j] = U[_i4][_j] / total;
  5207. }
  5208. }
  5209. centroids = new Array(opts.k);
  5210. for (var _i5 = 0; _i5 < opts.k; _i5++) {
  5211. centroids[_i5] = new Array(opts.attributes.length);
  5212. }
  5213. weight = new Array(nodes.length);
  5214. for (var _i6 = 0; _i6 < nodes.length; _i6++) {
  5215. // N x C matrix
  5216. weight[_i6] = new Array(opts.k);
  5217. }
  5218. // end init FCM
  5219. var isStillMoving = true;
  5220. var iterations = 0;
  5221. while (isStillMoving && iterations < opts.maxIterations) {
  5222. isStillMoving = false;
  5223. // Step 2: Calculate the centroids for each step.
  5224. updateCentroids(centroids, nodes, U, weight, opts);
  5225. // Step 3: Update the partition matrix U.
  5226. updateMembership(U, _U, centroids, nodes, opts);
  5227. // Step 4: Check for convergence.
  5228. if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {
  5229. isStillMoving = true;
  5230. }
  5231. iterations++;
  5232. }
  5233. // Assign nodes to clusters with highest probability.
  5234. clusters = assign$1(nodes, U, opts, cy);
  5235. return {
  5236. clusters: clusters,
  5237. degreeOfMembership: U
  5238. };
  5239. };
  5240. var kClustering = {
  5241. kMeans: kMeans,
  5242. kMedoids: kMedoids,
  5243. fuzzyCMeans: fuzzyCMeans,
  5244. fcm: fuzzyCMeans
  5245. };
  5246. // Implemented by Zoe Xi @zoexi for GSOC 2016
  5247. // https://github.com/cytoscape/cytoscape.js-hierarchical
  5248. var defaults$a = defaults$g({
  5249. distance: 'euclidean',
  5250. // distance metric to compare nodes
  5251. linkage: 'min',
  5252. // linkage criterion : how to determine the distance between clusters of nodes
  5253. mode: 'threshold',
  5254. // mode:'threshold' => clusters must be threshold distance apart
  5255. threshold: Infinity,
  5256. // the distance threshold
  5257. // mode:'dendrogram' => the nodes are organised as leaves in a tree (siblings are close), merging makes clusters
  5258. addDendrogram: false,
  5259. // whether to add the dendrogram to the graph for viz
  5260. dendrogramDepth: 0,
  5261. // depth at which dendrogram branches are merged into the returned clusters
  5262. attributes: [] // array of attr functions
  5263. });
  5264. var linkageAliases = {
  5265. 'single': 'min',
  5266. 'complete': 'max'
  5267. };
  5268. var setOptions$1 = function setOptions(options) {
  5269. var opts = defaults$a(options);
  5270. var preferredAlias = linkageAliases[opts.linkage];
  5271. if (preferredAlias != null) {
  5272. opts.linkage = preferredAlias;
  5273. }
  5274. return opts;
  5275. };
  5276. var mergeClosest = function mergeClosest(clusters, index, dists, mins, opts) {
  5277. // Find two closest clusters from cached mins
  5278. var minKey = 0;
  5279. var min = Infinity;
  5280. var dist;
  5281. var attrs = opts.attributes;
  5282. var getDist = function getDist(n1, n2) {
  5283. return clusteringDistance(opts.distance, attrs.length, function (i) {
  5284. return attrs[i](n1);
  5285. }, function (i) {
  5286. return attrs[i](n2);
  5287. }, n1, n2);
  5288. };
  5289. for (var i = 0; i < clusters.length; i++) {
  5290. var key = clusters[i].key;
  5291. var _dist = dists[key][mins[key]];
  5292. if (_dist < min) {
  5293. minKey = key;
  5294. min = _dist;
  5295. }
  5296. }
  5297. if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {
  5298. return false;
  5299. }
  5300. var c1 = index[minKey];
  5301. var c2 = index[mins[minKey]];
  5302. var merged;
  5303. // Merge two closest clusters
  5304. if (opts.mode === 'dendrogram') {
  5305. merged = {
  5306. left: c1,
  5307. right: c2,
  5308. key: c1.key
  5309. };
  5310. } else {
  5311. merged = {
  5312. value: c1.value.concat(c2.value),
  5313. key: c1.key
  5314. };
  5315. }
  5316. clusters[c1.index] = merged;
  5317. clusters.splice(c2.index, 1);
  5318. index[c1.key] = merged;
  5319. // Update distances with new merged cluster
  5320. for (var _i = 0; _i < clusters.length; _i++) {
  5321. var cur = clusters[_i];
  5322. if (c1.key === cur.key) {
  5323. dist = Infinity;
  5324. } else if (opts.linkage === 'min') {
  5325. dist = dists[c1.key][cur.key];
  5326. if (dists[c1.key][cur.key] > dists[c2.key][cur.key]) {
  5327. dist = dists[c2.key][cur.key];
  5328. }
  5329. } else if (opts.linkage === 'max') {
  5330. dist = dists[c1.key][cur.key];
  5331. if (dists[c1.key][cur.key] < dists[c2.key][cur.key]) {
  5332. dist = dists[c2.key][cur.key];
  5333. }
  5334. } else if (opts.linkage === 'mean') {
  5335. dist = (dists[c1.key][cur.key] * c1.size + dists[c2.key][cur.key] * c2.size) / (c1.size + c2.size);
  5336. } else {
  5337. if (opts.mode === 'dendrogram') dist = getDist(cur.value, c1.value);else dist = getDist(cur.value[0], c1.value[0]);
  5338. }
  5339. dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric
  5340. }
  5341. // Update cached mins
  5342. for (var _i2 = 0; _i2 < clusters.length; _i2++) {
  5343. var key1 = clusters[_i2].key;
  5344. if (mins[key1] === c1.key || mins[key1] === c2.key) {
  5345. var _min = key1;
  5346. for (var j = 0; j < clusters.length; j++) {
  5347. var key2 = clusters[j].key;
  5348. if (dists[key1][key2] < dists[key1][_min]) {
  5349. _min = key2;
  5350. }
  5351. }
  5352. mins[key1] = _min;
  5353. }
  5354. clusters[_i2].index = _i2;
  5355. }
  5356. // Clean up meta data used for clustering
  5357. c1.key = c2.key = c1.index = c2.index = null;
  5358. return true;
  5359. };
  5360. var _getAllChildren = function getAllChildren(root, arr, cy) {
  5361. if (!root) return;
  5362. if (root.value) {
  5363. arr.push(root.value);
  5364. } else {
  5365. if (root.left) _getAllChildren(root.left, arr);
  5366. if (root.right) _getAllChildren(root.right, arr);
  5367. }
  5368. };
  5369. var _buildDendrogram = function buildDendrogram(root, cy) {
  5370. if (!root) return '';
  5371. if (root.left && root.right) {
  5372. var leftStr = _buildDendrogram(root.left, cy);
  5373. var rightStr = _buildDendrogram(root.right, cy);
  5374. var node = cy.add({
  5375. group: 'nodes',
  5376. data: {
  5377. id: leftStr + ',' + rightStr
  5378. }
  5379. });
  5380. cy.add({
  5381. group: 'edges',
  5382. data: {
  5383. source: leftStr,
  5384. target: node.id()
  5385. }
  5386. });
  5387. cy.add({
  5388. group: 'edges',
  5389. data: {
  5390. source: rightStr,
  5391. target: node.id()
  5392. }
  5393. });
  5394. return node.id();
  5395. } else if (root.value) {
  5396. return root.value.id();
  5397. }
  5398. };
  5399. var _buildClustersFromTree = function buildClustersFromTree(root, k, cy) {
  5400. if (!root) return [];
  5401. var left = [],
  5402. right = [],
  5403. leaves = [];
  5404. if (k === 0) {
  5405. // don't cut tree, simply return all nodes as 1 single cluster
  5406. if (root.left) _getAllChildren(root.left, left);
  5407. if (root.right) _getAllChildren(root.right, right);
  5408. leaves = left.concat(right);
  5409. return [cy.collection(leaves)];
  5410. } else if (k === 1) {
  5411. // cut at root
  5412. if (root.value) {
  5413. // leaf node
  5414. return [cy.collection(root.value)];
  5415. } else {
  5416. if (root.left) _getAllChildren(root.left, left);
  5417. if (root.right) _getAllChildren(root.right, right);
  5418. return [cy.collection(left), cy.collection(right)];
  5419. }
  5420. } else {
  5421. if (root.value) {
  5422. return [cy.collection(root.value)];
  5423. } else {
  5424. if (root.left) left = _buildClustersFromTree(root.left, k - 1, cy);
  5425. if (root.right) right = _buildClustersFromTree(root.right, k - 1, cy);
  5426. return left.concat(right);
  5427. }
  5428. }
  5429. };
  5430. var hierarchicalClustering = function hierarchicalClustering(options) {
  5431. var cy = this.cy();
  5432. var nodes = this.nodes();
  5433. // Set parameters of algorithm: linkage type, distance metric, etc.
  5434. var opts = setOptions$1(options);
  5435. var attrs = opts.attributes;
  5436. var getDist = function getDist(n1, n2) {
  5437. return clusteringDistance(opts.distance, attrs.length, function (i) {
  5438. return attrs[i](n1);
  5439. }, function (i) {
  5440. return attrs[i](n2);
  5441. }, n1, n2);
  5442. };
  5443. // Begin hierarchical algorithm
  5444. var clusters = [];
  5445. var dists = []; // distances between each pair of clusters
  5446. var mins = []; // closest cluster for each cluster
  5447. var index = []; // hash of all clusters by key
  5448. // In agglomerative (bottom-up) clustering, each node starts as its own cluster
  5449. for (var n = 0; n < nodes.length; n++) {
  5450. var cluster = {
  5451. value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],
  5452. key: n,
  5453. index: n
  5454. };
  5455. clusters[n] = cluster;
  5456. index[n] = cluster;
  5457. dists[n] = [];
  5458. mins[n] = 0;
  5459. }
  5460. // Calculate the distance between each pair of clusters
  5461. for (var i = 0; i < clusters.length; i++) {
  5462. for (var j = 0; j <= i; j++) {
  5463. var dist = undefined;
  5464. if (opts.mode === 'dendrogram') {
  5465. // modes store cluster values differently
  5466. dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);
  5467. } else {
  5468. dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);
  5469. }
  5470. dists[i][j] = dist;
  5471. dists[j][i] = dist;
  5472. if (dist < dists[i][mins[i]]) {
  5473. mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j
  5474. }
  5475. }
  5476. }
  5477. // Find the closest pair of clusters and merge them into a single cluster.
  5478. // Update distances between new cluster and each of the old clusters, and loop until threshold reached.
  5479. var merged = mergeClosest(clusters, index, dists, mins, opts);
  5480. while (merged) {
  5481. merged = mergeClosest(clusters, index, dists, mins, opts);
  5482. }
  5483. var retClusters;
  5484. // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges
  5485. // in addition to returning the clusters.
  5486. if (opts.mode === 'dendrogram') {
  5487. retClusters = _buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);
  5488. if (opts.addDendrogram) _buildDendrogram(clusters[0], cy);
  5489. } else {
  5490. // Regular mode simply returns the clusters
  5491. retClusters = new Array(clusters.length);
  5492. clusters.forEach(function (cluster, i) {
  5493. // Clean up meta data used for clustering
  5494. cluster.key = cluster.index = null;
  5495. retClusters[i] = cy.collection(cluster.value);
  5496. });
  5497. }
  5498. return retClusters;
  5499. };
  5500. var hierarchicalClustering$1 = {
  5501. hierarchicalClustering: hierarchicalClustering,
  5502. hca: hierarchicalClustering
  5503. };
  5504. // Implemented by Zoe Xi @zoexi for GSOC 2016
  5505. // https://github.com/cytoscape/cytoscape.js-affinity-propagation
  5506. var defaults$9 = defaults$g({
  5507. distance: 'euclidean',
  5508. // distance metric to compare attributes between two nodes
  5509. preference: 'median',
  5510. // suitability of a data point to serve as an exemplar
  5511. damping: 0.8,
  5512. // damping factor between [0.5, 1)
  5513. maxIterations: 1000,
  5514. // max number of iterations to run
  5515. minIterations: 100,
  5516. // min number of iterations to run in order for clustering to stop
  5517. attributes: [// functions to quantify the similarity between any two points
  5518. // e.g. node => node.data('weight')
  5519. ]
  5520. });
  5521. var setOptions = function setOptions(options) {
  5522. var dmp = options.damping;
  5523. var pref = options.preference;
  5524. if (!(0.5 <= dmp && dmp < 1)) {
  5525. error("Damping must range on [0.5, 1). Got: ".concat(dmp));
  5526. }
  5527. var validPrefs = ['median', 'mean', 'min', 'max'];
  5528. if (!(validPrefs.some(function (v) {
  5529. return v === pref;
  5530. }) || number$1(pref))) {
  5531. error("Preference must be one of [".concat(validPrefs.map(function (p) {
  5532. return "'".concat(p, "'");
  5533. }).join(', '), "] or a number. Got: ").concat(pref));
  5534. }
  5535. return defaults$9(options);
  5536. };
  5537. var getSimilarity = function getSimilarity(type, n1, n2, attributes) {
  5538. var attr = function attr(n, i) {
  5539. return attributes[i](n);
  5540. };
  5541. // nb negative because similarity should have an inverse relationship to distance
  5542. return -clusteringDistance(type, attributes.length, function (i) {
  5543. return attr(n1, i);
  5544. }, function (i) {
  5545. return attr(n2, i);
  5546. }, n1, n2);
  5547. };
  5548. var getPreference = function getPreference(S, preference) {
  5549. // larger preference = greater # of clusters
  5550. var p = null;
  5551. if (preference === 'median') {
  5552. p = median(S);
  5553. } else if (preference === 'mean') {
  5554. p = mean(S);
  5555. } else if (preference === 'min') {
  5556. p = min(S);
  5557. } else if (preference === 'max') {
  5558. p = max(S);
  5559. } else {
  5560. // Custom preference number, as set by user
  5561. p = preference;
  5562. }
  5563. return p;
  5564. };
  5565. var findExemplars = function findExemplars(n, R, A) {
  5566. var indices = [];
  5567. for (var i = 0; i < n; i++) {
  5568. if (R[i * n + i] + A[i * n + i] > 0) {
  5569. indices.push(i);
  5570. }
  5571. }
  5572. return indices;
  5573. };
  5574. var assignClusters = function assignClusters(n, S, exemplars) {
  5575. var clusters = [];
  5576. for (var i = 0; i < n; i++) {
  5577. var index = -1;
  5578. var max = -Infinity;
  5579. for (var ei = 0; ei < exemplars.length; ei++) {
  5580. var e = exemplars[ei];
  5581. if (S[i * n + e] > max) {
  5582. index = e;
  5583. max = S[i * n + e];
  5584. }
  5585. }
  5586. if (index > 0) {
  5587. clusters.push(index);
  5588. }
  5589. }
  5590. for (var _ei = 0; _ei < exemplars.length; _ei++) {
  5591. clusters[exemplars[_ei]] = exemplars[_ei];
  5592. }
  5593. return clusters;
  5594. };
  5595. var assign = function assign(n, S, exemplars) {
  5596. var clusters = assignClusters(n, S, exemplars);
  5597. for (var ei = 0; ei < exemplars.length; ei++) {
  5598. var ii = [];
  5599. for (var c = 0; c < clusters.length; c++) {
  5600. if (clusters[c] === exemplars[ei]) {
  5601. ii.push(c);
  5602. }
  5603. }
  5604. var maxI = -1;
  5605. var maxSum = -Infinity;
  5606. for (var i = 0; i < ii.length; i++) {
  5607. var sum = 0;
  5608. for (var j = 0; j < ii.length; j++) {
  5609. sum += S[ii[j] * n + ii[i]];
  5610. }
  5611. if (sum > maxSum) {
  5612. maxI = i;
  5613. maxSum = sum;
  5614. }
  5615. }
  5616. exemplars[ei] = ii[maxI];
  5617. }
  5618. clusters = assignClusters(n, S, exemplars);
  5619. return clusters;
  5620. };
  5621. var affinityPropagation = function affinityPropagation(options) {
  5622. var cy = this.cy();
  5623. var nodes = this.nodes();
  5624. var opts = setOptions(options);
  5625. // Map each node to its position in node array
  5626. var id2position = {};
  5627. for (var i = 0; i < nodes.length; i++) {
  5628. id2position[nodes[i].id()] = i;
  5629. }
  5630. // Begin affinity propagation algorithm
  5631. var n; // number of data points
  5632. var n2; // size of matrices
  5633. var S; // similarity matrix (1D array)
  5634. var p; // preference/suitability of a data point to serve as an exemplar
  5635. var R; // responsibility matrix (1D array)
  5636. var A; // availability matrix (1D array)
  5637. n = nodes.length;
  5638. n2 = n * n;
  5639. // Initialize and build S similarity matrix
  5640. S = new Array(n2);
  5641. for (var _i = 0; _i < n2; _i++) {
  5642. S[_i] = -Infinity; // for cases where two data points shouldn't be linked together
  5643. }
  5644. for (var _i2 = 0; _i2 < n; _i2++) {
  5645. for (var j = 0; j < n; j++) {
  5646. if (_i2 !== j) {
  5647. S[_i2 * n + j] = getSimilarity(opts.distance, nodes[_i2], nodes[j], opts.attributes);
  5648. }
  5649. }
  5650. }
  5651. // Place preferences on the diagonal of S
  5652. p = getPreference(S, opts.preference);
  5653. for (var _i3 = 0; _i3 < n; _i3++) {
  5654. S[_i3 * n + _i3] = p;
  5655. }
  5656. // Initialize R responsibility matrix
  5657. R = new Array(n2);
  5658. for (var _i4 = 0; _i4 < n2; _i4++) {
  5659. R[_i4] = 0.0;
  5660. }
  5661. // Initialize A availability matrix
  5662. A = new Array(n2);
  5663. for (var _i5 = 0; _i5 < n2; _i5++) {
  5664. A[_i5] = 0.0;
  5665. }
  5666. var old = new Array(n);
  5667. var Rp = new Array(n);
  5668. var se = new Array(n);
  5669. for (var _i6 = 0; _i6 < n; _i6++) {
  5670. old[_i6] = 0.0;
  5671. Rp[_i6] = 0.0;
  5672. se[_i6] = 0;
  5673. }
  5674. var e = new Array(n * opts.minIterations);
  5675. for (var _i7 = 0; _i7 < e.length; _i7++) {
  5676. e[_i7] = 0;
  5677. }
  5678. var iter;
  5679. for (iter = 0; iter < opts.maxIterations; iter++) {
  5680. // main algorithmic loop
  5681. // Update R responsibility matrix
  5682. for (var _i8 = 0; _i8 < n; _i8++) {
  5683. var max = -Infinity,
  5684. max2 = -Infinity,
  5685. maxI = -1,
  5686. AS = 0.0;
  5687. for (var _j = 0; _j < n; _j++) {
  5688. old[_j] = R[_i8 * n + _j];
  5689. AS = A[_i8 * n + _j] + S[_i8 * n + _j];
  5690. if (AS >= max) {
  5691. max2 = max;
  5692. max = AS;
  5693. maxI = _j;
  5694. } else if (AS > max2) {
  5695. max2 = AS;
  5696. }
  5697. }
  5698. for (var _j2 = 0; _j2 < n; _j2++) {
  5699. R[_i8 * n + _j2] = (1 - opts.damping) * (S[_i8 * n + _j2] - max) + opts.damping * old[_j2];
  5700. }
  5701. R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];
  5702. }
  5703. // Update A availability matrix
  5704. for (var _i9 = 0; _i9 < n; _i9++) {
  5705. var sum = 0;
  5706. for (var _j3 = 0; _j3 < n; _j3++) {
  5707. old[_j3] = A[_j3 * n + _i9];
  5708. Rp[_j3] = Math.max(0, R[_j3 * n + _i9]);
  5709. sum += Rp[_j3];
  5710. }
  5711. sum -= Rp[_i9];
  5712. Rp[_i9] = R[_i9 * n + _i9];
  5713. sum += Rp[_i9];
  5714. for (var _j4 = 0; _j4 < n; _j4++) {
  5715. A[_j4 * n + _i9] = (1 - opts.damping) * Math.min(0, sum - Rp[_j4]) + opts.damping * old[_j4];
  5716. }
  5717. A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];
  5718. }
  5719. // Check for convergence
  5720. var K = 0;
  5721. for (var _i10 = 0; _i10 < n; _i10++) {
  5722. var E = A[_i10 * n + _i10] + R[_i10 * n + _i10] > 0 ? 1 : 0;
  5723. e[iter % opts.minIterations * n + _i10] = E;
  5724. K += E;
  5725. }
  5726. if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {
  5727. var _sum = 0;
  5728. for (var _i11 = 0; _i11 < n; _i11++) {
  5729. se[_i11] = 0;
  5730. for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {
  5731. se[_i11] += e[_j5 * n + _i11];
  5732. }
  5733. if (se[_i11] === 0 || se[_i11] === opts.minIterations) {
  5734. _sum++;
  5735. }
  5736. }
  5737. if (_sum === n) {
  5738. // then we have convergence
  5739. break;
  5740. }
  5741. }
  5742. }
  5743. // Identify exemplars (cluster centers)
  5744. var exemplarsIndices = findExemplars(n, R, A);
  5745. // Assign nodes to clusters
  5746. var clusterIndices = assign(n, S, exemplarsIndices);
  5747. var clusters = {};
  5748. for (var c = 0; c < exemplarsIndices.length; c++) {
  5749. clusters[exemplarsIndices[c]] = [];
  5750. }
  5751. for (var _i12 = 0; _i12 < nodes.length; _i12++) {
  5752. var pos = id2position[nodes[_i12].id()];
  5753. var clusterIndex = clusterIndices[pos];
  5754. if (clusterIndex != null) {
  5755. // the node may have not been assigned a cluster if no valid attributes were specified
  5756. clusters[clusterIndex].push(nodes[_i12]);
  5757. }
  5758. }
  5759. var retClusters = new Array(exemplarsIndices.length);
  5760. for (var _c = 0; _c < exemplarsIndices.length; _c++) {
  5761. retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);
  5762. }
  5763. return retClusters;
  5764. };
  5765. var affinityPropagation$1 = {
  5766. affinityPropagation: affinityPropagation,
  5767. ap: affinityPropagation
  5768. };
  5769. var hierholzerDefaults = defaults$g({
  5770. root: undefined,
  5771. directed: false
  5772. });
  5773. var elesfn$k = {
  5774. hierholzer: function hierholzer(options) {
  5775. if (!plainObject(options)) {
  5776. var args = arguments;
  5777. options = {
  5778. root: args[0],
  5779. directed: args[1]
  5780. };
  5781. }
  5782. var _hierholzerDefaults = hierholzerDefaults(options),
  5783. root = _hierholzerDefaults.root,
  5784. directed = _hierholzerDefaults.directed;
  5785. var eles = this;
  5786. var dflag = false;
  5787. var oddIn;
  5788. var oddOut;
  5789. var startVertex;
  5790. if (root) startVertex = string(root) ? this.filter(root)[0].id() : root[0].id();
  5791. var nodes = {};
  5792. var edges = {};
  5793. if (directed) {
  5794. eles.forEach(function (ele) {
  5795. var id = ele.id();
  5796. if (ele.isNode()) {
  5797. var ind = ele.indegree(true);
  5798. var outd = ele.outdegree(true);
  5799. var d1 = ind - outd;
  5800. var d2 = outd - ind;
  5801. if (d1 == 1) {
  5802. if (oddIn) dflag = true;else oddIn = id;
  5803. } else if (d2 == 1) {
  5804. if (oddOut) dflag = true;else oddOut = id;
  5805. } else if (d2 > 1 || d1 > 1) {
  5806. dflag = true;
  5807. }
  5808. nodes[id] = [];
  5809. ele.outgoers().forEach(function (e) {
  5810. if (e.isEdge()) nodes[id].push(e.id());
  5811. });
  5812. } else {
  5813. edges[id] = [undefined, ele.target().id()];
  5814. }
  5815. });
  5816. } else {
  5817. eles.forEach(function (ele) {
  5818. var id = ele.id();
  5819. if (ele.isNode()) {
  5820. var d = ele.degree(true);
  5821. if (d % 2) {
  5822. if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;
  5823. }
  5824. nodes[id] = [];
  5825. ele.connectedEdges().forEach(function (e) {
  5826. return nodes[id].push(e.id());
  5827. });
  5828. } else {
  5829. edges[id] = [ele.source().id(), ele.target().id()];
  5830. }
  5831. });
  5832. }
  5833. var result = {
  5834. found: false,
  5835. trail: undefined
  5836. };
  5837. if (dflag) return result;else if (oddOut && oddIn) {
  5838. if (directed) {
  5839. if (startVertex && oddOut != startVertex) {
  5840. return result;
  5841. }
  5842. startVertex = oddOut;
  5843. } else {
  5844. if (startVertex && oddOut != startVertex && oddIn != startVertex) {
  5845. return result;
  5846. } else if (!startVertex) {
  5847. startVertex = oddOut;
  5848. }
  5849. }
  5850. } else {
  5851. if (!startVertex) startVertex = eles[0].id();
  5852. }
  5853. var walk = function walk(v) {
  5854. var currentNode = v;
  5855. var subtour = [v];
  5856. var adj, adjTail, adjHead;
  5857. while (nodes[currentNode].length) {
  5858. adj = nodes[currentNode].shift();
  5859. adjTail = edges[adj][0];
  5860. adjHead = edges[adj][1];
  5861. if (currentNode != adjHead) {
  5862. nodes[adjHead] = nodes[adjHead].filter(function (e) {
  5863. return e != adj;
  5864. });
  5865. currentNode = adjHead;
  5866. } else if (!directed && currentNode != adjTail) {
  5867. nodes[adjTail] = nodes[adjTail].filter(function (e) {
  5868. return e != adj;
  5869. });
  5870. currentNode = adjTail;
  5871. }
  5872. subtour.unshift(adj);
  5873. subtour.unshift(currentNode);
  5874. }
  5875. return subtour;
  5876. };
  5877. var trail = [];
  5878. var subtour = [];
  5879. subtour = walk(startVertex);
  5880. while (subtour.length != 1) {
  5881. if (nodes[subtour[0]].length == 0) {
  5882. trail.unshift(eles.getElementById(subtour.shift()));
  5883. trail.unshift(eles.getElementById(subtour.shift()));
  5884. } else {
  5885. subtour = walk(subtour.shift()).concat(subtour);
  5886. }
  5887. }
  5888. trail.unshift(eles.getElementById(subtour.shift())); // final node
  5889. for (var d in nodes) {
  5890. if (nodes[d].length) {
  5891. return result;
  5892. }
  5893. }
  5894. result.found = true;
  5895. result.trail = this.spawn(trail, true);
  5896. return result;
  5897. }
  5898. };
  5899. var hopcroftTarjanBiconnected = function hopcroftTarjanBiconnected() {
  5900. var eles = this;
  5901. var nodes = {};
  5902. var id = 0;
  5903. var edgeCount = 0;
  5904. var components = [];
  5905. var stack = [];
  5906. var visitedEdges = {};
  5907. var buildComponent = function buildComponent(x, y) {
  5908. var i = stack.length - 1;
  5909. var cutset = [];
  5910. var component = eles.spawn();
  5911. while (stack[i].x != x || stack[i].y != y) {
  5912. cutset.push(stack.pop().edge);
  5913. i--;
  5914. }
  5915. cutset.push(stack.pop().edge);
  5916. cutset.forEach(function (edge) {
  5917. var connectedNodes = edge.connectedNodes().intersection(eles);
  5918. component.merge(edge);
  5919. connectedNodes.forEach(function (node) {
  5920. var nodeId = node.id();
  5921. var connectedEdges = node.connectedEdges().intersection(eles);
  5922. component.merge(node);
  5923. if (!nodes[nodeId].cutVertex) {
  5924. component.merge(connectedEdges);
  5925. } else {
  5926. component.merge(connectedEdges.filter(function (edge) {
  5927. return edge.isLoop();
  5928. }));
  5929. }
  5930. });
  5931. });
  5932. components.push(component);
  5933. };
  5934. var _biconnectedSearch = function biconnectedSearch(root, currentNode, parent) {
  5935. if (root === parent) edgeCount += 1;
  5936. nodes[currentNode] = {
  5937. id: id,
  5938. low: id++,
  5939. cutVertex: false
  5940. };
  5941. var edges = eles.getElementById(currentNode).connectedEdges().intersection(eles);
  5942. if (edges.size() === 0) {
  5943. components.push(eles.spawn(eles.getElementById(currentNode)));
  5944. } else {
  5945. var sourceId, targetId, otherNodeId, edgeId;
  5946. edges.forEach(function (edge) {
  5947. sourceId = edge.source().id();
  5948. targetId = edge.target().id();
  5949. otherNodeId = sourceId === currentNode ? targetId : sourceId;
  5950. if (otherNodeId !== parent) {
  5951. edgeId = edge.id();
  5952. if (!visitedEdges[edgeId]) {
  5953. visitedEdges[edgeId] = true;
  5954. stack.push({
  5955. x: currentNode,
  5956. y: otherNodeId,
  5957. edge: edge
  5958. });
  5959. }
  5960. if (!(otherNodeId in nodes)) {
  5961. _biconnectedSearch(root, otherNodeId, currentNode);
  5962. nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].low);
  5963. if (nodes[currentNode].id <= nodes[otherNodeId].low) {
  5964. nodes[currentNode].cutVertex = true;
  5965. buildComponent(currentNode, otherNodeId);
  5966. }
  5967. } else {
  5968. nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].id);
  5969. }
  5970. }
  5971. });
  5972. }
  5973. };
  5974. eles.forEach(function (ele) {
  5975. if (ele.isNode()) {
  5976. var nodeId = ele.id();
  5977. if (!(nodeId in nodes)) {
  5978. edgeCount = 0;
  5979. _biconnectedSearch(nodeId, nodeId);
  5980. nodes[nodeId].cutVertex = edgeCount > 1;
  5981. }
  5982. }
  5983. });
  5984. var cutVertices = Object.keys(nodes).filter(function (id) {
  5985. return nodes[id].cutVertex;
  5986. }).map(function (id) {
  5987. return eles.getElementById(id);
  5988. });
  5989. return {
  5990. cut: eles.spawn(cutVertices),
  5991. components: components
  5992. };
  5993. };
  5994. var hopcroftTarjanBiconnected$1 = {
  5995. hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,
  5996. htbc: hopcroftTarjanBiconnected,
  5997. htb: hopcroftTarjanBiconnected,
  5998. hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected
  5999. };
  6000. var tarjanStronglyConnected = function tarjanStronglyConnected() {
  6001. var eles = this;
  6002. var nodes = {};
  6003. var index = 0;
  6004. var components = [];
  6005. var stack = [];
  6006. var cut = eles.spawn(eles);
  6007. var _stronglyConnectedSearch = function stronglyConnectedSearch(sourceNodeId) {
  6008. stack.push(sourceNodeId);
  6009. nodes[sourceNodeId] = {
  6010. index: index,
  6011. low: index++,
  6012. explored: false
  6013. };
  6014. var connectedEdges = eles.getElementById(sourceNodeId).connectedEdges().intersection(eles);
  6015. connectedEdges.forEach(function (edge) {
  6016. var targetNodeId = edge.target().id();
  6017. if (targetNodeId !== sourceNodeId) {
  6018. if (!(targetNodeId in nodes)) {
  6019. _stronglyConnectedSearch(targetNodeId);
  6020. }
  6021. if (!nodes[targetNodeId].explored) {
  6022. nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);
  6023. }
  6024. }
  6025. });
  6026. if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {
  6027. var componentNodes = eles.spawn();
  6028. for (;;) {
  6029. var nodeId = stack.pop();
  6030. componentNodes.merge(eles.getElementById(nodeId));
  6031. nodes[nodeId].low = nodes[sourceNodeId].index;
  6032. nodes[nodeId].explored = true;
  6033. if (nodeId === sourceNodeId) {
  6034. break;
  6035. }
  6036. }
  6037. var componentEdges = componentNodes.edgesWith(componentNodes);
  6038. var component = componentNodes.merge(componentEdges);
  6039. components.push(component);
  6040. cut = cut.difference(component);
  6041. }
  6042. };
  6043. eles.forEach(function (ele) {
  6044. if (ele.isNode()) {
  6045. var nodeId = ele.id();
  6046. if (!(nodeId in nodes)) {
  6047. _stronglyConnectedSearch(nodeId);
  6048. }
  6049. }
  6050. });
  6051. return {
  6052. cut: cut,
  6053. components: components
  6054. };
  6055. };
  6056. var tarjanStronglyConnected$1 = {
  6057. tarjanStronglyConnected: tarjanStronglyConnected,
  6058. tsc: tarjanStronglyConnected,
  6059. tscc: tarjanStronglyConnected,
  6060. tarjanStronglyConnectedComponents: tarjanStronglyConnected
  6061. };
  6062. var elesfn$j = {};
  6063. [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) {
  6064. extend(elesfn$j, props);
  6065. });
  6066. /*!
  6067. Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
  6068. Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
  6069. Licensed under The MIT License (http://opensource.org/licenses/MIT)
  6070. */
  6071. /* promise states [Promises/A+ 2.1] */
  6072. var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
  6073. var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
  6074. var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
  6075. /* promise object constructor */
  6076. var _api = function api(executor) {
  6077. /* optionally support non-constructor/plain-function call */
  6078. if (!(this instanceof _api)) return new _api(executor);
  6079. /* initialize object */
  6080. this.id = 'Thenable/1.0.7';
  6081. this.state = STATE_PENDING; /* initial state */
  6082. this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */
  6083. this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */
  6084. this.onFulfilled = []; /* initial handlers */
  6085. this.onRejected = []; /* initial handlers */
  6086. /* provide optional information-hiding proxy */
  6087. this.proxy = {
  6088. then: this.then.bind(this)
  6089. };
  6090. /* support optional executor function */
  6091. if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
  6092. };
  6093. /* promise API methods */
  6094. _api.prototype = {
  6095. /* promise resolving methods */
  6096. fulfill: function fulfill(value) {
  6097. return deliver(this, STATE_FULFILLED, 'fulfillValue', value);
  6098. },
  6099. reject: function reject(value) {
  6100. return deliver(this, STATE_REJECTED, 'rejectReason', value);
  6101. },
  6102. /* "The then Method" [Promises/A+ 1.1, 1.2, 2.2] */
  6103. then: function then(onFulfilled, onRejected) {
  6104. var curr = this;
  6105. var next = new _api(); /* [Promises/A+ 2.2.7] */
  6106. curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill')); /* [Promises/A+ 2.2.2/2.2.6] */
  6107. curr.onRejected.push(resolver(onRejected, next, 'reject')); /* [Promises/A+ 2.2.3/2.2.6] */
  6108. execute(curr);
  6109. return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */
  6110. }
  6111. };
  6112. /* deliver an action */
  6113. var deliver = function deliver(curr, state, name, value) {
  6114. if (curr.state === STATE_PENDING) {
  6115. curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */
  6116. curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */
  6117. execute(curr);
  6118. }
  6119. return curr;
  6120. };
  6121. /* execute all handlers */
  6122. var execute = function execute(curr) {
  6123. if (curr.state === STATE_FULFILLED) execute_handlers(curr, 'onFulfilled', curr.fulfillValue);else if (curr.state === STATE_REJECTED) execute_handlers(curr, 'onRejected', curr.rejectReason);
  6124. };
  6125. /* execute particular set of handlers */
  6126. var execute_handlers = function execute_handlers(curr, name, value) {
  6127. /* global setImmediate: true */
  6128. /* global setTimeout: true */
  6129. /* short-circuit processing */
  6130. if (curr[name].length === 0) return;
  6131. /* iterate over all handlers, exactly once */
  6132. var handlers = curr[name];
  6133. curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */
  6134. var func = function func() {
  6135. for (var i = 0; i < handlers.length; i++) handlers[i](value); /* [Promises/A+ 2.2.5] */
  6136. };
  6137. /* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */
  6138. if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);
  6139. };
  6140. /* generate a resolver function */
  6141. var resolver = function resolver(cb, next, method) {
  6142. return function (value) {
  6143. if (typeof cb !== 'function') /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */
  6144. next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */else {
  6145. var result;
  6146. try {
  6147. result = cb(value);
  6148. } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */ catch (e) {
  6149. next.reject(e); /* [Promises/A+ 2.2.7.2] */
  6150. return;
  6151. }
  6152. _resolve(next, result); /* [Promises/A+ 2.2.7.1] */
  6153. }
  6154. };
  6155. };
  6156. /* "Promise Resolution Procedure" */ /* [Promises/A+ 2.3] */
  6157. var _resolve = function resolve(promise, x) {
  6158. /* sanity check arguments */ /* [Promises/A+ 2.3.1] */
  6159. if (promise === x || promise.proxy === x) {
  6160. promise.reject(new TypeError('cannot resolve promise with itself'));
  6161. return;
  6162. }
  6163. /* surgically check for a "then" method
  6164. (mainly to just call the "getter" of "then" only once) */
  6165. var then;
  6166. if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {
  6167. try {
  6168. then = x.then;
  6169. } /* [Promises/A+ 2.3.3.1, 3.5] */ catch (e) {
  6170. promise.reject(e); /* [Promises/A+ 2.3.3.2] */
  6171. return;
  6172. }
  6173. }
  6174. /* handle own Thenables [Promises/A+ 2.3.2]
  6175. and similar "thenables" [Promises/A+ 2.3.3] */
  6176. if (typeof then === 'function') {
  6177. var resolved = false;
  6178. try {
  6179. /* call retrieved "then" method */ /* [Promises/A+ 2.3.3.3] */
  6180. then.call(x, /* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */
  6181. function (y) {
  6182. if (resolved) return;
  6183. resolved = true; /* [Promises/A+ 2.3.3.3.3] */
  6184. if (y === x) /* [Promises/A+ 3.6] */
  6185. promise.reject(new TypeError('circular thenable chain'));else _resolve(promise, y);
  6186. }, /* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */
  6187. function (r) {
  6188. if (resolved) return;
  6189. resolved = true; /* [Promises/A+ 2.3.3.3.3] */
  6190. promise.reject(r);
  6191. });
  6192. } catch (e) {
  6193. if (!resolved) /* [Promises/A+ 2.3.3.3.3] */
  6194. promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */
  6195. }
  6196. return;
  6197. }
  6198. /* handle other values */
  6199. promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */
  6200. };
  6201. // so we always have Promise.all()
  6202. _api.all = function (ps) {
  6203. return new _api(function (resolveAll, rejectAll) {
  6204. var vals = new Array(ps.length);
  6205. var doneCount = 0;
  6206. var fulfill = function fulfill(i, val) {
  6207. vals[i] = val;
  6208. doneCount++;
  6209. if (doneCount === ps.length) {
  6210. resolveAll(vals);
  6211. }
  6212. };
  6213. for (var i = 0; i < ps.length; i++) {
  6214. (function (i) {
  6215. var p = ps[i];
  6216. var isPromise = p != null && p.then != null;
  6217. if (isPromise) {
  6218. p.then(function (val) {
  6219. fulfill(i, val);
  6220. }, function (err) {
  6221. rejectAll(err);
  6222. });
  6223. } else {
  6224. var val = p;
  6225. fulfill(i, val);
  6226. }
  6227. })(i);
  6228. }
  6229. });
  6230. };
  6231. _api.resolve = function (val) {
  6232. return new _api(function (resolve, reject) {
  6233. resolve(val);
  6234. });
  6235. };
  6236. _api.reject = function (val) {
  6237. return new _api(function (resolve, reject) {
  6238. reject(val);
  6239. });
  6240. };
  6241. var Promise$1 = typeof Promise !== 'undefined' ? Promise : _api; // eslint-disable-line no-undef
  6242. var Animation = function Animation(target, opts, opts2) {
  6243. var isCore = core(target);
  6244. var isEle = !isCore;
  6245. var _p = this._private = extend({
  6246. duration: 1000
  6247. }, opts, opts2);
  6248. _p.target = target;
  6249. _p.style = _p.style || _p.css;
  6250. _p.started = false;
  6251. _p.playing = false;
  6252. _p.hooked = false;
  6253. _p.applying = false;
  6254. _p.progress = 0;
  6255. _p.completes = [];
  6256. _p.frames = [];
  6257. if (_p.complete && fn$6(_p.complete)) {
  6258. _p.completes.push(_p.complete);
  6259. }
  6260. if (isEle) {
  6261. var pos = target.position();
  6262. _p.startPosition = _p.startPosition || {
  6263. x: pos.x,
  6264. y: pos.y
  6265. };
  6266. _p.startStyle = _p.startStyle || target.cy().style().getAnimationStartStyle(target, _p.style);
  6267. }
  6268. if (isCore) {
  6269. var pan = target.pan();
  6270. _p.startPan = {
  6271. x: pan.x,
  6272. y: pan.y
  6273. };
  6274. _p.startZoom = target.zoom();
  6275. }
  6276. // for future timeline/animations impl
  6277. this.length = 1;
  6278. this[0] = this;
  6279. };
  6280. var anifn = Animation.prototype;
  6281. extend(anifn, {
  6282. instanceString: function instanceString() {
  6283. return 'animation';
  6284. },
  6285. hook: function hook() {
  6286. var _p = this._private;
  6287. if (!_p.hooked) {
  6288. // add to target's animation queue
  6289. var q;
  6290. var tAni = _p.target._private.animation;
  6291. if (_p.queue) {
  6292. q = tAni.queue;
  6293. } else {
  6294. q = tAni.current;
  6295. }
  6296. q.push(this);
  6297. // add to the animation loop pool
  6298. if (elementOrCollection(_p.target)) {
  6299. _p.target.cy().addToAnimationPool(_p.target);
  6300. }
  6301. _p.hooked = true;
  6302. }
  6303. return this;
  6304. },
  6305. play: function play() {
  6306. var _p = this._private;
  6307. // autorewind
  6308. if (_p.progress === 1) {
  6309. _p.progress = 0;
  6310. }
  6311. _p.playing = true;
  6312. _p.started = false; // needs to be started by animation loop
  6313. _p.stopped = false;
  6314. this.hook();
  6315. // the animation loop will start the animation...
  6316. return this;
  6317. },
  6318. playing: function playing() {
  6319. return this._private.playing;
  6320. },
  6321. apply: function apply() {
  6322. var _p = this._private;
  6323. _p.applying = true;
  6324. _p.started = false; // needs to be started by animation loop
  6325. _p.stopped = false;
  6326. this.hook();
  6327. // the animation loop will apply the animation at this progress
  6328. return this;
  6329. },
  6330. applying: function applying() {
  6331. return this._private.applying;
  6332. },
  6333. pause: function pause() {
  6334. var _p = this._private;
  6335. _p.playing = false;
  6336. _p.started = false;
  6337. return this;
  6338. },
  6339. stop: function stop() {
  6340. var _p = this._private;
  6341. _p.playing = false;
  6342. _p.started = false;
  6343. _p.stopped = true; // to be removed from animation queues
  6344. return this;
  6345. },
  6346. rewind: function rewind() {
  6347. return this.progress(0);
  6348. },
  6349. fastforward: function fastforward() {
  6350. return this.progress(1);
  6351. },
  6352. time: function time(t) {
  6353. var _p = this._private;
  6354. if (t === undefined) {
  6355. return _p.progress * _p.duration;
  6356. } else {
  6357. return this.progress(t / _p.duration);
  6358. }
  6359. },
  6360. progress: function progress(p) {
  6361. var _p = this._private;
  6362. var wasPlaying = _p.playing;
  6363. if (p === undefined) {
  6364. return _p.progress;
  6365. } else {
  6366. if (wasPlaying) {
  6367. this.pause();
  6368. }
  6369. _p.progress = p;
  6370. _p.started = false;
  6371. if (wasPlaying) {
  6372. this.play();
  6373. }
  6374. }
  6375. return this;
  6376. },
  6377. completed: function completed() {
  6378. return this._private.progress === 1;
  6379. },
  6380. reverse: function reverse() {
  6381. var _p = this._private;
  6382. var wasPlaying = _p.playing;
  6383. if (wasPlaying) {
  6384. this.pause();
  6385. }
  6386. _p.progress = 1 - _p.progress;
  6387. _p.started = false;
  6388. var swap = function swap(a, b) {
  6389. var _pa = _p[a];
  6390. if (_pa == null) {
  6391. return;
  6392. }
  6393. _p[a] = _p[b];
  6394. _p[b] = _pa;
  6395. };
  6396. swap('zoom', 'startZoom');
  6397. swap('pan', 'startPan');
  6398. swap('position', 'startPosition');
  6399. // swap styles
  6400. if (_p.style) {
  6401. for (var i = 0; i < _p.style.length; i++) {
  6402. var prop = _p.style[i];
  6403. var name = prop.name;
  6404. var startStyleProp = _p.startStyle[name];
  6405. _p.startStyle[name] = prop;
  6406. _p.style[i] = startStyleProp;
  6407. }
  6408. }
  6409. if (wasPlaying) {
  6410. this.play();
  6411. }
  6412. return this;
  6413. },
  6414. promise: function promise(type) {
  6415. var _p = this._private;
  6416. var arr;
  6417. switch (type) {
  6418. case 'frame':
  6419. arr = _p.frames;
  6420. break;
  6421. default:
  6422. case 'complete':
  6423. case 'completed':
  6424. arr = _p.completes;
  6425. }
  6426. return new Promise$1(function (resolve, reject) {
  6427. arr.push(function () {
  6428. resolve();
  6429. });
  6430. });
  6431. }
  6432. });
  6433. anifn.complete = anifn.completed;
  6434. anifn.run = anifn.play;
  6435. anifn.running = anifn.playing;
  6436. var define$3 = {
  6437. animated: function animated() {
  6438. return function animatedImpl() {
  6439. var self = this;
  6440. var selfIsArrayLike = self.length !== undefined;
  6441. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6442. var cy = this._private.cy || this;
  6443. if (!cy.styleEnabled()) {
  6444. return false;
  6445. }
  6446. var ele = all[0];
  6447. if (ele) {
  6448. return ele._private.animation.current.length > 0;
  6449. }
  6450. };
  6451. },
  6452. // animated
  6453. clearQueue: function clearQueue() {
  6454. return function clearQueueImpl() {
  6455. var self = this;
  6456. var selfIsArrayLike = self.length !== undefined;
  6457. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6458. var cy = this._private.cy || this;
  6459. if (!cy.styleEnabled()) {
  6460. return this;
  6461. }
  6462. for (var i = 0; i < all.length; i++) {
  6463. var ele = all[i];
  6464. ele._private.animation.queue = [];
  6465. }
  6466. return this;
  6467. };
  6468. },
  6469. // clearQueue
  6470. delay: function delay() {
  6471. return function delayImpl(time, complete) {
  6472. var cy = this._private.cy || this;
  6473. if (!cy.styleEnabled()) {
  6474. return this;
  6475. }
  6476. return this.animate({
  6477. delay: time,
  6478. duration: time,
  6479. complete: complete
  6480. });
  6481. };
  6482. },
  6483. // delay
  6484. delayAnimation: function delayAnimation() {
  6485. return function delayAnimationImpl(time, complete) {
  6486. var cy = this._private.cy || this;
  6487. if (!cy.styleEnabled()) {
  6488. return this;
  6489. }
  6490. return this.animation({
  6491. delay: time,
  6492. duration: time,
  6493. complete: complete
  6494. });
  6495. };
  6496. },
  6497. // delay
  6498. animation: function animation() {
  6499. return function animationImpl(properties, params) {
  6500. var self = this;
  6501. var selfIsArrayLike = self.length !== undefined;
  6502. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6503. var cy = this._private.cy || this;
  6504. var isCore = !selfIsArrayLike;
  6505. var isEles = !isCore;
  6506. if (!cy.styleEnabled()) {
  6507. return this;
  6508. }
  6509. var style = cy.style();
  6510. properties = extend({}, properties, params);
  6511. var propertiesEmpty = Object.keys(properties).length === 0;
  6512. if (propertiesEmpty) {
  6513. return new Animation(all[0], properties); // nothing to animate
  6514. }
  6515. if (properties.duration === undefined) {
  6516. properties.duration = 400;
  6517. }
  6518. switch (properties.duration) {
  6519. case 'slow':
  6520. properties.duration = 600;
  6521. break;
  6522. case 'fast':
  6523. properties.duration = 200;
  6524. break;
  6525. }
  6526. if (isEles) {
  6527. properties.style = style.getPropsList(properties.style || properties.css);
  6528. properties.css = undefined;
  6529. }
  6530. if (isEles && properties.renderedPosition != null) {
  6531. var rpos = properties.renderedPosition;
  6532. var pan = cy.pan();
  6533. var zoom = cy.zoom();
  6534. properties.position = renderedToModelPosition(rpos, zoom, pan);
  6535. }
  6536. // override pan w/ panBy if set
  6537. if (isCore && properties.panBy != null) {
  6538. var panBy = properties.panBy;
  6539. var cyPan = cy.pan();
  6540. properties.pan = {
  6541. x: cyPan.x + panBy.x,
  6542. y: cyPan.y + panBy.y
  6543. };
  6544. }
  6545. // override pan w/ center if set
  6546. var center = properties.center || properties.centre;
  6547. if (isCore && center != null) {
  6548. var centerPan = cy.getCenterPan(center.eles, properties.zoom);
  6549. if (centerPan != null) {
  6550. properties.pan = centerPan;
  6551. }
  6552. }
  6553. // override pan & zoom w/ fit if set
  6554. if (isCore && properties.fit != null) {
  6555. var fit = properties.fit;
  6556. var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);
  6557. if (fitVp != null) {
  6558. properties.pan = fitVp.pan;
  6559. properties.zoom = fitVp.zoom;
  6560. }
  6561. }
  6562. // override zoom (& potentially pan) w/ zoom obj if set
  6563. if (isCore && plainObject(properties.zoom)) {
  6564. var vp = cy.getZoomedViewport(properties.zoom);
  6565. if (vp != null) {
  6566. if (vp.zoomed) {
  6567. properties.zoom = vp.zoom;
  6568. }
  6569. if (vp.panned) {
  6570. properties.pan = vp.pan;
  6571. }
  6572. } else {
  6573. properties.zoom = null; // an inavalid zoom (e.g. no delta) gets automatically destroyed
  6574. }
  6575. }
  6576. return new Animation(all[0], properties);
  6577. };
  6578. },
  6579. // animate
  6580. animate: function animate() {
  6581. return function animateImpl(properties, params) {
  6582. var self = this;
  6583. var selfIsArrayLike = self.length !== undefined;
  6584. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6585. var cy = this._private.cy || this;
  6586. if (!cy.styleEnabled()) {
  6587. return this;
  6588. }
  6589. if (params) {
  6590. properties = extend({}, properties, params);
  6591. }
  6592. // manually hook and run the animation
  6593. for (var i = 0; i < all.length; i++) {
  6594. var ele = all[i];
  6595. var queue = ele.animated() && (properties.queue === undefined || properties.queue);
  6596. var ani = ele.animation(properties, queue ? {
  6597. queue: true
  6598. } : undefined);
  6599. ani.play();
  6600. }
  6601. return this; // chaining
  6602. };
  6603. },
  6604. // animate
  6605. stop: function stop() {
  6606. return function stopImpl(clearQueue, jumpToEnd) {
  6607. var self = this;
  6608. var selfIsArrayLike = self.length !== undefined;
  6609. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6610. var cy = this._private.cy || this;
  6611. if (!cy.styleEnabled()) {
  6612. return this;
  6613. }
  6614. for (var i = 0; i < all.length; i++) {
  6615. var ele = all[i];
  6616. var _p = ele._private;
  6617. var anis = _p.animation.current;
  6618. for (var j = 0; j < anis.length; j++) {
  6619. var ani = anis[j];
  6620. var ani_p = ani._private;
  6621. if (jumpToEnd) {
  6622. // next iteration of the animation loop, the animation
  6623. // will go straight to the end and be removed
  6624. ani_p.duration = 0;
  6625. }
  6626. }
  6627. // clear the queue of future animations
  6628. if (clearQueue) {
  6629. _p.animation.queue = [];
  6630. }
  6631. if (!jumpToEnd) {
  6632. _p.animation.current = [];
  6633. }
  6634. }
  6635. // we have to notify (the animation loop doesn't do it for us on `stop`)
  6636. cy.notify('draw');
  6637. return this;
  6638. };
  6639. } // stop
  6640. }; // define
  6641. /**
  6642. * Checks if `value` is classified as an `Array` object.
  6643. *
  6644. * @static
  6645. * @memberOf _
  6646. * @since 0.1.0
  6647. * @category Lang
  6648. * @param {*} value The value to check.
  6649. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  6650. * @example
  6651. *
  6652. * _.isArray([1, 2, 3]);
  6653. * // => true
  6654. *
  6655. * _.isArray(document.body.children);
  6656. * // => false
  6657. *
  6658. * _.isArray('abc');
  6659. * // => false
  6660. *
  6661. * _.isArray(_.noop);
  6662. * // => false
  6663. */
  6664. var isArray_1;
  6665. var hasRequiredIsArray;
  6666. function requireIsArray () {
  6667. if (hasRequiredIsArray) return isArray_1;
  6668. hasRequiredIsArray = 1;
  6669. var isArray = Array.isArray;
  6670. isArray_1 = isArray;
  6671. return isArray_1;
  6672. }
  6673. var _isKey;
  6674. var hasRequired_isKey;
  6675. function require_isKey () {
  6676. if (hasRequired_isKey) return _isKey;
  6677. hasRequired_isKey = 1;
  6678. var isArray = requireIsArray(),
  6679. isSymbol = requireIsSymbol();
  6680. /** Used to match property names within property paths. */
  6681. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  6682. reIsPlainProp = /^\w*$/;
  6683. /**
  6684. * Checks if `value` is a property name and not a property path.
  6685. *
  6686. * @private
  6687. * @param {*} value The value to check.
  6688. * @param {Object} [object] The object to query keys on.
  6689. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  6690. */
  6691. function isKey(value, object) {
  6692. if (isArray(value)) {
  6693. return false;
  6694. }
  6695. var type = typeof value;
  6696. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  6697. value == null || isSymbol(value)) {
  6698. return true;
  6699. }
  6700. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  6701. (object != null && value in Object(object));
  6702. }
  6703. _isKey = isKey;
  6704. return _isKey;
  6705. }
  6706. var isFunction_1;
  6707. var hasRequiredIsFunction;
  6708. function requireIsFunction () {
  6709. if (hasRequiredIsFunction) return isFunction_1;
  6710. hasRequiredIsFunction = 1;
  6711. var baseGetTag = require_baseGetTag(),
  6712. isObject = requireIsObject();
  6713. /** `Object#toString` result references. */
  6714. var asyncTag = '[object AsyncFunction]',
  6715. funcTag = '[object Function]',
  6716. genTag = '[object GeneratorFunction]',
  6717. proxyTag = '[object Proxy]';
  6718. /**
  6719. * Checks if `value` is classified as a `Function` object.
  6720. *
  6721. * @static
  6722. * @memberOf _
  6723. * @since 0.1.0
  6724. * @category Lang
  6725. * @param {*} value The value to check.
  6726. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  6727. * @example
  6728. *
  6729. * _.isFunction(_);
  6730. * // => true
  6731. *
  6732. * _.isFunction(/abc/);
  6733. * // => false
  6734. */
  6735. function isFunction(value) {
  6736. if (!isObject(value)) {
  6737. return false;
  6738. }
  6739. // The use of `Object#toString` avoids issues with the `typeof` operator
  6740. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  6741. var tag = baseGetTag(value);
  6742. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  6743. }
  6744. isFunction_1 = isFunction;
  6745. return isFunction_1;
  6746. }
  6747. var _coreJsData;
  6748. var hasRequired_coreJsData;
  6749. function require_coreJsData () {
  6750. if (hasRequired_coreJsData) return _coreJsData;
  6751. hasRequired_coreJsData = 1;
  6752. var root = require_root();
  6753. /** Used to detect overreaching core-js shims. */
  6754. var coreJsData = root['__core-js_shared__'];
  6755. _coreJsData = coreJsData;
  6756. return _coreJsData;
  6757. }
  6758. var _isMasked;
  6759. var hasRequired_isMasked;
  6760. function require_isMasked () {
  6761. if (hasRequired_isMasked) return _isMasked;
  6762. hasRequired_isMasked = 1;
  6763. var coreJsData = require_coreJsData();
  6764. /** Used to detect methods masquerading as native. */
  6765. var maskSrcKey = (function() {
  6766. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  6767. return uid ? ('Symbol(src)_1.' + uid) : '';
  6768. }());
  6769. /**
  6770. * Checks if `func` has its source masked.
  6771. *
  6772. * @private
  6773. * @param {Function} func The function to check.
  6774. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  6775. */
  6776. function isMasked(func) {
  6777. return !!maskSrcKey && (maskSrcKey in func);
  6778. }
  6779. _isMasked = isMasked;
  6780. return _isMasked;
  6781. }
  6782. /** Used for built-in method references. */
  6783. var _toSource;
  6784. var hasRequired_toSource;
  6785. function require_toSource () {
  6786. if (hasRequired_toSource) return _toSource;
  6787. hasRequired_toSource = 1;
  6788. var funcProto = Function.prototype;
  6789. /** Used to resolve the decompiled source of functions. */
  6790. var funcToString = funcProto.toString;
  6791. /**
  6792. * Converts `func` to its source code.
  6793. *
  6794. * @private
  6795. * @param {Function} func The function to convert.
  6796. * @returns {string} Returns the source code.
  6797. */
  6798. function toSource(func) {
  6799. if (func != null) {
  6800. try {
  6801. return funcToString.call(func);
  6802. } catch (e) {}
  6803. try {
  6804. return (func + '');
  6805. } catch (e) {}
  6806. }
  6807. return '';
  6808. }
  6809. _toSource = toSource;
  6810. return _toSource;
  6811. }
  6812. var _baseIsNative;
  6813. var hasRequired_baseIsNative;
  6814. function require_baseIsNative () {
  6815. if (hasRequired_baseIsNative) return _baseIsNative;
  6816. hasRequired_baseIsNative = 1;
  6817. var isFunction = requireIsFunction(),
  6818. isMasked = require_isMasked(),
  6819. isObject = requireIsObject(),
  6820. toSource = require_toSource();
  6821. /**
  6822. * Used to match `RegExp`
  6823. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  6824. */
  6825. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  6826. /** Used to detect host constructors (Safari). */
  6827. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  6828. /** Used for built-in method references. */
  6829. var funcProto = Function.prototype,
  6830. objectProto = Object.prototype;
  6831. /** Used to resolve the decompiled source of functions. */
  6832. var funcToString = funcProto.toString;
  6833. /** Used to check objects for own properties. */
  6834. var hasOwnProperty = objectProto.hasOwnProperty;
  6835. /** Used to detect if a method is native. */
  6836. var reIsNative = RegExp('^' +
  6837. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  6838. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  6839. );
  6840. /**
  6841. * The base implementation of `_.isNative` without bad shim checks.
  6842. *
  6843. * @private
  6844. * @param {*} value The value to check.
  6845. * @returns {boolean} Returns `true` if `value` is a native function,
  6846. * else `false`.
  6847. */
  6848. function baseIsNative(value) {
  6849. if (!isObject(value) || isMasked(value)) {
  6850. return false;
  6851. }
  6852. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  6853. return pattern.test(toSource(value));
  6854. }
  6855. _baseIsNative = baseIsNative;
  6856. return _baseIsNative;
  6857. }
  6858. /**
  6859. * Gets the value at `key` of `object`.
  6860. *
  6861. * @private
  6862. * @param {Object} [object] The object to query.
  6863. * @param {string} key The key of the property to get.
  6864. * @returns {*} Returns the property value.
  6865. */
  6866. var _getValue;
  6867. var hasRequired_getValue;
  6868. function require_getValue () {
  6869. if (hasRequired_getValue) return _getValue;
  6870. hasRequired_getValue = 1;
  6871. function getValue(object, key) {
  6872. return object == null ? undefined : object[key];
  6873. }
  6874. _getValue = getValue;
  6875. return _getValue;
  6876. }
  6877. var _getNative;
  6878. var hasRequired_getNative;
  6879. function require_getNative () {
  6880. if (hasRequired_getNative) return _getNative;
  6881. hasRequired_getNative = 1;
  6882. var baseIsNative = require_baseIsNative(),
  6883. getValue = require_getValue();
  6884. /**
  6885. * Gets the native function at `key` of `object`.
  6886. *
  6887. * @private
  6888. * @param {Object} object The object to query.
  6889. * @param {string} key The key of the method to get.
  6890. * @returns {*} Returns the function if it's native, else `undefined`.
  6891. */
  6892. function getNative(object, key) {
  6893. var value = getValue(object, key);
  6894. return baseIsNative(value) ? value : undefined;
  6895. }
  6896. _getNative = getNative;
  6897. return _getNative;
  6898. }
  6899. var _nativeCreate;
  6900. var hasRequired_nativeCreate;
  6901. function require_nativeCreate () {
  6902. if (hasRequired_nativeCreate) return _nativeCreate;
  6903. hasRequired_nativeCreate = 1;
  6904. var getNative = require_getNative();
  6905. /* Built-in method references that are verified to be native. */
  6906. var nativeCreate = getNative(Object, 'create');
  6907. _nativeCreate = nativeCreate;
  6908. return _nativeCreate;
  6909. }
  6910. var _hashClear;
  6911. var hasRequired_hashClear;
  6912. function require_hashClear () {
  6913. if (hasRequired_hashClear) return _hashClear;
  6914. hasRequired_hashClear = 1;
  6915. var nativeCreate = require_nativeCreate();
  6916. /**
  6917. * Removes all key-value entries from the hash.
  6918. *
  6919. * @private
  6920. * @name clear
  6921. * @memberOf Hash
  6922. */
  6923. function hashClear() {
  6924. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  6925. this.size = 0;
  6926. }
  6927. _hashClear = hashClear;
  6928. return _hashClear;
  6929. }
  6930. /**
  6931. * Removes `key` and its value from the hash.
  6932. *
  6933. * @private
  6934. * @name delete
  6935. * @memberOf Hash
  6936. * @param {Object} hash The hash to modify.
  6937. * @param {string} key The key of the value to remove.
  6938. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  6939. */
  6940. var _hashDelete;
  6941. var hasRequired_hashDelete;
  6942. function require_hashDelete () {
  6943. if (hasRequired_hashDelete) return _hashDelete;
  6944. hasRequired_hashDelete = 1;
  6945. function hashDelete(key) {
  6946. var result = this.has(key) && delete this.__data__[key];
  6947. this.size -= result ? 1 : 0;
  6948. return result;
  6949. }
  6950. _hashDelete = hashDelete;
  6951. return _hashDelete;
  6952. }
  6953. var _hashGet;
  6954. var hasRequired_hashGet;
  6955. function require_hashGet () {
  6956. if (hasRequired_hashGet) return _hashGet;
  6957. hasRequired_hashGet = 1;
  6958. var nativeCreate = require_nativeCreate();
  6959. /** Used to stand-in for `undefined` hash values. */
  6960. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  6961. /** Used for built-in method references. */
  6962. var objectProto = Object.prototype;
  6963. /** Used to check objects for own properties. */
  6964. var hasOwnProperty = objectProto.hasOwnProperty;
  6965. /**
  6966. * Gets the hash value for `key`.
  6967. *
  6968. * @private
  6969. * @name get
  6970. * @memberOf Hash
  6971. * @param {string} key The key of the value to get.
  6972. * @returns {*} Returns the entry value.
  6973. */
  6974. function hashGet(key) {
  6975. var data = this.__data__;
  6976. if (nativeCreate) {
  6977. var result = data[key];
  6978. return result === HASH_UNDEFINED ? undefined : result;
  6979. }
  6980. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  6981. }
  6982. _hashGet = hashGet;
  6983. return _hashGet;
  6984. }
  6985. var _hashHas;
  6986. var hasRequired_hashHas;
  6987. function require_hashHas () {
  6988. if (hasRequired_hashHas) return _hashHas;
  6989. hasRequired_hashHas = 1;
  6990. var nativeCreate = require_nativeCreate();
  6991. /** Used for built-in method references. */
  6992. var objectProto = Object.prototype;
  6993. /** Used to check objects for own properties. */
  6994. var hasOwnProperty = objectProto.hasOwnProperty;
  6995. /**
  6996. * Checks if a hash value for `key` exists.
  6997. *
  6998. * @private
  6999. * @name has
  7000. * @memberOf Hash
  7001. * @param {string} key The key of the entry to check.
  7002. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7003. */
  7004. function hashHas(key) {
  7005. var data = this.__data__;
  7006. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
  7007. }
  7008. _hashHas = hashHas;
  7009. return _hashHas;
  7010. }
  7011. var _hashSet;
  7012. var hasRequired_hashSet;
  7013. function require_hashSet () {
  7014. if (hasRequired_hashSet) return _hashSet;
  7015. hasRequired_hashSet = 1;
  7016. var nativeCreate = require_nativeCreate();
  7017. /** Used to stand-in for `undefined` hash values. */
  7018. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  7019. /**
  7020. * Sets the hash `key` to `value`.
  7021. *
  7022. * @private
  7023. * @name set
  7024. * @memberOf Hash
  7025. * @param {string} key The key of the value to set.
  7026. * @param {*} value The value to set.
  7027. * @returns {Object} Returns the hash instance.
  7028. */
  7029. function hashSet(key, value) {
  7030. var data = this.__data__;
  7031. this.size += this.has(key) ? 0 : 1;
  7032. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  7033. return this;
  7034. }
  7035. _hashSet = hashSet;
  7036. return _hashSet;
  7037. }
  7038. var _Hash;
  7039. var hasRequired_Hash;
  7040. function require_Hash () {
  7041. if (hasRequired_Hash) return _Hash;
  7042. hasRequired_Hash = 1;
  7043. var hashClear = require_hashClear(),
  7044. hashDelete = require_hashDelete(),
  7045. hashGet = require_hashGet(),
  7046. hashHas = require_hashHas(),
  7047. hashSet = require_hashSet();
  7048. /**
  7049. * Creates a hash object.
  7050. *
  7051. * @private
  7052. * @constructor
  7053. * @param {Array} [entries] The key-value pairs to cache.
  7054. */
  7055. function Hash(entries) {
  7056. var index = -1,
  7057. length = entries == null ? 0 : entries.length;
  7058. this.clear();
  7059. while (++index < length) {
  7060. var entry = entries[index];
  7061. this.set(entry[0], entry[1]);
  7062. }
  7063. }
  7064. // Add methods to `Hash`.
  7065. Hash.prototype.clear = hashClear;
  7066. Hash.prototype['delete'] = hashDelete;
  7067. Hash.prototype.get = hashGet;
  7068. Hash.prototype.has = hashHas;
  7069. Hash.prototype.set = hashSet;
  7070. _Hash = Hash;
  7071. return _Hash;
  7072. }
  7073. /**
  7074. * Removes all key-value entries from the list cache.
  7075. *
  7076. * @private
  7077. * @name clear
  7078. * @memberOf ListCache
  7079. */
  7080. var _listCacheClear;
  7081. var hasRequired_listCacheClear;
  7082. function require_listCacheClear () {
  7083. if (hasRequired_listCacheClear) return _listCacheClear;
  7084. hasRequired_listCacheClear = 1;
  7085. function listCacheClear() {
  7086. this.__data__ = [];
  7087. this.size = 0;
  7088. }
  7089. _listCacheClear = listCacheClear;
  7090. return _listCacheClear;
  7091. }
  7092. /**
  7093. * Performs a
  7094. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7095. * comparison between two values to determine if they are equivalent.
  7096. *
  7097. * @static
  7098. * @memberOf _
  7099. * @since 4.0.0
  7100. * @category Lang
  7101. * @param {*} value The value to compare.
  7102. * @param {*} other The other value to compare.
  7103. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  7104. * @example
  7105. *
  7106. * var object = { 'a': 1 };
  7107. * var other = { 'a': 1 };
  7108. *
  7109. * _.eq(object, object);
  7110. * // => true
  7111. *
  7112. * _.eq(object, other);
  7113. * // => false
  7114. *
  7115. * _.eq('a', 'a');
  7116. * // => true
  7117. *
  7118. * _.eq('a', Object('a'));
  7119. * // => false
  7120. *
  7121. * _.eq(NaN, NaN);
  7122. * // => true
  7123. */
  7124. var eq_1;
  7125. var hasRequiredEq;
  7126. function requireEq () {
  7127. if (hasRequiredEq) return eq_1;
  7128. hasRequiredEq = 1;
  7129. function eq(value, other) {
  7130. return value === other || (value !== value && other !== other);
  7131. }
  7132. eq_1 = eq;
  7133. return eq_1;
  7134. }
  7135. var _assocIndexOf;
  7136. var hasRequired_assocIndexOf;
  7137. function require_assocIndexOf () {
  7138. if (hasRequired_assocIndexOf) return _assocIndexOf;
  7139. hasRequired_assocIndexOf = 1;
  7140. var eq = requireEq();
  7141. /**
  7142. * Gets the index at which the `key` is found in `array` of key-value pairs.
  7143. *
  7144. * @private
  7145. * @param {Array} array The array to inspect.
  7146. * @param {*} key The key to search for.
  7147. * @returns {number} Returns the index of the matched value, else `-1`.
  7148. */
  7149. function assocIndexOf(array, key) {
  7150. var length = array.length;
  7151. while (length--) {
  7152. if (eq(array[length][0], key)) {
  7153. return length;
  7154. }
  7155. }
  7156. return -1;
  7157. }
  7158. _assocIndexOf = assocIndexOf;
  7159. return _assocIndexOf;
  7160. }
  7161. var _listCacheDelete;
  7162. var hasRequired_listCacheDelete;
  7163. function require_listCacheDelete () {
  7164. if (hasRequired_listCacheDelete) return _listCacheDelete;
  7165. hasRequired_listCacheDelete = 1;
  7166. var assocIndexOf = require_assocIndexOf();
  7167. /** Used for built-in method references. */
  7168. var arrayProto = Array.prototype;
  7169. /** Built-in value references. */
  7170. var splice = arrayProto.splice;
  7171. /**
  7172. * Removes `key` and its value from the list cache.
  7173. *
  7174. * @private
  7175. * @name delete
  7176. * @memberOf ListCache
  7177. * @param {string} key The key of the value to remove.
  7178. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7179. */
  7180. function listCacheDelete(key) {
  7181. var data = this.__data__,
  7182. index = assocIndexOf(data, key);
  7183. if (index < 0) {
  7184. return false;
  7185. }
  7186. var lastIndex = data.length - 1;
  7187. if (index == lastIndex) {
  7188. data.pop();
  7189. } else {
  7190. splice.call(data, index, 1);
  7191. }
  7192. --this.size;
  7193. return true;
  7194. }
  7195. _listCacheDelete = listCacheDelete;
  7196. return _listCacheDelete;
  7197. }
  7198. var _listCacheGet;
  7199. var hasRequired_listCacheGet;
  7200. function require_listCacheGet () {
  7201. if (hasRequired_listCacheGet) return _listCacheGet;
  7202. hasRequired_listCacheGet = 1;
  7203. var assocIndexOf = require_assocIndexOf();
  7204. /**
  7205. * Gets the list cache value for `key`.
  7206. *
  7207. * @private
  7208. * @name get
  7209. * @memberOf ListCache
  7210. * @param {string} key The key of the value to get.
  7211. * @returns {*} Returns the entry value.
  7212. */
  7213. function listCacheGet(key) {
  7214. var data = this.__data__,
  7215. index = assocIndexOf(data, key);
  7216. return index < 0 ? undefined : data[index][1];
  7217. }
  7218. _listCacheGet = listCacheGet;
  7219. return _listCacheGet;
  7220. }
  7221. var _listCacheHas;
  7222. var hasRequired_listCacheHas;
  7223. function require_listCacheHas () {
  7224. if (hasRequired_listCacheHas) return _listCacheHas;
  7225. hasRequired_listCacheHas = 1;
  7226. var assocIndexOf = require_assocIndexOf();
  7227. /**
  7228. * Checks if a list cache value for `key` exists.
  7229. *
  7230. * @private
  7231. * @name has
  7232. * @memberOf ListCache
  7233. * @param {string} key The key of the entry to check.
  7234. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7235. */
  7236. function listCacheHas(key) {
  7237. return assocIndexOf(this.__data__, key) > -1;
  7238. }
  7239. _listCacheHas = listCacheHas;
  7240. return _listCacheHas;
  7241. }
  7242. var _listCacheSet;
  7243. var hasRequired_listCacheSet;
  7244. function require_listCacheSet () {
  7245. if (hasRequired_listCacheSet) return _listCacheSet;
  7246. hasRequired_listCacheSet = 1;
  7247. var assocIndexOf = require_assocIndexOf();
  7248. /**
  7249. * Sets the list cache `key` to `value`.
  7250. *
  7251. * @private
  7252. * @name set
  7253. * @memberOf ListCache
  7254. * @param {string} key The key of the value to set.
  7255. * @param {*} value The value to set.
  7256. * @returns {Object} Returns the list cache instance.
  7257. */
  7258. function listCacheSet(key, value) {
  7259. var data = this.__data__,
  7260. index = assocIndexOf(data, key);
  7261. if (index < 0) {
  7262. ++this.size;
  7263. data.push([key, value]);
  7264. } else {
  7265. data[index][1] = value;
  7266. }
  7267. return this;
  7268. }
  7269. _listCacheSet = listCacheSet;
  7270. return _listCacheSet;
  7271. }
  7272. var _ListCache;
  7273. var hasRequired_ListCache;
  7274. function require_ListCache () {
  7275. if (hasRequired_ListCache) return _ListCache;
  7276. hasRequired_ListCache = 1;
  7277. var listCacheClear = require_listCacheClear(),
  7278. listCacheDelete = require_listCacheDelete(),
  7279. listCacheGet = require_listCacheGet(),
  7280. listCacheHas = require_listCacheHas(),
  7281. listCacheSet = require_listCacheSet();
  7282. /**
  7283. * Creates an list cache object.
  7284. *
  7285. * @private
  7286. * @constructor
  7287. * @param {Array} [entries] The key-value pairs to cache.
  7288. */
  7289. function ListCache(entries) {
  7290. var index = -1,
  7291. length = entries == null ? 0 : entries.length;
  7292. this.clear();
  7293. while (++index < length) {
  7294. var entry = entries[index];
  7295. this.set(entry[0], entry[1]);
  7296. }
  7297. }
  7298. // Add methods to `ListCache`.
  7299. ListCache.prototype.clear = listCacheClear;
  7300. ListCache.prototype['delete'] = listCacheDelete;
  7301. ListCache.prototype.get = listCacheGet;
  7302. ListCache.prototype.has = listCacheHas;
  7303. ListCache.prototype.set = listCacheSet;
  7304. _ListCache = ListCache;
  7305. return _ListCache;
  7306. }
  7307. var _Map;
  7308. var hasRequired_Map;
  7309. function require_Map () {
  7310. if (hasRequired_Map) return _Map;
  7311. hasRequired_Map = 1;
  7312. var getNative = require_getNative(),
  7313. root = require_root();
  7314. /* Built-in method references that are verified to be native. */
  7315. var Map = getNative(root, 'Map');
  7316. _Map = Map;
  7317. return _Map;
  7318. }
  7319. var _mapCacheClear;
  7320. var hasRequired_mapCacheClear;
  7321. function require_mapCacheClear () {
  7322. if (hasRequired_mapCacheClear) return _mapCacheClear;
  7323. hasRequired_mapCacheClear = 1;
  7324. var Hash = require_Hash(),
  7325. ListCache = require_ListCache(),
  7326. Map = require_Map();
  7327. /**
  7328. * Removes all key-value entries from the map.
  7329. *
  7330. * @private
  7331. * @name clear
  7332. * @memberOf MapCache
  7333. */
  7334. function mapCacheClear() {
  7335. this.size = 0;
  7336. this.__data__ = {
  7337. 'hash': new Hash,
  7338. 'map': new (Map || ListCache),
  7339. 'string': new Hash
  7340. };
  7341. }
  7342. _mapCacheClear = mapCacheClear;
  7343. return _mapCacheClear;
  7344. }
  7345. /**
  7346. * Checks if `value` is suitable for use as unique object key.
  7347. *
  7348. * @private
  7349. * @param {*} value The value to check.
  7350. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  7351. */
  7352. var _isKeyable;
  7353. var hasRequired_isKeyable;
  7354. function require_isKeyable () {
  7355. if (hasRequired_isKeyable) return _isKeyable;
  7356. hasRequired_isKeyable = 1;
  7357. function isKeyable(value) {
  7358. var type = typeof value;
  7359. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  7360. ? (value !== '__proto__')
  7361. : (value === null);
  7362. }
  7363. _isKeyable = isKeyable;
  7364. return _isKeyable;
  7365. }
  7366. var _getMapData;
  7367. var hasRequired_getMapData;
  7368. function require_getMapData () {
  7369. if (hasRequired_getMapData) return _getMapData;
  7370. hasRequired_getMapData = 1;
  7371. var isKeyable = require_isKeyable();
  7372. /**
  7373. * Gets the data for `map`.
  7374. *
  7375. * @private
  7376. * @param {Object} map The map to query.
  7377. * @param {string} key The reference key.
  7378. * @returns {*} Returns the map data.
  7379. */
  7380. function getMapData(map, key) {
  7381. var data = map.__data__;
  7382. return isKeyable(key)
  7383. ? data[typeof key == 'string' ? 'string' : 'hash']
  7384. : data.map;
  7385. }
  7386. _getMapData = getMapData;
  7387. return _getMapData;
  7388. }
  7389. var _mapCacheDelete;
  7390. var hasRequired_mapCacheDelete;
  7391. function require_mapCacheDelete () {
  7392. if (hasRequired_mapCacheDelete) return _mapCacheDelete;
  7393. hasRequired_mapCacheDelete = 1;
  7394. var getMapData = require_getMapData();
  7395. /**
  7396. * Removes `key` and its value from the map.
  7397. *
  7398. * @private
  7399. * @name delete
  7400. * @memberOf MapCache
  7401. * @param {string} key The key of the value to remove.
  7402. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7403. */
  7404. function mapCacheDelete(key) {
  7405. var result = getMapData(this, key)['delete'](key);
  7406. this.size -= result ? 1 : 0;
  7407. return result;
  7408. }
  7409. _mapCacheDelete = mapCacheDelete;
  7410. return _mapCacheDelete;
  7411. }
  7412. var _mapCacheGet;
  7413. var hasRequired_mapCacheGet;
  7414. function require_mapCacheGet () {
  7415. if (hasRequired_mapCacheGet) return _mapCacheGet;
  7416. hasRequired_mapCacheGet = 1;
  7417. var getMapData = require_getMapData();
  7418. /**
  7419. * Gets the map value for `key`.
  7420. *
  7421. * @private
  7422. * @name get
  7423. * @memberOf MapCache
  7424. * @param {string} key The key of the value to get.
  7425. * @returns {*} Returns the entry value.
  7426. */
  7427. function mapCacheGet(key) {
  7428. return getMapData(this, key).get(key);
  7429. }
  7430. _mapCacheGet = mapCacheGet;
  7431. return _mapCacheGet;
  7432. }
  7433. var _mapCacheHas;
  7434. var hasRequired_mapCacheHas;
  7435. function require_mapCacheHas () {
  7436. if (hasRequired_mapCacheHas) return _mapCacheHas;
  7437. hasRequired_mapCacheHas = 1;
  7438. var getMapData = require_getMapData();
  7439. /**
  7440. * Checks if a map value for `key` exists.
  7441. *
  7442. * @private
  7443. * @name has
  7444. * @memberOf MapCache
  7445. * @param {string} key The key of the entry to check.
  7446. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7447. */
  7448. function mapCacheHas(key) {
  7449. return getMapData(this, key).has(key);
  7450. }
  7451. _mapCacheHas = mapCacheHas;
  7452. return _mapCacheHas;
  7453. }
  7454. var _mapCacheSet;
  7455. var hasRequired_mapCacheSet;
  7456. function require_mapCacheSet () {
  7457. if (hasRequired_mapCacheSet) return _mapCacheSet;
  7458. hasRequired_mapCacheSet = 1;
  7459. var getMapData = require_getMapData();
  7460. /**
  7461. * Sets the map `key` to `value`.
  7462. *
  7463. * @private
  7464. * @name set
  7465. * @memberOf MapCache
  7466. * @param {string} key The key of the value to set.
  7467. * @param {*} value The value to set.
  7468. * @returns {Object} Returns the map cache instance.
  7469. */
  7470. function mapCacheSet(key, value) {
  7471. var data = getMapData(this, key),
  7472. size = data.size;
  7473. data.set(key, value);
  7474. this.size += data.size == size ? 0 : 1;
  7475. return this;
  7476. }
  7477. _mapCacheSet = mapCacheSet;
  7478. return _mapCacheSet;
  7479. }
  7480. var _MapCache;
  7481. var hasRequired_MapCache;
  7482. function require_MapCache () {
  7483. if (hasRequired_MapCache) return _MapCache;
  7484. hasRequired_MapCache = 1;
  7485. var mapCacheClear = require_mapCacheClear(),
  7486. mapCacheDelete = require_mapCacheDelete(),
  7487. mapCacheGet = require_mapCacheGet(),
  7488. mapCacheHas = require_mapCacheHas(),
  7489. mapCacheSet = require_mapCacheSet();
  7490. /**
  7491. * Creates a map cache object to store key-value pairs.
  7492. *
  7493. * @private
  7494. * @constructor
  7495. * @param {Array} [entries] The key-value pairs to cache.
  7496. */
  7497. function MapCache(entries) {
  7498. var index = -1,
  7499. length = entries == null ? 0 : entries.length;
  7500. this.clear();
  7501. while (++index < length) {
  7502. var entry = entries[index];
  7503. this.set(entry[0], entry[1]);
  7504. }
  7505. }
  7506. // Add methods to `MapCache`.
  7507. MapCache.prototype.clear = mapCacheClear;
  7508. MapCache.prototype['delete'] = mapCacheDelete;
  7509. MapCache.prototype.get = mapCacheGet;
  7510. MapCache.prototype.has = mapCacheHas;
  7511. MapCache.prototype.set = mapCacheSet;
  7512. _MapCache = MapCache;
  7513. return _MapCache;
  7514. }
  7515. var memoize_1;
  7516. var hasRequiredMemoize;
  7517. function requireMemoize () {
  7518. if (hasRequiredMemoize) return memoize_1;
  7519. hasRequiredMemoize = 1;
  7520. var MapCache = require_MapCache();
  7521. /** Error message constants. */
  7522. var FUNC_ERROR_TEXT = 'Expected a function';
  7523. /**
  7524. * Creates a function that memoizes the result of `func`. If `resolver` is
  7525. * provided, it determines the cache key for storing the result based on the
  7526. * arguments provided to the memoized function. By default, the first argument
  7527. * provided to the memoized function is used as the map cache key. The `func`
  7528. * is invoked with the `this` binding of the memoized function.
  7529. *
  7530. * **Note:** The cache is exposed as the `cache` property on the memoized
  7531. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  7532. * constructor with one whose instances implement the
  7533. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  7534. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  7535. *
  7536. * @static
  7537. * @memberOf _
  7538. * @since 0.1.0
  7539. * @category Function
  7540. * @param {Function} func The function to have its output memoized.
  7541. * @param {Function} [resolver] The function to resolve the cache key.
  7542. * @returns {Function} Returns the new memoized function.
  7543. * @example
  7544. *
  7545. * var object = { 'a': 1, 'b': 2 };
  7546. * var other = { 'c': 3, 'd': 4 };
  7547. *
  7548. * var values = _.memoize(_.values);
  7549. * values(object);
  7550. * // => [1, 2]
  7551. *
  7552. * values(other);
  7553. * // => [3, 4]
  7554. *
  7555. * object.a = 2;
  7556. * values(object);
  7557. * // => [1, 2]
  7558. *
  7559. * // Modify the result cache.
  7560. * values.cache.set(object, ['a', 'b']);
  7561. * values(object);
  7562. * // => ['a', 'b']
  7563. *
  7564. * // Replace `_.memoize.Cache`.
  7565. * _.memoize.Cache = WeakMap;
  7566. */
  7567. function memoize(func, resolver) {
  7568. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  7569. throw new TypeError(FUNC_ERROR_TEXT);
  7570. }
  7571. var memoized = function() {
  7572. var args = arguments,
  7573. key = resolver ? resolver.apply(this, args) : args[0],
  7574. cache = memoized.cache;
  7575. if (cache.has(key)) {
  7576. return cache.get(key);
  7577. }
  7578. var result = func.apply(this, args);
  7579. memoized.cache = cache.set(key, result) || cache;
  7580. return result;
  7581. };
  7582. memoized.cache = new (memoize.Cache || MapCache);
  7583. return memoized;
  7584. }
  7585. // Expose `MapCache`.
  7586. memoize.Cache = MapCache;
  7587. memoize_1 = memoize;
  7588. return memoize_1;
  7589. }
  7590. var _memoizeCapped;
  7591. var hasRequired_memoizeCapped;
  7592. function require_memoizeCapped () {
  7593. if (hasRequired_memoizeCapped) return _memoizeCapped;
  7594. hasRequired_memoizeCapped = 1;
  7595. var memoize = requireMemoize();
  7596. /** Used as the maximum memoize cache size. */
  7597. var MAX_MEMOIZE_SIZE = 500;
  7598. /**
  7599. * A specialized version of `_.memoize` which clears the memoized function's
  7600. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  7601. *
  7602. * @private
  7603. * @param {Function} func The function to have its output memoized.
  7604. * @returns {Function} Returns the new memoized function.
  7605. */
  7606. function memoizeCapped(func) {
  7607. var result = memoize(func, function(key) {
  7608. if (cache.size === MAX_MEMOIZE_SIZE) {
  7609. cache.clear();
  7610. }
  7611. return key;
  7612. });
  7613. var cache = result.cache;
  7614. return result;
  7615. }
  7616. _memoizeCapped = memoizeCapped;
  7617. return _memoizeCapped;
  7618. }
  7619. var _stringToPath;
  7620. var hasRequired_stringToPath;
  7621. function require_stringToPath () {
  7622. if (hasRequired_stringToPath) return _stringToPath;
  7623. hasRequired_stringToPath = 1;
  7624. var memoizeCapped = require_memoizeCapped();
  7625. /** Used to match property names within property paths. */
  7626. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  7627. /** Used to match backslashes in property paths. */
  7628. var reEscapeChar = /\\(\\)?/g;
  7629. /**
  7630. * Converts `string` to a property path array.
  7631. *
  7632. * @private
  7633. * @param {string} string The string to convert.
  7634. * @returns {Array} Returns the property path array.
  7635. */
  7636. var stringToPath = memoizeCapped(function(string) {
  7637. var result = [];
  7638. if (string.charCodeAt(0) === 46 /* . */) {
  7639. result.push('');
  7640. }
  7641. string.replace(rePropName, function(match, number, quote, subString) {
  7642. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  7643. });
  7644. return result;
  7645. });
  7646. _stringToPath = stringToPath;
  7647. return _stringToPath;
  7648. }
  7649. /**
  7650. * A specialized version of `_.map` for arrays without support for iteratee
  7651. * shorthands.
  7652. *
  7653. * @private
  7654. * @param {Array} [array] The array to iterate over.
  7655. * @param {Function} iteratee The function invoked per iteration.
  7656. * @returns {Array} Returns the new mapped array.
  7657. */
  7658. var _arrayMap;
  7659. var hasRequired_arrayMap;
  7660. function require_arrayMap () {
  7661. if (hasRequired_arrayMap) return _arrayMap;
  7662. hasRequired_arrayMap = 1;
  7663. function arrayMap(array, iteratee) {
  7664. var index = -1,
  7665. length = array == null ? 0 : array.length,
  7666. result = Array(length);
  7667. while (++index < length) {
  7668. result[index] = iteratee(array[index], index, array);
  7669. }
  7670. return result;
  7671. }
  7672. _arrayMap = arrayMap;
  7673. return _arrayMap;
  7674. }
  7675. var _baseToString;
  7676. var hasRequired_baseToString;
  7677. function require_baseToString () {
  7678. if (hasRequired_baseToString) return _baseToString;
  7679. hasRequired_baseToString = 1;
  7680. var Symbol = require_Symbol(),
  7681. arrayMap = require_arrayMap(),
  7682. isArray = requireIsArray(),
  7683. isSymbol = requireIsSymbol();
  7684. /** Used to convert symbols to primitives and strings. */
  7685. var symbolProto = Symbol ? Symbol.prototype : undefined,
  7686. symbolToString = symbolProto ? symbolProto.toString : undefined;
  7687. /**
  7688. * The base implementation of `_.toString` which doesn't convert nullish
  7689. * values to empty strings.
  7690. *
  7691. * @private
  7692. * @param {*} value The value to process.
  7693. * @returns {string} Returns the string.
  7694. */
  7695. function baseToString(value) {
  7696. // Exit early for strings to avoid a performance hit in some environments.
  7697. if (typeof value == 'string') {
  7698. return value;
  7699. }
  7700. if (isArray(value)) {
  7701. // Recursively convert values (susceptible to call stack limits).
  7702. return arrayMap(value, baseToString) + '';
  7703. }
  7704. if (isSymbol(value)) {
  7705. return symbolToString ? symbolToString.call(value) : '';
  7706. }
  7707. var result = (value + '');
  7708. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  7709. }
  7710. _baseToString = baseToString;
  7711. return _baseToString;
  7712. }
  7713. var toString_1;
  7714. var hasRequiredToString;
  7715. function requireToString () {
  7716. if (hasRequiredToString) return toString_1;
  7717. hasRequiredToString = 1;
  7718. var baseToString = require_baseToString();
  7719. /**
  7720. * Converts `value` to a string. An empty string is returned for `null`
  7721. * and `undefined` values. The sign of `-0` is preserved.
  7722. *
  7723. * @static
  7724. * @memberOf _
  7725. * @since 4.0.0
  7726. * @category Lang
  7727. * @param {*} value The value to convert.
  7728. * @returns {string} Returns the converted string.
  7729. * @example
  7730. *
  7731. * _.toString(null);
  7732. * // => ''
  7733. *
  7734. * _.toString(-0);
  7735. * // => '-0'
  7736. *
  7737. * _.toString([1, 2, 3]);
  7738. * // => '1,2,3'
  7739. */
  7740. function toString(value) {
  7741. return value == null ? '' : baseToString(value);
  7742. }
  7743. toString_1 = toString;
  7744. return toString_1;
  7745. }
  7746. var _castPath;
  7747. var hasRequired_castPath;
  7748. function require_castPath () {
  7749. if (hasRequired_castPath) return _castPath;
  7750. hasRequired_castPath = 1;
  7751. var isArray = requireIsArray(),
  7752. isKey = require_isKey(),
  7753. stringToPath = require_stringToPath(),
  7754. toString = requireToString();
  7755. /**
  7756. * Casts `value` to a path array if it's not one.
  7757. *
  7758. * @private
  7759. * @param {*} value The value to inspect.
  7760. * @param {Object} [object] The object to query keys on.
  7761. * @returns {Array} Returns the cast property path array.
  7762. */
  7763. function castPath(value, object) {
  7764. if (isArray(value)) {
  7765. return value;
  7766. }
  7767. return isKey(value, object) ? [value] : stringToPath(toString(value));
  7768. }
  7769. _castPath = castPath;
  7770. return _castPath;
  7771. }
  7772. var _toKey;
  7773. var hasRequired_toKey;
  7774. function require_toKey () {
  7775. if (hasRequired_toKey) return _toKey;
  7776. hasRequired_toKey = 1;
  7777. var isSymbol = requireIsSymbol();
  7778. /**
  7779. * Converts `value` to a string key if it's not a string or symbol.
  7780. *
  7781. * @private
  7782. * @param {*} value The value to inspect.
  7783. * @returns {string|symbol} Returns the key.
  7784. */
  7785. function toKey(value) {
  7786. if (typeof value == 'string' || isSymbol(value)) {
  7787. return value;
  7788. }
  7789. var result = (value + '');
  7790. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  7791. }
  7792. _toKey = toKey;
  7793. return _toKey;
  7794. }
  7795. var _baseGet;
  7796. var hasRequired_baseGet;
  7797. function require_baseGet () {
  7798. if (hasRequired_baseGet) return _baseGet;
  7799. hasRequired_baseGet = 1;
  7800. var castPath = require_castPath(),
  7801. toKey = require_toKey();
  7802. /**
  7803. * The base implementation of `_.get` without support for default values.
  7804. *
  7805. * @private
  7806. * @param {Object} object The object to query.
  7807. * @param {Array|string} path The path of the property to get.
  7808. * @returns {*} Returns the resolved value.
  7809. */
  7810. function baseGet(object, path) {
  7811. path = castPath(path, object);
  7812. var index = 0,
  7813. length = path.length;
  7814. while (object != null && index < length) {
  7815. object = object[toKey(path[index++])];
  7816. }
  7817. return (index && index == length) ? object : undefined;
  7818. }
  7819. _baseGet = baseGet;
  7820. return _baseGet;
  7821. }
  7822. var get_1;
  7823. var hasRequiredGet;
  7824. function requireGet () {
  7825. if (hasRequiredGet) return get_1;
  7826. hasRequiredGet = 1;
  7827. var baseGet = require_baseGet();
  7828. /**
  7829. * Gets the value at `path` of `object`. If the resolved value is
  7830. * `undefined`, the `defaultValue` is returned in its place.
  7831. *
  7832. * @static
  7833. * @memberOf _
  7834. * @since 3.7.0
  7835. * @category Object
  7836. * @param {Object} object The object to query.
  7837. * @param {Array|string} path The path of the property to get.
  7838. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  7839. * @returns {*} Returns the resolved value.
  7840. * @example
  7841. *
  7842. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  7843. *
  7844. * _.get(object, 'a[0].b.c');
  7845. * // => 3
  7846. *
  7847. * _.get(object, ['a', '0', 'b', 'c']);
  7848. * // => 3
  7849. *
  7850. * _.get(object, 'a.b.c', 'default');
  7851. * // => 'default'
  7852. */
  7853. function get(object, path, defaultValue) {
  7854. var result = object == null ? undefined : baseGet(object, path);
  7855. return result === undefined ? defaultValue : result;
  7856. }
  7857. get_1 = get;
  7858. return get_1;
  7859. }
  7860. var getExports = requireGet();
  7861. var get = /*@__PURE__*/getDefaultExportFromCjs(getExports);
  7862. var _defineProperty;
  7863. var hasRequired_defineProperty;
  7864. function require_defineProperty () {
  7865. if (hasRequired_defineProperty) return _defineProperty;
  7866. hasRequired_defineProperty = 1;
  7867. var getNative = require_getNative();
  7868. var defineProperty = (function() {
  7869. try {
  7870. var func = getNative(Object, 'defineProperty');
  7871. func({}, '', {});
  7872. return func;
  7873. } catch (e) {}
  7874. }());
  7875. _defineProperty = defineProperty;
  7876. return _defineProperty;
  7877. }
  7878. var _baseAssignValue;
  7879. var hasRequired_baseAssignValue;
  7880. function require_baseAssignValue () {
  7881. if (hasRequired_baseAssignValue) return _baseAssignValue;
  7882. hasRequired_baseAssignValue = 1;
  7883. var defineProperty = require_defineProperty();
  7884. /**
  7885. * The base implementation of `assignValue` and `assignMergeValue` without
  7886. * value checks.
  7887. *
  7888. * @private
  7889. * @param {Object} object The object to modify.
  7890. * @param {string} key The key of the property to assign.
  7891. * @param {*} value The value to assign.
  7892. */
  7893. function baseAssignValue(object, key, value) {
  7894. if (key == '__proto__' && defineProperty) {
  7895. defineProperty(object, key, {
  7896. 'configurable': true,
  7897. 'enumerable': true,
  7898. 'value': value,
  7899. 'writable': true
  7900. });
  7901. } else {
  7902. object[key] = value;
  7903. }
  7904. }
  7905. _baseAssignValue = baseAssignValue;
  7906. return _baseAssignValue;
  7907. }
  7908. var _assignValue;
  7909. var hasRequired_assignValue;
  7910. function require_assignValue () {
  7911. if (hasRequired_assignValue) return _assignValue;
  7912. hasRequired_assignValue = 1;
  7913. var baseAssignValue = require_baseAssignValue(),
  7914. eq = requireEq();
  7915. /** Used for built-in method references. */
  7916. var objectProto = Object.prototype;
  7917. /** Used to check objects for own properties. */
  7918. var hasOwnProperty = objectProto.hasOwnProperty;
  7919. /**
  7920. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  7921. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7922. * for equality comparisons.
  7923. *
  7924. * @private
  7925. * @param {Object} object The object to modify.
  7926. * @param {string} key The key of the property to assign.
  7927. * @param {*} value The value to assign.
  7928. */
  7929. function assignValue(object, key, value) {
  7930. var objValue = object[key];
  7931. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  7932. (value === undefined && !(key in object))) {
  7933. baseAssignValue(object, key, value);
  7934. }
  7935. }
  7936. _assignValue = assignValue;
  7937. return _assignValue;
  7938. }
  7939. /** Used as references for various `Number` constants. */
  7940. var _isIndex;
  7941. var hasRequired_isIndex;
  7942. function require_isIndex () {
  7943. if (hasRequired_isIndex) return _isIndex;
  7944. hasRequired_isIndex = 1;
  7945. var MAX_SAFE_INTEGER = 9007199254740991;
  7946. /** Used to detect unsigned integer values. */
  7947. var reIsUint = /^(?:0|[1-9]\d*)$/;
  7948. /**
  7949. * Checks if `value` is a valid array-like index.
  7950. *
  7951. * @private
  7952. * @param {*} value The value to check.
  7953. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  7954. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  7955. */
  7956. function isIndex(value, length) {
  7957. var type = typeof value;
  7958. length = length == null ? MAX_SAFE_INTEGER : length;
  7959. return !!length &&
  7960. (type == 'number' ||
  7961. (type != 'symbol' && reIsUint.test(value))) &&
  7962. (value > -1 && value % 1 == 0 && value < length);
  7963. }
  7964. _isIndex = isIndex;
  7965. return _isIndex;
  7966. }
  7967. var _baseSet;
  7968. var hasRequired_baseSet;
  7969. function require_baseSet () {
  7970. if (hasRequired_baseSet) return _baseSet;
  7971. hasRequired_baseSet = 1;
  7972. var assignValue = require_assignValue(),
  7973. castPath = require_castPath(),
  7974. isIndex = require_isIndex(),
  7975. isObject = requireIsObject(),
  7976. toKey = require_toKey();
  7977. /**
  7978. * The base implementation of `_.set`.
  7979. *
  7980. * @private
  7981. * @param {Object} object The object to modify.
  7982. * @param {Array|string} path The path of the property to set.
  7983. * @param {*} value The value to set.
  7984. * @param {Function} [customizer] The function to customize path creation.
  7985. * @returns {Object} Returns `object`.
  7986. */
  7987. function baseSet(object, path, value, customizer) {
  7988. if (!isObject(object)) {
  7989. return object;
  7990. }
  7991. path = castPath(path, object);
  7992. var index = -1,
  7993. length = path.length,
  7994. lastIndex = length - 1,
  7995. nested = object;
  7996. while (nested != null && ++index < length) {
  7997. var key = toKey(path[index]),
  7998. newValue = value;
  7999. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  8000. return object;
  8001. }
  8002. if (index != lastIndex) {
  8003. var objValue = nested[key];
  8004. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  8005. if (newValue === undefined) {
  8006. newValue = isObject(objValue)
  8007. ? objValue
  8008. : (isIndex(path[index + 1]) ? [] : {});
  8009. }
  8010. }
  8011. assignValue(nested, key, newValue);
  8012. nested = nested[key];
  8013. }
  8014. return object;
  8015. }
  8016. _baseSet = baseSet;
  8017. return _baseSet;
  8018. }
  8019. var set_1;
  8020. var hasRequiredSet;
  8021. function requireSet () {
  8022. if (hasRequiredSet) return set_1;
  8023. hasRequiredSet = 1;
  8024. var baseSet = require_baseSet();
  8025. /**
  8026. * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
  8027. * it's created. Arrays are created for missing index properties while objects
  8028. * are created for all other missing properties. Use `_.setWith` to customize
  8029. * `path` creation.
  8030. *
  8031. * **Note:** This method mutates `object`.
  8032. *
  8033. * @static
  8034. * @memberOf _
  8035. * @since 3.7.0
  8036. * @category Object
  8037. * @param {Object} object The object to modify.
  8038. * @param {Array|string} path The path of the property to set.
  8039. * @param {*} value The value to set.
  8040. * @returns {Object} Returns `object`.
  8041. * @example
  8042. *
  8043. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  8044. *
  8045. * _.set(object, 'a[0].b.c', 4);
  8046. * console.log(object.a[0].b.c);
  8047. * // => 4
  8048. *
  8049. * _.set(object, ['x', '0', 'y', 'z'], 5);
  8050. * console.log(object.x[0].y.z);
  8051. * // => 5
  8052. */
  8053. function set(object, path, value) {
  8054. return object == null ? object : baseSet(object, path, value);
  8055. }
  8056. set_1 = set;
  8057. return set_1;
  8058. }
  8059. var setExports = requireSet();
  8060. var set = /*@__PURE__*/getDefaultExportFromCjs(setExports);
  8061. /**
  8062. * Copies the values of `source` to `array`.
  8063. *
  8064. * @private
  8065. * @param {Array} source The array to copy values from.
  8066. * @param {Array} [array=[]] The array to copy values to.
  8067. * @returns {Array} Returns `array`.
  8068. */
  8069. var _copyArray;
  8070. var hasRequired_copyArray;
  8071. function require_copyArray () {
  8072. if (hasRequired_copyArray) return _copyArray;
  8073. hasRequired_copyArray = 1;
  8074. function copyArray(source, array) {
  8075. var index = -1,
  8076. length = source.length;
  8077. array || (array = Array(length));
  8078. while (++index < length) {
  8079. array[index] = source[index];
  8080. }
  8081. return array;
  8082. }
  8083. _copyArray = copyArray;
  8084. return _copyArray;
  8085. }
  8086. var toPath_1;
  8087. var hasRequiredToPath;
  8088. function requireToPath () {
  8089. if (hasRequiredToPath) return toPath_1;
  8090. hasRequiredToPath = 1;
  8091. var arrayMap = require_arrayMap(),
  8092. copyArray = require_copyArray(),
  8093. isArray = requireIsArray(),
  8094. isSymbol = requireIsSymbol(),
  8095. stringToPath = require_stringToPath(),
  8096. toKey = require_toKey(),
  8097. toString = requireToString();
  8098. /**
  8099. * Converts `value` to a property path array.
  8100. *
  8101. * @static
  8102. * @memberOf _
  8103. * @since 4.0.0
  8104. * @category Util
  8105. * @param {*} value The value to convert.
  8106. * @returns {Array} Returns the new property path array.
  8107. * @example
  8108. *
  8109. * _.toPath('a.b.c');
  8110. * // => ['a', 'b', 'c']
  8111. *
  8112. * _.toPath('a[0].b.c');
  8113. * // => ['a', '0', 'b', 'c']
  8114. */
  8115. function toPath(value) {
  8116. if (isArray(value)) {
  8117. return arrayMap(value, toKey);
  8118. }
  8119. return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
  8120. }
  8121. toPath_1 = toPath;
  8122. return toPath_1;
  8123. }
  8124. var toPathExports = requireToPath();
  8125. var toPath = /*@__PURE__*/getDefaultExportFromCjs(toPathExports);
  8126. var define$2 = {
  8127. // access data field
  8128. data: function data(params) {
  8129. var defaults = {
  8130. field: 'data',
  8131. bindingEvent: 'data',
  8132. allowBinding: false,
  8133. allowSetting: false,
  8134. allowGetting: false,
  8135. settingEvent: 'data',
  8136. settingTriggersEvent: false,
  8137. triggerFnName: 'trigger',
  8138. immutableKeys: {},
  8139. // key => true if immutable
  8140. updateStyle: false,
  8141. beforeGet: function beforeGet(self) {},
  8142. beforeSet: function beforeSet(self, obj) {},
  8143. onSet: function onSet(self) {},
  8144. canSet: function canSet(self) {
  8145. return true;
  8146. }
  8147. };
  8148. params = extend({}, defaults, params);
  8149. return function dataImpl(name, value) {
  8150. var p = params;
  8151. var self = this;
  8152. var selfIsArrayLike = self.length !== undefined;
  8153. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  8154. var single = selfIsArrayLike ? self[0] : self;
  8155. // .data('foo', ...)
  8156. if (string(name)) {
  8157. // set or get property
  8158. var isPathLike = name.indexOf('.') !== -1; // there might be a normal field with a dot
  8159. var path = isPathLike && toPath(name);
  8160. // .data('foo')
  8161. if (p.allowGetting && value === undefined) {
  8162. // get
  8163. var ret;
  8164. if (single) {
  8165. p.beforeGet(single);
  8166. // check if it's path and a field with the same name doesn't exist
  8167. if (path && single._private[p.field][name] === undefined) {
  8168. ret = get(single._private[p.field], path);
  8169. } else {
  8170. ret = single._private[p.field][name];
  8171. }
  8172. }
  8173. return ret;
  8174. // .data('foo', 'bar')
  8175. } else if (p.allowSetting && value !== undefined) {
  8176. // set
  8177. var valid = !p.immutableKeys[name];
  8178. if (valid) {
  8179. var change = _defineProperty$1({}, name, value);
  8180. p.beforeSet(self, change);
  8181. for (var i = 0, l = all.length; i < l; i++) {
  8182. var ele = all[i];
  8183. if (p.canSet(ele)) {
  8184. if (path && single._private[p.field][name] === undefined) {
  8185. set(ele._private[p.field], path, value);
  8186. } else {
  8187. ele._private[p.field][name] = value;
  8188. }
  8189. }
  8190. }
  8191. // update mappers if asked
  8192. if (p.updateStyle) {
  8193. self.updateStyle();
  8194. }
  8195. // call onSet callback
  8196. p.onSet(self);
  8197. if (p.settingTriggersEvent) {
  8198. self[p.triggerFnName](p.settingEvent);
  8199. }
  8200. }
  8201. }
  8202. // .data({ 'foo': 'bar' })
  8203. } else if (p.allowSetting && plainObject(name)) {
  8204. // extend
  8205. var obj = name;
  8206. var k, v;
  8207. var keys = Object.keys(obj);
  8208. p.beforeSet(self, obj);
  8209. for (var _i = 0; _i < keys.length; _i++) {
  8210. k = keys[_i];
  8211. v = obj[k];
  8212. var _valid = !p.immutableKeys[k];
  8213. if (_valid) {
  8214. for (var j = 0; j < all.length; j++) {
  8215. var _ele = all[j];
  8216. if (p.canSet(_ele)) {
  8217. _ele._private[p.field][k] = v;
  8218. }
  8219. }
  8220. }
  8221. }
  8222. // update mappers if asked
  8223. if (p.updateStyle) {
  8224. self.updateStyle();
  8225. }
  8226. // call onSet callback
  8227. p.onSet(self);
  8228. if (p.settingTriggersEvent) {
  8229. self[p.triggerFnName](p.settingEvent);
  8230. }
  8231. // .data(function(){ ... })
  8232. } else if (p.allowBinding && fn$6(name)) {
  8233. // bind to event
  8234. var fn = name;
  8235. self.on(p.bindingEvent, fn);
  8236. // .data()
  8237. } else if (p.allowGetting && name === undefined) {
  8238. // get whole object
  8239. var _ret;
  8240. if (single) {
  8241. p.beforeGet(single);
  8242. _ret = single._private[p.field];
  8243. }
  8244. return _ret;
  8245. }
  8246. return self; // maintain chainability
  8247. }; // function
  8248. },
  8249. // data
  8250. // remove data field
  8251. removeData: function removeData(params) {
  8252. var defaults = {
  8253. field: 'data',
  8254. event: 'data',
  8255. triggerFnName: 'trigger',
  8256. triggerEvent: false,
  8257. immutableKeys: {} // key => true if immutable
  8258. };
  8259. params = extend({}, defaults, params);
  8260. return function removeDataImpl(names) {
  8261. var p = params;
  8262. var self = this;
  8263. var selfIsArrayLike = self.length !== undefined;
  8264. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  8265. // .removeData('foo bar')
  8266. if (string(names)) {
  8267. // then get the list of keys, and delete them
  8268. var keys = names.split(/\s+/);
  8269. var l = keys.length;
  8270. for (var i = 0; i < l; i++) {
  8271. // delete each non-empty key
  8272. var key = keys[i];
  8273. if (emptyString(key)) {
  8274. continue;
  8275. }
  8276. var valid = !p.immutableKeys[key]; // not valid if immutable
  8277. if (valid) {
  8278. for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {
  8279. all[i_a]._private[p.field][key] = undefined;
  8280. }
  8281. }
  8282. }
  8283. if (p.triggerEvent) {
  8284. self[p.triggerFnName](p.event);
  8285. }
  8286. // .removeData()
  8287. } else if (names === undefined) {
  8288. // then delete all keys
  8289. for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {
  8290. var _privateFields = all[_i_a]._private[p.field];
  8291. var _keys = Object.keys(_privateFields);
  8292. for (var _i2 = 0; _i2 < _keys.length; _i2++) {
  8293. var _key = _keys[_i2];
  8294. var validKeyToDelete = !p.immutableKeys[_key];
  8295. if (validKeyToDelete) {
  8296. _privateFields[_key] = undefined;
  8297. }
  8298. }
  8299. }
  8300. if (p.triggerEvent) {
  8301. self[p.triggerFnName](p.event);
  8302. }
  8303. }
  8304. return self; // maintain chaining
  8305. }; // function
  8306. } // removeData
  8307. }; // define
  8308. var define$1 = {
  8309. eventAliasesOn: function eventAliasesOn(proto) {
  8310. var p = proto;
  8311. p.addListener = p.listen = p.bind = p.on;
  8312. p.unlisten = p.unbind = p.off = p.removeListener;
  8313. p.trigger = p.emit;
  8314. // this is just a wrapper alias of .on()
  8315. p.pon = p.promiseOn = function (events, selector) {
  8316. var self = this;
  8317. var args = Array.prototype.slice.call(arguments, 0);
  8318. return new Promise$1(function (resolve, reject) {
  8319. var callback = function callback(e) {
  8320. self.off.apply(self, offArgs);
  8321. resolve(e);
  8322. };
  8323. var onArgs = args.concat([callback]);
  8324. var offArgs = onArgs.concat([]);
  8325. self.on.apply(self, onArgs);
  8326. });
  8327. };
  8328. }
  8329. }; // define
  8330. // use this module to cherry pick functions into your prototype
  8331. // (useful for functions shared between the core and collections, for example)
  8332. var define = {};
  8333. [define$3, define$2, define$1].forEach(function (m) {
  8334. extend(define, m);
  8335. });
  8336. var elesfn$i = {
  8337. animate: define.animate(),
  8338. animation: define.animation(),
  8339. animated: define.animated(),
  8340. clearQueue: define.clearQueue(),
  8341. delay: define.delay(),
  8342. delayAnimation: define.delayAnimation(),
  8343. stop: define.stop()
  8344. };
  8345. var elesfn$h = {
  8346. classes: function classes(_classes) {
  8347. var self = this;
  8348. if (_classes === undefined) {
  8349. var ret = [];
  8350. self[0]._private.classes.forEach(function (cls) {
  8351. return ret.push(cls);
  8352. });
  8353. return ret;
  8354. } else if (!array(_classes)) {
  8355. // extract classes from string
  8356. _classes = (_classes || '').match(/\S+/g) || [];
  8357. }
  8358. var changed = [];
  8359. var classesSet = new Set$1(_classes);
  8360. // check and update each ele
  8361. for (var j = 0; j < self.length; j++) {
  8362. var ele = self[j];
  8363. var _p = ele._private;
  8364. var eleClasses = _p.classes;
  8365. var changedEle = false;
  8366. // check if ele has all of the passed classes
  8367. for (var i = 0; i < _classes.length; i++) {
  8368. var cls = _classes[i];
  8369. var eleHasClass = eleClasses.has(cls);
  8370. if (!eleHasClass) {
  8371. changedEle = true;
  8372. break;
  8373. }
  8374. }
  8375. // check if ele has classes outside of those passed
  8376. if (!changedEle) {
  8377. changedEle = eleClasses.size !== _classes.length;
  8378. }
  8379. if (changedEle) {
  8380. _p.classes = classesSet;
  8381. changed.push(ele);
  8382. }
  8383. }
  8384. // trigger update style on those eles that had class changes
  8385. if (changed.length > 0) {
  8386. this.spawn(changed).updateStyle().emit('class');
  8387. }
  8388. return self;
  8389. },
  8390. addClass: function addClass(classes) {
  8391. return this.toggleClass(classes, true);
  8392. },
  8393. hasClass: function hasClass(className) {
  8394. var ele = this[0];
  8395. return ele != null && ele._private.classes.has(className);
  8396. },
  8397. toggleClass: function toggleClass(classes, toggle) {
  8398. if (!array(classes)) {
  8399. // extract classes from string
  8400. classes = classes.match(/\S+/g) || [];
  8401. }
  8402. var self = this;
  8403. var toggleUndefd = toggle === undefined;
  8404. var changed = []; // eles who had classes changed
  8405. for (var i = 0, il = self.length; i < il; i++) {
  8406. var ele = self[i];
  8407. var eleClasses = ele._private.classes;
  8408. var changedEle = false;
  8409. for (var j = 0; j < classes.length; j++) {
  8410. var cls = classes[j];
  8411. var hasClass = eleClasses.has(cls);
  8412. var changedNow = false;
  8413. if (toggle || toggleUndefd && !hasClass) {
  8414. eleClasses.add(cls);
  8415. changedNow = true;
  8416. } else if (!toggle || toggleUndefd && hasClass) {
  8417. eleClasses["delete"](cls);
  8418. changedNow = true;
  8419. }
  8420. if (!changedEle && changedNow) {
  8421. changed.push(ele);
  8422. changedEle = true;
  8423. }
  8424. } // for j classes
  8425. } // for i eles
  8426. // trigger update style on those eles that had class changes
  8427. if (changed.length > 0) {
  8428. this.spawn(changed).updateStyle().emit('class');
  8429. }
  8430. return self;
  8431. },
  8432. removeClass: function removeClass(classes) {
  8433. return this.toggleClass(classes, false);
  8434. },
  8435. flashClass: function flashClass(classes, duration) {
  8436. var self = this;
  8437. if (duration == null) {
  8438. duration = 250;
  8439. } else if (duration === 0) {
  8440. return self; // nothing to do really
  8441. }
  8442. self.addClass(classes);
  8443. setTimeout(function () {
  8444. self.removeClass(classes);
  8445. }, duration);
  8446. return self;
  8447. }
  8448. };
  8449. elesfn$h.className = elesfn$h.classNames = elesfn$h.classes;
  8450. // tokens in the query language
  8451. var tokens = {
  8452. metaChar: '[\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]',
  8453. // chars we need to escape in let names, etc
  8454. comparatorOp: '=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=',
  8455. // binary comparison op (used in data selectors)
  8456. boolOp: '\\?|\\!|\\^',
  8457. // boolean (unary) operators (used in data selectors)
  8458. string: '"(?:\\\\"|[^"])*"' + '|' + "'(?:\\\\'|[^'])*'",
  8459. // string literals (used in data selectors) -- doublequotes | singlequotes
  8460. number: number,
  8461. // number literal (used in data selectors) --- e.g. 0.1234, 1234, 12e123
  8462. meta: 'degree|indegree|outdegree',
  8463. // allowed metadata fields (i.e. allowed functions to use from Collection)
  8464. separator: '\\s*,\\s*',
  8465. // queries are separated by commas, e.g. edge[foo = 'bar'], node.someClass
  8466. descendant: '\\s+',
  8467. child: '\\s+>\\s+',
  8468. subject: '\\$',
  8469. group: 'node|edge|\\*',
  8470. directedEdge: '\\s+->\\s+',
  8471. undirectedEdge: '\\s+<->\\s+'
  8472. };
  8473. tokens.variable = '(?:[\\w-.]|(?:\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods
  8474. tokens.className = '(?:[\\w-]|(?:\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name
  8475. tokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number
  8476. tokens.id = tokens.variable; // an element id (follows variable conventions)
  8477. (function () {
  8478. var ops, op, i;
  8479. // add @ variants to comparatorOp
  8480. ops = tokens.comparatorOp.split('|');
  8481. for (i = 0; i < ops.length; i++) {
  8482. op = ops[i];
  8483. tokens.comparatorOp += '|@' + op;
  8484. }
  8485. // add ! variants to comparatorOp
  8486. ops = tokens.comparatorOp.split('|');
  8487. for (i = 0; i < ops.length; i++) {
  8488. op = ops[i];
  8489. if (op.indexOf('!') >= 0) {
  8490. continue;
  8491. } // skip ops that explicitly contain !
  8492. if (op === '=') {
  8493. continue;
  8494. } // skip = b/c != is explicitly defined
  8495. tokens.comparatorOp += '|\\!' + op;
  8496. }
  8497. })();
  8498. /**
  8499. * Make a new query object
  8500. *
  8501. * @prop type {Type} The type enum (int) of the query
  8502. * @prop checks List of checks to make against an ele to test for a match
  8503. */
  8504. var newQuery = function newQuery() {
  8505. return {
  8506. checks: []
  8507. };
  8508. };
  8509. /**
  8510. * A check type enum-like object. Uses integer values for fast match() lookup.
  8511. * The ordering does not matter as long as the ints are unique.
  8512. */
  8513. var Type = {
  8514. /** E.g. node */
  8515. GROUP: 0,
  8516. /** A collection of elements */
  8517. COLLECTION: 1,
  8518. /** A filter(ele) function */
  8519. FILTER: 2,
  8520. /** E.g. [foo > 1] */
  8521. DATA_COMPARE: 3,
  8522. /** E.g. [foo] */
  8523. DATA_EXIST: 4,
  8524. /** E.g. [?foo] */
  8525. DATA_BOOL: 5,
  8526. /** E.g. [[degree > 2]] */
  8527. META_COMPARE: 6,
  8528. /** E.g. :selected */
  8529. STATE: 7,
  8530. /** E.g. #foo */
  8531. ID: 8,
  8532. /** E.g. .foo */
  8533. CLASS: 9,
  8534. /** E.g. #foo <-> #bar */
  8535. UNDIRECTED_EDGE: 10,
  8536. /** E.g. #foo -> #bar */
  8537. DIRECTED_EDGE: 11,
  8538. /** E.g. $#foo -> #bar */
  8539. NODE_SOURCE: 12,
  8540. /** E.g. #foo -> $#bar */
  8541. NODE_TARGET: 13,
  8542. /** E.g. $#foo <-> #bar */
  8543. NODE_NEIGHBOR: 14,
  8544. /** E.g. #foo > #bar */
  8545. CHILD: 15,
  8546. /** E.g. #foo #bar */
  8547. DESCENDANT: 16,
  8548. /** E.g. $#foo > #bar */
  8549. PARENT: 17,
  8550. /** E.g. $#foo #bar */
  8551. ANCESTOR: 18,
  8552. /** E.g. #foo > $bar > #baz */
  8553. COMPOUND_SPLIT: 19,
  8554. /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */
  8555. TRUE: 20
  8556. };
  8557. var stateSelectors = [{
  8558. selector: ':selected',
  8559. matches: function matches(ele) {
  8560. return ele.selected();
  8561. }
  8562. }, {
  8563. selector: ':unselected',
  8564. matches: function matches(ele) {
  8565. return !ele.selected();
  8566. }
  8567. }, {
  8568. selector: ':selectable',
  8569. matches: function matches(ele) {
  8570. return ele.selectable();
  8571. }
  8572. }, {
  8573. selector: ':unselectable',
  8574. matches: function matches(ele) {
  8575. return !ele.selectable();
  8576. }
  8577. }, {
  8578. selector: ':locked',
  8579. matches: function matches(ele) {
  8580. return ele.locked();
  8581. }
  8582. }, {
  8583. selector: ':unlocked',
  8584. matches: function matches(ele) {
  8585. return !ele.locked();
  8586. }
  8587. }, {
  8588. selector: ':visible',
  8589. matches: function matches(ele) {
  8590. return ele.visible();
  8591. }
  8592. }, {
  8593. selector: ':hidden',
  8594. matches: function matches(ele) {
  8595. return !ele.visible();
  8596. }
  8597. }, {
  8598. selector: ':transparent',
  8599. matches: function matches(ele) {
  8600. return ele.transparent();
  8601. }
  8602. }, {
  8603. selector: ':grabbed',
  8604. matches: function matches(ele) {
  8605. return ele.grabbed();
  8606. }
  8607. }, {
  8608. selector: ':free',
  8609. matches: function matches(ele) {
  8610. return !ele.grabbed();
  8611. }
  8612. }, {
  8613. selector: ':removed',
  8614. matches: function matches(ele) {
  8615. return ele.removed();
  8616. }
  8617. }, {
  8618. selector: ':inside',
  8619. matches: function matches(ele) {
  8620. return !ele.removed();
  8621. }
  8622. }, {
  8623. selector: ':grabbable',
  8624. matches: function matches(ele) {
  8625. return ele.grabbable();
  8626. }
  8627. }, {
  8628. selector: ':ungrabbable',
  8629. matches: function matches(ele) {
  8630. return !ele.grabbable();
  8631. }
  8632. }, {
  8633. selector: ':animated',
  8634. matches: function matches(ele) {
  8635. return ele.animated();
  8636. }
  8637. }, {
  8638. selector: ':unanimated',
  8639. matches: function matches(ele) {
  8640. return !ele.animated();
  8641. }
  8642. }, {
  8643. selector: ':parent',
  8644. matches: function matches(ele) {
  8645. return ele.isParent();
  8646. }
  8647. }, {
  8648. selector: ':childless',
  8649. matches: function matches(ele) {
  8650. return ele.isChildless();
  8651. }
  8652. }, {
  8653. selector: ':child',
  8654. matches: function matches(ele) {
  8655. return ele.isChild();
  8656. }
  8657. }, {
  8658. selector: ':orphan',
  8659. matches: function matches(ele) {
  8660. return ele.isOrphan();
  8661. }
  8662. }, {
  8663. selector: ':nonorphan',
  8664. matches: function matches(ele) {
  8665. return ele.isChild();
  8666. }
  8667. }, {
  8668. selector: ':compound',
  8669. matches: function matches(ele) {
  8670. if (ele.isNode()) {
  8671. return ele.isParent();
  8672. } else {
  8673. return ele.source().isParent() || ele.target().isParent();
  8674. }
  8675. }
  8676. }, {
  8677. selector: ':loop',
  8678. matches: function matches(ele) {
  8679. return ele.isLoop();
  8680. }
  8681. }, {
  8682. selector: ':simple',
  8683. matches: function matches(ele) {
  8684. return ele.isSimple();
  8685. }
  8686. }, {
  8687. selector: ':active',
  8688. matches: function matches(ele) {
  8689. return ele.active();
  8690. }
  8691. }, {
  8692. selector: ':inactive',
  8693. matches: function matches(ele) {
  8694. return !ele.active();
  8695. }
  8696. }, {
  8697. selector: ':backgrounding',
  8698. matches: function matches(ele) {
  8699. return ele.backgrounding();
  8700. }
  8701. }, {
  8702. selector: ':nonbackgrounding',
  8703. matches: function matches(ele) {
  8704. return !ele.backgrounding();
  8705. }
  8706. }].sort(function (a, b) {
  8707. // n.b. selectors that are starting substrings of others must have the longer ones first
  8708. return descending(a.selector, b.selector);
  8709. });
  8710. var lookup = function () {
  8711. var selToFn = {};
  8712. var s;
  8713. for (var i = 0; i < stateSelectors.length; i++) {
  8714. s = stateSelectors[i];
  8715. selToFn[s.selector] = s.matches;
  8716. }
  8717. return selToFn;
  8718. }();
  8719. var stateSelectorMatches = function stateSelectorMatches(sel, ele) {
  8720. return lookup[sel](ele);
  8721. };
  8722. var stateSelectorRegex = '(' + stateSelectors.map(function (s) {
  8723. return s.selector;
  8724. }).join('|') + ')';
  8725. // when a token like a variable has escaped meta characters, we need to clean the backslashes out
  8726. // so that values get compared properly in Selector.filter()
  8727. var cleanMetaChars = function cleanMetaChars(str) {
  8728. return str.replace(new RegExp('\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {
  8729. return $1;
  8730. });
  8731. };
  8732. var replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {
  8733. selector[selector.length - 1] = replacementQuery;
  8734. };
  8735. // NOTE: add new expression syntax here to have it recognised by the parser;
  8736. // - a query contains all adjacent (i.e. no separator in between) expressions;
  8737. // - the current query is stored in selector[i]
  8738. // - you need to check the query objects in match() for it actually filter properly, but that's pretty straight forward
  8739. var exprs = [{
  8740. name: 'group',
  8741. // just used for identifying when debugging
  8742. query: true,
  8743. regex: '(' + tokens.group + ')',
  8744. populate: function populate(selector, query, _ref) {
  8745. var _ref2 = _slicedToArray(_ref, 1),
  8746. group = _ref2[0];
  8747. query.checks.push({
  8748. type: Type.GROUP,
  8749. value: group === '*' ? group : group + 's'
  8750. });
  8751. }
  8752. }, {
  8753. name: 'state',
  8754. query: true,
  8755. regex: stateSelectorRegex,
  8756. populate: function populate(selector, query, _ref3) {
  8757. var _ref4 = _slicedToArray(_ref3, 1),
  8758. state = _ref4[0];
  8759. query.checks.push({
  8760. type: Type.STATE,
  8761. value: state
  8762. });
  8763. }
  8764. }, {
  8765. name: 'id',
  8766. query: true,
  8767. regex: '\\#(' + tokens.id + ')',
  8768. populate: function populate(selector, query, _ref5) {
  8769. var _ref6 = _slicedToArray(_ref5, 1),
  8770. id = _ref6[0];
  8771. query.checks.push({
  8772. type: Type.ID,
  8773. value: cleanMetaChars(id)
  8774. });
  8775. }
  8776. }, {
  8777. name: 'className',
  8778. query: true,
  8779. regex: '\\.(' + tokens.className + ')',
  8780. populate: function populate(selector, query, _ref7) {
  8781. var _ref8 = _slicedToArray(_ref7, 1),
  8782. className = _ref8[0];
  8783. query.checks.push({
  8784. type: Type.CLASS,
  8785. value: cleanMetaChars(className)
  8786. });
  8787. }
  8788. }, {
  8789. name: 'dataExists',
  8790. query: true,
  8791. regex: '\\[\\s*(' + tokens.variable + ')\\s*\\]',
  8792. populate: function populate(selector, query, _ref9) {
  8793. var _ref10 = _slicedToArray(_ref9, 1),
  8794. variable = _ref10[0];
  8795. query.checks.push({
  8796. type: Type.DATA_EXIST,
  8797. field: cleanMetaChars(variable)
  8798. });
  8799. }
  8800. }, {
  8801. name: 'dataCompare',
  8802. query: true,
  8803. regex: '\\[\\s*(' + tokens.variable + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.value + ')\\s*\\]',
  8804. populate: function populate(selector, query, _ref11) {
  8805. var _ref12 = _slicedToArray(_ref11, 3),
  8806. variable = _ref12[0],
  8807. comparatorOp = _ref12[1],
  8808. value = _ref12[2];
  8809. var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;
  8810. if (valueIsString) {
  8811. value = value.substring(1, value.length - 1);
  8812. } else {
  8813. value = parseFloat(value);
  8814. }
  8815. query.checks.push({
  8816. type: Type.DATA_COMPARE,
  8817. field: cleanMetaChars(variable),
  8818. operator: comparatorOp,
  8819. value: value
  8820. });
  8821. }
  8822. }, {
  8823. name: 'dataBool',
  8824. query: true,
  8825. regex: '\\[\\s*(' + tokens.boolOp + ')\\s*(' + tokens.variable + ')\\s*\\]',
  8826. populate: function populate(selector, query, _ref13) {
  8827. var _ref14 = _slicedToArray(_ref13, 2),
  8828. boolOp = _ref14[0],
  8829. variable = _ref14[1];
  8830. query.checks.push({
  8831. type: Type.DATA_BOOL,
  8832. field: cleanMetaChars(variable),
  8833. operator: boolOp
  8834. });
  8835. }
  8836. }, {
  8837. name: 'metaCompare',
  8838. query: true,
  8839. regex: '\\[\\[\\s*(' + tokens.meta + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.number + ')\\s*\\]\\]',
  8840. populate: function populate(selector, query, _ref15) {
  8841. var _ref16 = _slicedToArray(_ref15, 3),
  8842. meta = _ref16[0],
  8843. comparatorOp = _ref16[1],
  8844. number = _ref16[2];
  8845. query.checks.push({
  8846. type: Type.META_COMPARE,
  8847. field: cleanMetaChars(meta),
  8848. operator: comparatorOp,
  8849. value: parseFloat(number)
  8850. });
  8851. }
  8852. }, {
  8853. name: 'nextQuery',
  8854. separator: true,
  8855. regex: tokens.separator,
  8856. populate: function populate(selector, query) {
  8857. var currentSubject = selector.currentSubject;
  8858. var edgeCount = selector.edgeCount;
  8859. var compoundCount = selector.compoundCount;
  8860. var lastQ = selector[selector.length - 1];
  8861. if (currentSubject != null) {
  8862. lastQ.subject = currentSubject;
  8863. selector.currentSubject = null;
  8864. }
  8865. lastQ.edgeCount = edgeCount;
  8866. lastQ.compoundCount = compoundCount;
  8867. selector.edgeCount = 0;
  8868. selector.compoundCount = 0;
  8869. // go on to next query
  8870. var nextQuery = selector[selector.length++] = newQuery();
  8871. return nextQuery; // this is the new query to be filled by the following exprs
  8872. }
  8873. }, {
  8874. name: 'directedEdge',
  8875. separator: true,
  8876. regex: tokens.directedEdge,
  8877. populate: function populate(selector, query) {
  8878. if (selector.currentSubject == null) {
  8879. // undirected edge
  8880. var edgeQuery = newQuery();
  8881. var source = query;
  8882. var target = newQuery();
  8883. edgeQuery.checks.push({
  8884. type: Type.DIRECTED_EDGE,
  8885. source: source,
  8886. target: target
  8887. });
  8888. // the query in the selector should be the edge rather than the source
  8889. replaceLastQuery(selector, query, edgeQuery);
  8890. selector.edgeCount++;
  8891. // we're now populating the target query with expressions that follow
  8892. return target;
  8893. } else {
  8894. // source/target
  8895. var srcTgtQ = newQuery();
  8896. var _source = query;
  8897. var _target = newQuery();
  8898. srcTgtQ.checks.push({
  8899. type: Type.NODE_SOURCE,
  8900. source: _source,
  8901. target: _target
  8902. });
  8903. // the query in the selector should be the neighbourhood rather than the node
  8904. replaceLastQuery(selector, query, srcTgtQ);
  8905. selector.edgeCount++;
  8906. return _target; // now populating the target with the following expressions
  8907. }
  8908. }
  8909. }, {
  8910. name: 'undirectedEdge',
  8911. separator: true,
  8912. regex: tokens.undirectedEdge,
  8913. populate: function populate(selector, query) {
  8914. if (selector.currentSubject == null) {
  8915. // undirected edge
  8916. var edgeQuery = newQuery();
  8917. var source = query;
  8918. var target = newQuery();
  8919. edgeQuery.checks.push({
  8920. type: Type.UNDIRECTED_EDGE,
  8921. nodes: [source, target]
  8922. });
  8923. // the query in the selector should be the edge rather than the source
  8924. replaceLastQuery(selector, query, edgeQuery);
  8925. selector.edgeCount++;
  8926. // we're now populating the target query with expressions that follow
  8927. return target;
  8928. } else {
  8929. // neighbourhood
  8930. var nhoodQ = newQuery();
  8931. var node = query;
  8932. var neighbor = newQuery();
  8933. nhoodQ.checks.push({
  8934. type: Type.NODE_NEIGHBOR,
  8935. node: node,
  8936. neighbor: neighbor
  8937. });
  8938. // the query in the selector should be the neighbourhood rather than the node
  8939. replaceLastQuery(selector, query, nhoodQ);
  8940. return neighbor; // now populating the neighbor with following expressions
  8941. }
  8942. }
  8943. }, {
  8944. name: 'child',
  8945. separator: true,
  8946. regex: tokens.child,
  8947. populate: function populate(selector, query) {
  8948. if (selector.currentSubject == null) {
  8949. // default: child query
  8950. var parentChildQuery = newQuery();
  8951. var child = newQuery();
  8952. var parent = selector[selector.length - 1];
  8953. parentChildQuery.checks.push({
  8954. type: Type.CHILD,
  8955. parent: parent,
  8956. child: child
  8957. });
  8958. // the query in the selector should be the '>' itself
  8959. replaceLastQuery(selector, query, parentChildQuery);
  8960. selector.compoundCount++;
  8961. // we're now populating the child query with expressions that follow
  8962. return child;
  8963. } else if (selector.currentSubject === query) {
  8964. // compound split query
  8965. var compound = newQuery();
  8966. var left = selector[selector.length - 1];
  8967. var right = newQuery();
  8968. var subject = newQuery();
  8969. var _child = newQuery();
  8970. var _parent = newQuery();
  8971. // set up the root compound q
  8972. compound.checks.push({
  8973. type: Type.COMPOUND_SPLIT,
  8974. left: left,
  8975. right: right,
  8976. subject: subject
  8977. });
  8978. // populate the subject and replace the q at the old spot (within left) with TRUE
  8979. subject.checks = query.checks; // take the checks from the left
  8980. query.checks = [{
  8981. type: Type.TRUE
  8982. }]; // checks under left refs the subject implicitly
  8983. // set up the right q
  8984. _parent.checks.push({
  8985. type: Type.TRUE
  8986. }); // parent implicitly refs the subject
  8987. right.checks.push({
  8988. type: Type.PARENT,
  8989. // type is swapped on right side queries
  8990. parent: _parent,
  8991. child: _child // empty for now
  8992. });
  8993. replaceLastQuery(selector, left, compound);
  8994. // update the ref since we moved things around for `query`
  8995. selector.currentSubject = subject;
  8996. selector.compoundCount++;
  8997. return _child; // now populating the right side's child
  8998. } else {
  8999. // parent query
  9000. // info for parent query
  9001. var _parent2 = newQuery();
  9002. var _child2 = newQuery();
  9003. var pcQChecks = [{
  9004. type: Type.PARENT,
  9005. parent: _parent2,
  9006. child: _child2
  9007. }];
  9008. // the parent-child query takes the place of the query previously being populated
  9009. _parent2.checks = query.checks; // the previous query contains the checks for the parent
  9010. query.checks = pcQChecks; // pc query takes over
  9011. selector.compoundCount++;
  9012. return _child2; // we're now populating the child
  9013. }
  9014. }
  9015. }, {
  9016. name: 'descendant',
  9017. separator: true,
  9018. regex: tokens.descendant,
  9019. populate: function populate(selector, query) {
  9020. if (selector.currentSubject == null) {
  9021. // default: descendant query
  9022. var ancChQuery = newQuery();
  9023. var descendant = newQuery();
  9024. var ancestor = selector[selector.length - 1];
  9025. ancChQuery.checks.push({
  9026. type: Type.DESCENDANT,
  9027. ancestor: ancestor,
  9028. descendant: descendant
  9029. });
  9030. // the query in the selector should be the '>' itself
  9031. replaceLastQuery(selector, query, ancChQuery);
  9032. selector.compoundCount++;
  9033. // we're now populating the descendant query with expressions that follow
  9034. return descendant;
  9035. } else if (selector.currentSubject === query) {
  9036. // compound split query
  9037. var compound = newQuery();
  9038. var left = selector[selector.length - 1];
  9039. var right = newQuery();
  9040. var subject = newQuery();
  9041. var _descendant = newQuery();
  9042. var _ancestor = newQuery();
  9043. // set up the root compound q
  9044. compound.checks.push({
  9045. type: Type.COMPOUND_SPLIT,
  9046. left: left,
  9047. right: right,
  9048. subject: subject
  9049. });
  9050. // populate the subject and replace the q at the old spot (within left) with TRUE
  9051. subject.checks = query.checks; // take the checks from the left
  9052. query.checks = [{
  9053. type: Type.TRUE
  9054. }]; // checks under left refs the subject implicitly
  9055. // set up the right q
  9056. _ancestor.checks.push({
  9057. type: Type.TRUE
  9058. }); // ancestor implicitly refs the subject
  9059. right.checks.push({
  9060. type: Type.ANCESTOR,
  9061. // type is swapped on right side queries
  9062. ancestor: _ancestor,
  9063. descendant: _descendant // empty for now
  9064. });
  9065. replaceLastQuery(selector, left, compound);
  9066. // update the ref since we moved things around for `query`
  9067. selector.currentSubject = subject;
  9068. selector.compoundCount++;
  9069. return _descendant; // now populating the right side's descendant
  9070. } else {
  9071. // ancestor query
  9072. // info for parent query
  9073. var _ancestor2 = newQuery();
  9074. var _descendant2 = newQuery();
  9075. var adQChecks = [{
  9076. type: Type.ANCESTOR,
  9077. ancestor: _ancestor2,
  9078. descendant: _descendant2
  9079. }];
  9080. // the parent-child query takes the place of the query previously being populated
  9081. _ancestor2.checks = query.checks; // the previous query contains the checks for the parent
  9082. query.checks = adQChecks; // pc query takes over
  9083. selector.compoundCount++;
  9084. return _descendant2; // we're now populating the child
  9085. }
  9086. }
  9087. }, {
  9088. name: 'subject',
  9089. modifier: true,
  9090. regex: tokens.subject,
  9091. populate: function populate(selector, query) {
  9092. if (selector.currentSubject != null && selector.currentSubject !== query) {
  9093. warn('Redefinition of subject in selector `' + selector.toString() + '`');
  9094. return false;
  9095. }
  9096. selector.currentSubject = query;
  9097. var topQ = selector[selector.length - 1];
  9098. var topChk = topQ.checks[0];
  9099. var topType = topChk == null ? null : topChk.type;
  9100. if (topType === Type.DIRECTED_EDGE) {
  9101. // directed edge with subject on the target
  9102. // change to target node check
  9103. topChk.type = Type.NODE_TARGET;
  9104. } else if (topType === Type.UNDIRECTED_EDGE) {
  9105. // undirected edge with subject on the second node
  9106. // change to neighbor check
  9107. topChk.type = Type.NODE_NEIGHBOR;
  9108. topChk.node = topChk.nodes[1]; // second node is subject
  9109. topChk.neighbor = topChk.nodes[0];
  9110. // clean up unused fields for new type
  9111. topChk.nodes = null;
  9112. }
  9113. }
  9114. }];
  9115. exprs.forEach(function (e) {
  9116. return e.regexObj = new RegExp('^' + e.regex);
  9117. });
  9118. /**
  9119. * Of all the expressions, find the first match in the remaining text.
  9120. * @param {string} remaining The remaining text to parse
  9121. * @returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`
  9122. */
  9123. var consumeExpr = function consumeExpr(remaining) {
  9124. var expr;
  9125. var match;
  9126. var name;
  9127. for (var j = 0; j < exprs.length; j++) {
  9128. var e = exprs[j];
  9129. var n = e.name;
  9130. var m = remaining.match(e.regexObj);
  9131. if (m != null) {
  9132. match = m;
  9133. expr = e;
  9134. name = n;
  9135. var consumed = m[0];
  9136. remaining = remaining.substring(consumed.length);
  9137. break; // we've consumed one expr, so we can return now
  9138. }
  9139. }
  9140. return {
  9141. expr: expr,
  9142. match: match,
  9143. name: name,
  9144. remaining: remaining
  9145. };
  9146. };
  9147. /**
  9148. * Consume all the leading whitespace
  9149. * @param {string} remaining The text to consume
  9150. * @returns The text with the leading whitespace removed
  9151. */
  9152. var consumeWhitespace = function consumeWhitespace(remaining) {
  9153. var match = remaining.match(/^\s+/);
  9154. if (match) {
  9155. var consumed = match[0];
  9156. remaining = remaining.substring(consumed.length);
  9157. }
  9158. return remaining;
  9159. };
  9160. /**
  9161. * Parse the string and store the parsed representation in the Selector.
  9162. * @param {string} selector The selector string
  9163. * @returns `true` if the selector was successfully parsed, `false` otherwise
  9164. */
  9165. var parse = function parse(selector) {
  9166. var self = this;
  9167. var remaining = self.inputText = selector;
  9168. var currentQuery = self[0] = newQuery();
  9169. self.length = 1;
  9170. remaining = consumeWhitespace(remaining); // get rid of leading whitespace
  9171. for (;;) {
  9172. var exprInfo = consumeExpr(remaining);
  9173. if (exprInfo.expr == null) {
  9174. warn('The selector `' + selector + '`is invalid');
  9175. return false;
  9176. } else {
  9177. var args = exprInfo.match.slice(1);
  9178. // let the token populate the selector object in currentQuery
  9179. var ret = exprInfo.expr.populate(self, currentQuery, args);
  9180. if (ret === false) {
  9181. return false; // exit if population failed
  9182. } else if (ret != null) {
  9183. currentQuery = ret; // change the current query to be filled if the expr specifies
  9184. }
  9185. }
  9186. remaining = exprInfo.remaining;
  9187. // we're done when there's nothing left to parse
  9188. if (remaining.match(/^\s*$/)) {
  9189. break;
  9190. }
  9191. }
  9192. var lastQ = self[self.length - 1];
  9193. if (self.currentSubject != null) {
  9194. lastQ.subject = self.currentSubject;
  9195. }
  9196. lastQ.edgeCount = self.edgeCount;
  9197. lastQ.compoundCount = self.compoundCount;
  9198. for (var i = 0; i < self.length; i++) {
  9199. var q = self[i];
  9200. // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations
  9201. if (q.compoundCount > 0 && q.edgeCount > 0) {
  9202. warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');
  9203. return false;
  9204. }
  9205. if (q.edgeCount > 1) {
  9206. warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');
  9207. return false;
  9208. } else if (q.edgeCount === 1) {
  9209. 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.');
  9210. }
  9211. }
  9212. return true; // success
  9213. };
  9214. /**
  9215. * Get the selector represented as a string. This value uses default formatting,
  9216. * so things like spacing may differ from the input text passed to the constructor.
  9217. * @returns {string} The selector string
  9218. */
  9219. var toString = function toString() {
  9220. if (this.toStringCache != null) {
  9221. return this.toStringCache;
  9222. }
  9223. var clean = function clean(obj) {
  9224. if (obj == null) {
  9225. return '';
  9226. } else {
  9227. return obj;
  9228. }
  9229. };
  9230. var cleanVal = function cleanVal(val) {
  9231. if (string(val)) {
  9232. return '"' + val + '"';
  9233. } else {
  9234. return clean(val);
  9235. }
  9236. };
  9237. var space = function space(val) {
  9238. return ' ' + val + ' ';
  9239. };
  9240. var checkToString = function checkToString(check, subject) {
  9241. var type = check.type,
  9242. value = check.value;
  9243. switch (type) {
  9244. case Type.GROUP:
  9245. {
  9246. var group = clean(value);
  9247. return group.substring(0, group.length - 1);
  9248. }
  9249. case Type.DATA_COMPARE:
  9250. {
  9251. var field = check.field,
  9252. operator = check.operator;
  9253. return '[' + field + space(clean(operator)) + cleanVal(value) + ']';
  9254. }
  9255. case Type.DATA_BOOL:
  9256. {
  9257. var _operator = check.operator,
  9258. _field = check.field;
  9259. return '[' + clean(_operator) + _field + ']';
  9260. }
  9261. case Type.DATA_EXIST:
  9262. {
  9263. var _field2 = check.field;
  9264. return '[' + _field2 + ']';
  9265. }
  9266. case Type.META_COMPARE:
  9267. {
  9268. var _operator2 = check.operator,
  9269. _field3 = check.field;
  9270. return '[[' + _field3 + space(clean(_operator2)) + cleanVal(value) + ']]';
  9271. }
  9272. case Type.STATE:
  9273. {
  9274. return value;
  9275. }
  9276. case Type.ID:
  9277. {
  9278. return '#' + value;
  9279. }
  9280. case Type.CLASS:
  9281. {
  9282. return '.' + value;
  9283. }
  9284. case Type.PARENT:
  9285. case Type.CHILD:
  9286. {
  9287. return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);
  9288. }
  9289. case Type.ANCESTOR:
  9290. case Type.DESCENDANT:
  9291. {
  9292. return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);
  9293. }
  9294. case Type.COMPOUND_SPLIT:
  9295. {
  9296. var lhs = queryToString(check.left, subject);
  9297. var sub = queryToString(check.subject, subject);
  9298. var rhs = queryToString(check.right, subject);
  9299. return lhs + (lhs.length > 0 ? ' ' : '') + sub + rhs;
  9300. }
  9301. case Type.TRUE:
  9302. {
  9303. return '';
  9304. }
  9305. }
  9306. };
  9307. var queryToString = function queryToString(query, subject) {
  9308. return query.checks.reduce(function (str, chk, i) {
  9309. return str + (subject === query && i === 0 ? '$' : '') + checkToString(chk, subject);
  9310. }, '');
  9311. };
  9312. var str = '';
  9313. for (var i = 0; i < this.length; i++) {
  9314. var query = this[i];
  9315. str += queryToString(query, query.subject);
  9316. if (this.length > 1 && i < this.length - 1) {
  9317. str += ', ';
  9318. }
  9319. }
  9320. this.toStringCache = str;
  9321. return str;
  9322. };
  9323. var parse$1 = {
  9324. parse: parse,
  9325. toString: toString
  9326. };
  9327. var valCmp = function valCmp(fieldVal, operator, value) {
  9328. var matches;
  9329. var isFieldStr = string(fieldVal);
  9330. var isFieldNum = number$1(fieldVal);
  9331. var isValStr = string(value);
  9332. var fieldStr, valStr;
  9333. var caseInsensitive = false;
  9334. var notExpr = false;
  9335. var isIneqCmp = false;
  9336. if (operator.indexOf('!') >= 0) {
  9337. operator = operator.replace('!', '');
  9338. notExpr = true;
  9339. }
  9340. if (operator.indexOf('@') >= 0) {
  9341. operator = operator.replace('@', '');
  9342. caseInsensitive = true;
  9343. }
  9344. if (isFieldStr || isValStr || caseInsensitive) {
  9345. fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;
  9346. valStr = '' + value;
  9347. }
  9348. // if we're doing a case insensitive comparison, then we're using a STRING comparison
  9349. // even if we're comparing numbers
  9350. if (caseInsensitive) {
  9351. fieldVal = fieldStr = fieldStr.toLowerCase();
  9352. value = valStr = valStr.toLowerCase();
  9353. }
  9354. switch (operator) {
  9355. case '*=':
  9356. matches = fieldStr.indexOf(valStr) >= 0;
  9357. break;
  9358. case '$=':
  9359. matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;
  9360. break;
  9361. case '^=':
  9362. matches = fieldStr.indexOf(valStr) === 0;
  9363. break;
  9364. case '=':
  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. case '<=':
  9380. isIneqCmp = true;
  9381. matches = fieldVal <= value;
  9382. break;
  9383. default:
  9384. matches = false;
  9385. break;
  9386. }
  9387. // apply the not op, but null vals for inequalities should always stay non-matching
  9388. if (notExpr && (fieldVal != null || !isIneqCmp)) {
  9389. matches = !matches;
  9390. }
  9391. return matches;
  9392. };
  9393. var boolCmp = function boolCmp(fieldVal, operator) {
  9394. switch (operator) {
  9395. case '?':
  9396. return fieldVal ? true : false;
  9397. case '!':
  9398. return fieldVal ? false : true;
  9399. case '^':
  9400. return fieldVal === undefined;
  9401. }
  9402. };
  9403. var existCmp = function existCmp(fieldVal) {
  9404. return fieldVal !== undefined;
  9405. };
  9406. var data$1 = function data(ele, field) {
  9407. return ele.data(field);
  9408. };
  9409. var meta = function meta(ele, field) {
  9410. return ele[field]();
  9411. };
  9412. /** A lookup of `match(check, ele)` functions by `Type` int */
  9413. var match = [];
  9414. /**
  9415. * Returns whether the query matches for the element
  9416. * @param query The `{ type, value, ... }` query object
  9417. * @param ele The element to compare against
  9418. */
  9419. var matches$1 = function matches(query, ele) {
  9420. return query.checks.every(function (chk) {
  9421. return match[chk.type](chk, ele);
  9422. });
  9423. };
  9424. match[Type.GROUP] = function (check, ele) {
  9425. var group = check.value;
  9426. return group === '*' || group === ele.group();
  9427. };
  9428. match[Type.STATE] = function (check, ele) {
  9429. var stateSelector = check.value;
  9430. return stateSelectorMatches(stateSelector, ele);
  9431. };
  9432. match[Type.ID] = function (check, ele) {
  9433. var id = check.value;
  9434. return ele.id() === id;
  9435. };
  9436. match[Type.CLASS] = function (check, ele) {
  9437. var cls = check.value;
  9438. return ele.hasClass(cls);
  9439. };
  9440. match[Type.META_COMPARE] = function (check, ele) {
  9441. var field = check.field,
  9442. operator = check.operator,
  9443. value = check.value;
  9444. return valCmp(meta(ele, field), operator, value);
  9445. };
  9446. match[Type.DATA_COMPARE] = function (check, ele) {
  9447. var field = check.field,
  9448. operator = check.operator,
  9449. value = check.value;
  9450. return valCmp(data$1(ele, field), operator, value);
  9451. };
  9452. match[Type.DATA_BOOL] = function (check, ele) {
  9453. var field = check.field,
  9454. operator = check.operator;
  9455. return boolCmp(data$1(ele, field), operator);
  9456. };
  9457. match[Type.DATA_EXIST] = function (check, ele) {
  9458. var field = check.field;
  9459. check.operator;
  9460. return existCmp(data$1(ele, field));
  9461. };
  9462. match[Type.UNDIRECTED_EDGE] = function (check, ele) {
  9463. var qA = check.nodes[0];
  9464. var qB = check.nodes[1];
  9465. var src = ele.source();
  9466. var tgt = ele.target();
  9467. return matches$1(qA, src) && matches$1(qB, tgt) || matches$1(qB, src) && matches$1(qA, tgt);
  9468. };
  9469. match[Type.NODE_NEIGHBOR] = function (check, ele) {
  9470. return matches$1(check.node, ele) && ele.neighborhood().some(function (n) {
  9471. return n.isNode() && matches$1(check.neighbor, n);
  9472. });
  9473. };
  9474. match[Type.DIRECTED_EDGE] = function (check, ele) {
  9475. return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());
  9476. };
  9477. match[Type.NODE_SOURCE] = function (check, ele) {
  9478. return matches$1(check.source, ele) && ele.outgoers().some(function (n) {
  9479. return n.isNode() && matches$1(check.target, n);
  9480. });
  9481. };
  9482. match[Type.NODE_TARGET] = function (check, ele) {
  9483. return matches$1(check.target, ele) && ele.incomers().some(function (n) {
  9484. return n.isNode() && matches$1(check.source, n);
  9485. });
  9486. };
  9487. match[Type.CHILD] = function (check, ele) {
  9488. return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());
  9489. };
  9490. match[Type.PARENT] = function (check, ele) {
  9491. return matches$1(check.parent, ele) && ele.children().some(function (c) {
  9492. return matches$1(check.child, c);
  9493. });
  9494. };
  9495. match[Type.DESCENDANT] = function (check, ele) {
  9496. return matches$1(check.descendant, ele) && ele.ancestors().some(function (a) {
  9497. return matches$1(check.ancestor, a);
  9498. });
  9499. };
  9500. match[Type.ANCESTOR] = function (check, ele) {
  9501. return matches$1(check.ancestor, ele) && ele.descendants().some(function (d) {
  9502. return matches$1(check.descendant, d);
  9503. });
  9504. };
  9505. match[Type.COMPOUND_SPLIT] = function (check, ele) {
  9506. return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);
  9507. };
  9508. match[Type.TRUE] = function () {
  9509. return true;
  9510. };
  9511. match[Type.COLLECTION] = function (check, ele) {
  9512. var collection = check.value;
  9513. return collection.has(ele);
  9514. };
  9515. match[Type.FILTER] = function (check, ele) {
  9516. var filter = check.value;
  9517. return filter(ele);
  9518. };
  9519. // filter an existing collection
  9520. var filter = function filter(collection) {
  9521. var self = this;
  9522. // for 1 id #foo queries, just get the element
  9523. if (self.length === 1 && self[0].checks.length === 1 && self[0].checks[0].type === Type.ID) {
  9524. return collection.getElementById(self[0].checks[0].value).collection();
  9525. }
  9526. var selectorFunction = function selectorFunction(element) {
  9527. for (var j = 0; j < self.length; j++) {
  9528. var query = self[j];
  9529. if (matches$1(query, element)) {
  9530. return true;
  9531. }
  9532. }
  9533. return false;
  9534. };
  9535. if (self.text() == null) {
  9536. selectorFunction = function selectorFunction() {
  9537. return true;
  9538. };
  9539. }
  9540. return collection.filter(selectorFunction);
  9541. }; // filter
  9542. // does selector match a single element?
  9543. var matches = function matches(ele) {
  9544. var self = this;
  9545. for (var j = 0; j < self.length; j++) {
  9546. var query = self[j];
  9547. if (matches$1(query, ele)) {
  9548. return true;
  9549. }
  9550. }
  9551. return false;
  9552. }; // matches
  9553. var matching = {
  9554. matches: matches,
  9555. filter: filter
  9556. };
  9557. var Selector = function Selector(selector) {
  9558. this.inputText = selector;
  9559. this.currentSubject = null;
  9560. this.compoundCount = 0;
  9561. this.edgeCount = 0;
  9562. this.length = 0;
  9563. if (selector == null || string(selector) && selector.match(/^\s*$/)) ; else if (elementOrCollection(selector)) {
  9564. this.addQuery({
  9565. checks: [{
  9566. type: Type.COLLECTION,
  9567. value: selector.collection()
  9568. }]
  9569. });
  9570. } else if (fn$6(selector)) {
  9571. this.addQuery({
  9572. checks: [{
  9573. type: Type.FILTER,
  9574. value: selector
  9575. }]
  9576. });
  9577. } else if (string(selector)) {
  9578. if (!this.parse(selector)) {
  9579. this.invalid = true;
  9580. }
  9581. } else {
  9582. error('A selector must be created from a string; found ');
  9583. }
  9584. };
  9585. var selfn = Selector.prototype;
  9586. [parse$1, matching].forEach(function (p) {
  9587. return extend(selfn, p);
  9588. });
  9589. selfn.text = function () {
  9590. return this.inputText;
  9591. };
  9592. selfn.size = function () {
  9593. return this.length;
  9594. };
  9595. selfn.eq = function (i) {
  9596. return this[i];
  9597. };
  9598. selfn.sameText = function (otherSel) {
  9599. return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();
  9600. };
  9601. selfn.addQuery = function (q) {
  9602. this[this.length++] = q;
  9603. };
  9604. selfn.selector = selfn.toString;
  9605. var elesfn$g = {
  9606. allAre: function allAre(selector) {
  9607. var selObj = new Selector(selector);
  9608. return this.every(function (ele) {
  9609. return selObj.matches(ele);
  9610. });
  9611. },
  9612. is: function is(selector) {
  9613. var selObj = new Selector(selector);
  9614. return this.some(function (ele) {
  9615. return selObj.matches(ele);
  9616. });
  9617. },
  9618. some: function some(fn, thisArg) {
  9619. for (var i = 0; i < this.length; i++) {
  9620. var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
  9621. if (ret) {
  9622. return true;
  9623. }
  9624. }
  9625. return false;
  9626. },
  9627. every: function every(fn, thisArg) {
  9628. for (var i = 0; i < this.length; i++) {
  9629. var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
  9630. if (!ret) {
  9631. return false;
  9632. }
  9633. }
  9634. return true;
  9635. },
  9636. same: function same(collection) {
  9637. // cheap collection ref check
  9638. if (this === collection) {
  9639. return true;
  9640. }
  9641. collection = this.cy().collection(collection);
  9642. var thisLength = this.length;
  9643. var collectionLength = collection.length;
  9644. // cheap length check
  9645. if (thisLength !== collectionLength) {
  9646. return false;
  9647. }
  9648. // cheap element ref check
  9649. if (thisLength === 1) {
  9650. return this[0] === collection[0];
  9651. }
  9652. return this.every(function (ele) {
  9653. return collection.hasElementWithId(ele.id());
  9654. });
  9655. },
  9656. anySame: function anySame(collection) {
  9657. collection = this.cy().collection(collection);
  9658. return this.some(function (ele) {
  9659. return collection.hasElementWithId(ele.id());
  9660. });
  9661. },
  9662. allAreNeighbors: function allAreNeighbors(collection) {
  9663. collection = this.cy().collection(collection);
  9664. var nhood = this.neighborhood();
  9665. return collection.every(function (ele) {
  9666. return nhood.hasElementWithId(ele.id());
  9667. });
  9668. },
  9669. contains: function contains(collection) {
  9670. collection = this.cy().collection(collection);
  9671. var self = this;
  9672. return collection.every(function (ele) {
  9673. return self.hasElementWithId(ele.id());
  9674. });
  9675. }
  9676. };
  9677. elesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;
  9678. elesfn$g.has = elesfn$g.contains;
  9679. elesfn$g.equal = elesfn$g.equals = elesfn$g.same;
  9680. var cache = function cache(fn, name) {
  9681. return function traversalCache(arg1, arg2, arg3, arg4) {
  9682. var selectorOrEles = arg1;
  9683. var eles = this;
  9684. var key;
  9685. if (selectorOrEles == null) {
  9686. key = '';
  9687. } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {
  9688. key = selectorOrEles.id();
  9689. }
  9690. if (eles.length === 1 && key) {
  9691. var _p = eles[0]._private;
  9692. var tch = _p.traversalCache = _p.traversalCache || {};
  9693. var ch = tch[name] = tch[name] || [];
  9694. var hash = hashString(key);
  9695. var cacheHit = ch[hash];
  9696. if (cacheHit) {
  9697. return cacheHit;
  9698. } else {
  9699. return ch[hash] = fn.call(eles, arg1, arg2, arg3, arg4);
  9700. }
  9701. } else {
  9702. return fn.call(eles, arg1, arg2, arg3, arg4);
  9703. }
  9704. };
  9705. };
  9706. var elesfn$f = {
  9707. parent: function parent(selector) {
  9708. var parents = [];
  9709. // optimisation for single ele call
  9710. if (this.length === 1) {
  9711. var parent = this[0]._private.parent;
  9712. if (parent) {
  9713. return parent;
  9714. }
  9715. }
  9716. for (var i = 0; i < this.length; i++) {
  9717. var ele = this[i];
  9718. var _parent = ele._private.parent;
  9719. if (_parent) {
  9720. parents.push(_parent);
  9721. }
  9722. }
  9723. return this.spawn(parents, true).filter(selector);
  9724. },
  9725. parents: function parents(selector) {
  9726. var parents = [];
  9727. var eles = this.parent();
  9728. while (eles.nonempty()) {
  9729. for (var i = 0; i < eles.length; i++) {
  9730. var ele = eles[i];
  9731. parents.push(ele);
  9732. }
  9733. eles = eles.parent();
  9734. }
  9735. return this.spawn(parents, true).filter(selector);
  9736. },
  9737. commonAncestors: function commonAncestors(selector) {
  9738. var ancestors;
  9739. for (var i = 0; i < this.length; i++) {
  9740. var ele = this[i];
  9741. var parents = ele.parents();
  9742. ancestors = ancestors || parents;
  9743. ancestors = ancestors.intersect(parents); // current list must be common with current ele parents set
  9744. }
  9745. return ancestors.filter(selector);
  9746. },
  9747. orphans: function orphans(selector) {
  9748. return this.stdFilter(function (ele) {
  9749. return ele.isOrphan();
  9750. }).filter(selector);
  9751. },
  9752. nonorphans: function nonorphans(selector) {
  9753. return this.stdFilter(function (ele) {
  9754. return ele.isChild();
  9755. }).filter(selector);
  9756. },
  9757. children: cache(function (selector) {
  9758. var children = [];
  9759. for (var i = 0; i < this.length; i++) {
  9760. var ele = this[i];
  9761. var eleChildren = ele._private.children;
  9762. for (var j = 0; j < eleChildren.length; j++) {
  9763. children.push(eleChildren[j]);
  9764. }
  9765. }
  9766. return this.spawn(children, true).filter(selector);
  9767. }, 'children'),
  9768. siblings: function siblings(selector) {
  9769. return this.parent().children().not(this).filter(selector);
  9770. },
  9771. isParent: function isParent() {
  9772. var ele = this[0];
  9773. if (ele) {
  9774. return ele.isNode() && ele._private.children.length !== 0;
  9775. }
  9776. },
  9777. isChildless: function isChildless() {
  9778. var ele = this[0];
  9779. if (ele) {
  9780. return ele.isNode() && ele._private.children.length === 0;
  9781. }
  9782. },
  9783. isChild: function isChild() {
  9784. var ele = this[0];
  9785. if (ele) {
  9786. return ele.isNode() && ele._private.parent != null;
  9787. }
  9788. },
  9789. isOrphan: function isOrphan() {
  9790. var ele = this[0];
  9791. if (ele) {
  9792. return ele.isNode() && ele._private.parent == null;
  9793. }
  9794. },
  9795. descendants: function descendants(selector) {
  9796. var elements = [];
  9797. function add(eles) {
  9798. for (var i = 0; i < eles.length; i++) {
  9799. var ele = eles[i];
  9800. elements.push(ele);
  9801. if (ele.children().nonempty()) {
  9802. add(ele.children());
  9803. }
  9804. }
  9805. }
  9806. add(this.children());
  9807. return this.spawn(elements, true).filter(selector);
  9808. }
  9809. };
  9810. function forEachCompound(eles, fn, includeSelf, recursiveStep) {
  9811. var q = [];
  9812. var did = new Set$1();
  9813. var cy = eles.cy();
  9814. var hasCompounds = cy.hasCompoundNodes();
  9815. for (var i = 0; i < eles.length; i++) {
  9816. var ele = eles[i];
  9817. if (includeSelf) {
  9818. q.push(ele);
  9819. } else if (hasCompounds) {
  9820. recursiveStep(q, did, ele);
  9821. }
  9822. }
  9823. while (q.length > 0) {
  9824. var _ele = q.shift();
  9825. fn(_ele);
  9826. did.add(_ele.id());
  9827. if (hasCompounds) {
  9828. recursiveStep(q, did, _ele);
  9829. }
  9830. }
  9831. return eles;
  9832. }
  9833. function addChildren(q, did, ele) {
  9834. if (ele.isParent()) {
  9835. var children = ele._private.children;
  9836. for (var i = 0; i < children.length; i++) {
  9837. var child = children[i];
  9838. if (!did.has(child.id())) {
  9839. q.push(child);
  9840. }
  9841. }
  9842. }
  9843. }
  9844. // very efficient version of eles.add( eles.descendants() ).forEach()
  9845. // for internal use
  9846. elesfn$f.forEachDown = function (fn) {
  9847. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9848. return forEachCompound(this, fn, includeSelf, addChildren);
  9849. };
  9850. function addParent(q, did, ele) {
  9851. if (ele.isChild()) {
  9852. var parent = ele._private.parent;
  9853. if (!did.has(parent.id())) {
  9854. q.push(parent);
  9855. }
  9856. }
  9857. }
  9858. elesfn$f.forEachUp = function (fn) {
  9859. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9860. return forEachCompound(this, fn, includeSelf, addParent);
  9861. };
  9862. function addParentAndChildren(q, did, ele) {
  9863. addParent(q, did, ele);
  9864. addChildren(q, did, ele);
  9865. }
  9866. elesfn$f.forEachUpAndDown = function (fn) {
  9867. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9868. return forEachCompound(this, fn, includeSelf, addParentAndChildren);
  9869. };
  9870. // aliases
  9871. elesfn$f.ancestors = elesfn$f.parents;
  9872. var fn$5, elesfn$e;
  9873. fn$5 = elesfn$e = {
  9874. data: define.data({
  9875. field: 'data',
  9876. bindingEvent: 'data',
  9877. allowBinding: true,
  9878. allowSetting: true,
  9879. settingEvent: 'data',
  9880. settingTriggersEvent: true,
  9881. triggerFnName: 'trigger',
  9882. allowGetting: true,
  9883. immutableKeys: {
  9884. 'id': true,
  9885. 'source': true,
  9886. 'target': true,
  9887. 'parent': true
  9888. },
  9889. updateStyle: true
  9890. }),
  9891. removeData: define.removeData({
  9892. field: 'data',
  9893. event: 'data',
  9894. triggerFnName: 'trigger',
  9895. triggerEvent: true,
  9896. immutableKeys: {
  9897. 'id': true,
  9898. 'source': true,
  9899. 'target': true,
  9900. 'parent': true
  9901. },
  9902. updateStyle: true
  9903. }),
  9904. scratch: define.data({
  9905. field: 'scratch',
  9906. bindingEvent: 'scratch',
  9907. allowBinding: true,
  9908. allowSetting: true,
  9909. settingEvent: 'scratch',
  9910. settingTriggersEvent: true,
  9911. triggerFnName: 'trigger',
  9912. allowGetting: true,
  9913. updateStyle: true
  9914. }),
  9915. removeScratch: define.removeData({
  9916. field: 'scratch',
  9917. event: 'scratch',
  9918. triggerFnName: 'trigger',
  9919. triggerEvent: true,
  9920. updateStyle: true
  9921. }),
  9922. rscratch: define.data({
  9923. field: 'rscratch',
  9924. allowBinding: false,
  9925. allowSetting: true,
  9926. settingTriggersEvent: false,
  9927. allowGetting: true
  9928. }),
  9929. removeRscratch: define.removeData({
  9930. field: 'rscratch',
  9931. triggerEvent: false
  9932. }),
  9933. id: function id() {
  9934. var ele = this[0];
  9935. if (ele) {
  9936. return ele._private.data.id;
  9937. }
  9938. }
  9939. };
  9940. // aliases
  9941. fn$5.attr = fn$5.data;
  9942. fn$5.removeAttr = fn$5.removeData;
  9943. var data = elesfn$e;
  9944. var elesfn$d = {};
  9945. function defineDegreeFunction(callback) {
  9946. return function (includeLoops) {
  9947. var self = this;
  9948. if (includeLoops === undefined) {
  9949. includeLoops = true;
  9950. }
  9951. if (self.length === 0) {
  9952. return;
  9953. }
  9954. if (self.isNode() && !self.removed()) {
  9955. var degree = 0;
  9956. var node = self[0];
  9957. var connectedEdges = node._private.edges;
  9958. for (var i = 0; i < connectedEdges.length; i++) {
  9959. var edge = connectedEdges[i];
  9960. if (!includeLoops && edge.isLoop()) {
  9961. continue;
  9962. }
  9963. degree += callback(node, edge);
  9964. }
  9965. return degree;
  9966. } else {
  9967. return;
  9968. }
  9969. };
  9970. }
  9971. extend(elesfn$d, {
  9972. degree: defineDegreeFunction(function (node, edge) {
  9973. if (edge.source().same(edge.target())) {
  9974. return 2;
  9975. } else {
  9976. return 1;
  9977. }
  9978. }),
  9979. indegree: defineDegreeFunction(function (node, edge) {
  9980. if (edge.target().same(node)) {
  9981. return 1;
  9982. } else {
  9983. return 0;
  9984. }
  9985. }),
  9986. outdegree: defineDegreeFunction(function (node, edge) {
  9987. if (edge.source().same(node)) {
  9988. return 1;
  9989. } else {
  9990. return 0;
  9991. }
  9992. })
  9993. });
  9994. function defineDegreeBoundsFunction(degreeFn, callback) {
  9995. return function (includeLoops) {
  9996. var ret;
  9997. var nodes = this.nodes();
  9998. for (var i = 0; i < nodes.length; i++) {
  9999. var ele = nodes[i];
  10000. var degree = ele[degreeFn](includeLoops);
  10001. if (degree !== undefined && (ret === undefined || callback(degree, ret))) {
  10002. ret = degree;
  10003. }
  10004. }
  10005. return ret;
  10006. };
  10007. }
  10008. extend(elesfn$d, {
  10009. minDegree: defineDegreeBoundsFunction('degree', function (degree, min) {
  10010. return degree < min;
  10011. }),
  10012. maxDegree: defineDegreeBoundsFunction('degree', function (degree, max) {
  10013. return degree > max;
  10014. }),
  10015. minIndegree: defineDegreeBoundsFunction('indegree', function (degree, min) {
  10016. return degree < min;
  10017. }),
  10018. maxIndegree: defineDegreeBoundsFunction('indegree', function (degree, max) {
  10019. return degree > max;
  10020. }),
  10021. minOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, min) {
  10022. return degree < min;
  10023. }),
  10024. maxOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, max) {
  10025. return degree > max;
  10026. })
  10027. });
  10028. extend(elesfn$d, {
  10029. totalDegree: function totalDegree(includeLoops) {
  10030. var total = 0;
  10031. var nodes = this.nodes();
  10032. for (var i = 0; i < nodes.length; i++) {
  10033. total += nodes[i].degree(includeLoops);
  10034. }
  10035. return total;
  10036. }
  10037. });
  10038. var fn$4, elesfn$c;
  10039. var beforePositionSet = function beforePositionSet(eles, newPos, silent) {
  10040. for (var i = 0; i < eles.length; i++) {
  10041. var ele = eles[i];
  10042. if (!ele.locked()) {
  10043. var oldPos = ele._private.position;
  10044. var delta = {
  10045. x: newPos.x != null ? newPos.x - oldPos.x : 0,
  10046. y: newPos.y != null ? newPos.y - oldPos.y : 0
  10047. };
  10048. if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {
  10049. ele.children().shift(delta, silent);
  10050. }
  10051. ele.dirtyBoundingBoxCache();
  10052. }
  10053. }
  10054. };
  10055. var positionDef = {
  10056. field: 'position',
  10057. bindingEvent: 'position',
  10058. allowBinding: true,
  10059. allowSetting: true,
  10060. settingEvent: 'position',
  10061. settingTriggersEvent: true,
  10062. triggerFnName: 'emitAndNotify',
  10063. allowGetting: true,
  10064. validKeys: ['x', 'y'],
  10065. beforeGet: function beforeGet(ele) {
  10066. ele.updateCompoundBounds();
  10067. },
  10068. beforeSet: function beforeSet(eles, newPos) {
  10069. beforePositionSet(eles, newPos, false);
  10070. },
  10071. onSet: function onSet(eles) {
  10072. eles.dirtyCompoundBoundsCache();
  10073. },
  10074. canSet: function canSet(ele) {
  10075. return !ele.locked();
  10076. }
  10077. };
  10078. fn$4 = elesfn$c = {
  10079. position: define.data(positionDef),
  10080. // position but no notification to renderer
  10081. silentPosition: define.data(extend({}, positionDef, {
  10082. allowBinding: false,
  10083. allowSetting: true,
  10084. settingTriggersEvent: false,
  10085. allowGetting: false,
  10086. beforeSet: function beforeSet(eles, newPos) {
  10087. beforePositionSet(eles, newPos, true);
  10088. },
  10089. onSet: function onSet(eles) {
  10090. eles.dirtyCompoundBoundsCache();
  10091. }
  10092. })),
  10093. positions: function positions(pos, silent) {
  10094. if (plainObject(pos)) {
  10095. if (silent) {
  10096. this.silentPosition(pos);
  10097. } else {
  10098. this.position(pos);
  10099. }
  10100. } else if (fn$6(pos)) {
  10101. var _fn = pos;
  10102. var cy = this.cy();
  10103. cy.startBatch();
  10104. for (var i = 0; i < this.length; i++) {
  10105. var ele = this[i];
  10106. var _pos = undefined;
  10107. if (_pos = _fn(ele, i)) {
  10108. if (silent) {
  10109. ele.silentPosition(_pos);
  10110. } else {
  10111. ele.position(_pos);
  10112. }
  10113. }
  10114. }
  10115. cy.endBatch();
  10116. }
  10117. return this; // chaining
  10118. },
  10119. silentPositions: function silentPositions(pos) {
  10120. return this.positions(pos, true);
  10121. },
  10122. shift: function shift(dim, val, silent) {
  10123. var delta;
  10124. if (plainObject(dim)) {
  10125. delta = {
  10126. x: number$1(dim.x) ? dim.x : 0,
  10127. y: number$1(dim.y) ? dim.y : 0
  10128. };
  10129. silent = val;
  10130. } else if (string(dim) && number$1(val)) {
  10131. delta = {
  10132. x: 0,
  10133. y: 0
  10134. };
  10135. delta[dim] = val;
  10136. }
  10137. if (delta != null) {
  10138. var cy = this.cy();
  10139. cy.startBatch();
  10140. for (var i = 0; i < this.length; i++) {
  10141. var ele = this[i];
  10142. // exclude any node that is a descendant of the calling collection
  10143. if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {
  10144. continue;
  10145. }
  10146. var pos = ele.position();
  10147. var newPos = {
  10148. x: pos.x + delta.x,
  10149. y: pos.y + delta.y
  10150. };
  10151. if (silent) {
  10152. ele.silentPosition(newPos);
  10153. } else {
  10154. ele.position(newPos);
  10155. }
  10156. }
  10157. cy.endBatch();
  10158. }
  10159. return this;
  10160. },
  10161. silentShift: function silentShift(dim, val) {
  10162. if (plainObject(dim)) {
  10163. this.shift(dim, true);
  10164. } else if (string(dim) && number$1(val)) {
  10165. this.shift(dim, val, true);
  10166. }
  10167. return this;
  10168. },
  10169. // get/set the rendered (i.e. on screen) positon of the element
  10170. renderedPosition: function renderedPosition(dim, val) {
  10171. var ele = this[0];
  10172. var cy = this.cy();
  10173. var zoom = cy.zoom();
  10174. var pan = cy.pan();
  10175. var rpos = plainObject(dim) ? dim : undefined;
  10176. var setting = rpos !== undefined || val !== undefined && string(dim);
  10177. if (ele && ele.isNode()) {
  10178. // must have an element and must be a node to return position
  10179. if (setting) {
  10180. for (var i = 0; i < this.length; i++) {
  10181. var _ele = this[i];
  10182. if (val !== undefined) {
  10183. // set one dimension
  10184. _ele.position(dim, (val - pan[dim]) / zoom);
  10185. } else if (rpos !== undefined) {
  10186. // set whole position
  10187. _ele.position(renderedToModelPosition(rpos, zoom, pan));
  10188. }
  10189. }
  10190. } else {
  10191. // getting
  10192. var pos = ele.position();
  10193. rpos = modelToRenderedPosition$1(pos, zoom, pan);
  10194. if (dim === undefined) {
  10195. // then return the whole rendered position
  10196. return rpos;
  10197. } else {
  10198. // then return the specified dimension
  10199. return rpos[dim];
  10200. }
  10201. }
  10202. } else if (!setting) {
  10203. return undefined; // for empty collection case
  10204. }
  10205. return this; // chaining
  10206. },
  10207. // get/set the position relative to the parent
  10208. relativePosition: function relativePosition(dim, val) {
  10209. var ele = this[0];
  10210. var cy = this.cy();
  10211. var ppos = plainObject(dim) ? dim : undefined;
  10212. var setting = ppos !== undefined || val !== undefined && string(dim);
  10213. var hasCompoundNodes = cy.hasCompoundNodes();
  10214. if (ele && ele.isNode()) {
  10215. // must have an element and must be a node to return position
  10216. if (setting) {
  10217. for (var i = 0; i < this.length; i++) {
  10218. var _ele2 = this[i];
  10219. var parent = hasCompoundNodes ? _ele2.parent() : null;
  10220. var hasParent = parent && parent.length > 0;
  10221. var relativeToParent = hasParent;
  10222. if (hasParent) {
  10223. parent = parent[0];
  10224. }
  10225. var origin = relativeToParent ? parent.position() : {
  10226. x: 0,
  10227. y: 0
  10228. };
  10229. if (val !== undefined) {
  10230. // set one dimension
  10231. _ele2.position(dim, val + origin[dim]);
  10232. } else if (ppos !== undefined) {
  10233. // set whole position
  10234. _ele2.position({
  10235. x: ppos.x + origin.x,
  10236. y: ppos.y + origin.y
  10237. });
  10238. }
  10239. }
  10240. } else {
  10241. // getting
  10242. var pos = ele.position();
  10243. var _parent = hasCompoundNodes ? ele.parent() : null;
  10244. var _hasParent = _parent && _parent.length > 0;
  10245. var _relativeToParent = _hasParent;
  10246. if (_hasParent) {
  10247. _parent = _parent[0];
  10248. }
  10249. var _origin = _relativeToParent ? _parent.position() : {
  10250. x: 0,
  10251. y: 0
  10252. };
  10253. ppos = {
  10254. x: pos.x - _origin.x,
  10255. y: pos.y - _origin.y
  10256. };
  10257. if (dim === undefined) {
  10258. // then return the whole rendered position
  10259. return ppos;
  10260. } else {
  10261. // then return the specified dimension
  10262. return ppos[dim];
  10263. }
  10264. }
  10265. } else if (!setting) {
  10266. return undefined; // for empty collection case
  10267. }
  10268. return this; // chaining
  10269. }
  10270. };
  10271. // aliases
  10272. fn$4.modelPosition = fn$4.point = fn$4.position;
  10273. fn$4.modelPositions = fn$4.points = fn$4.positions;
  10274. fn$4.renderedPoint = fn$4.renderedPosition;
  10275. fn$4.relativePoint = fn$4.relativePosition;
  10276. var position = elesfn$c;
  10277. var fn$3, elesfn$b;
  10278. fn$3 = elesfn$b = {};
  10279. elesfn$b.renderedBoundingBox = function (options) {
  10280. var bb = this.boundingBox(options);
  10281. var cy = this.cy();
  10282. var zoom = cy.zoom();
  10283. var pan = cy.pan();
  10284. var x1 = bb.x1 * zoom + pan.x;
  10285. var x2 = bb.x2 * zoom + pan.x;
  10286. var y1 = bb.y1 * zoom + pan.y;
  10287. var y2 = bb.y2 * zoom + pan.y;
  10288. return {
  10289. x1: x1,
  10290. x2: x2,
  10291. y1: y1,
  10292. y2: y2,
  10293. w: x2 - x1,
  10294. h: y2 - y1
  10295. };
  10296. };
  10297. elesfn$b.dirtyCompoundBoundsCache = function () {
  10298. var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  10299. var cy = this.cy();
  10300. if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
  10301. return this;
  10302. }
  10303. this.forEachUp(function (ele) {
  10304. if (ele.isParent()) {
  10305. var _p = ele._private;
  10306. _p.compoundBoundsClean = false;
  10307. _p.bbCache = null;
  10308. if (!silent) {
  10309. ele.emitAndNotify('bounds');
  10310. }
  10311. }
  10312. });
  10313. return this;
  10314. };
  10315. elesfn$b.updateCompoundBounds = function () {
  10316. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  10317. var cy = this.cy();
  10318. // not possible to do on non-compound graphs or with the style disabled
  10319. if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
  10320. return this;
  10321. }
  10322. // save cycles when batching -- but bounds will be stale (or not exist yet)
  10323. if (!force && cy.batching()) {
  10324. return this;
  10325. }
  10326. function update(parent) {
  10327. if (!parent.isParent()) {
  10328. return;
  10329. }
  10330. var _p = parent._private;
  10331. var children = parent.children();
  10332. var includeLabels = parent.pstyle('compound-sizing-wrt-labels').value === 'include';
  10333. var min = {
  10334. width: {
  10335. val: parent.pstyle('min-width').pfValue,
  10336. left: parent.pstyle('min-width-bias-left'),
  10337. right: parent.pstyle('min-width-bias-right')
  10338. },
  10339. height: {
  10340. val: parent.pstyle('min-height').pfValue,
  10341. top: parent.pstyle('min-height-bias-top'),
  10342. bottom: parent.pstyle('min-height-bias-bottom')
  10343. }
  10344. };
  10345. var bb = children.boundingBox({
  10346. includeLabels: includeLabels,
  10347. includeOverlays: false,
  10348. // updating the compound bounds happens outside of the regular
  10349. // cache cycle (i.e. before fired events)
  10350. useCache: false
  10351. });
  10352. var pos = _p.position;
  10353. // if children take up zero area then keep position and fall back on stylesheet w/h
  10354. if (bb.w === 0 || bb.h === 0) {
  10355. bb = {
  10356. w: parent.pstyle('width').pfValue,
  10357. h: parent.pstyle('height').pfValue
  10358. };
  10359. bb.x1 = pos.x - bb.w / 2;
  10360. bb.x2 = pos.x + bb.w / 2;
  10361. bb.y1 = pos.y - bb.h / 2;
  10362. bb.y2 = pos.y + bb.h / 2;
  10363. }
  10364. function computeBiasValues(propDiff, propBias, propBiasComplement) {
  10365. var biasDiff = 0;
  10366. var biasComplementDiff = 0;
  10367. var biasTotal = propBias + propBiasComplement;
  10368. if (propDiff > 0 && biasTotal > 0) {
  10369. biasDiff = propBias / biasTotal * propDiff;
  10370. biasComplementDiff = propBiasComplement / biasTotal * propDiff;
  10371. }
  10372. return {
  10373. biasDiff: biasDiff,
  10374. biasComplementDiff: biasComplementDiff
  10375. };
  10376. }
  10377. function computePaddingValues(width, height, paddingObject, relativeTo) {
  10378. // Assuming percentage is number from 0 to 1
  10379. if (paddingObject.units === '%') {
  10380. switch (relativeTo) {
  10381. case 'width':
  10382. return width > 0 ? paddingObject.pfValue * width : 0;
  10383. case 'height':
  10384. return height > 0 ? paddingObject.pfValue * height : 0;
  10385. case 'average':
  10386. return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;
  10387. case 'min':
  10388. return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;
  10389. case 'max':
  10390. return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;
  10391. default:
  10392. return 0;
  10393. }
  10394. } else if (paddingObject.units === 'px') {
  10395. return paddingObject.pfValue;
  10396. } else {
  10397. return 0;
  10398. }
  10399. }
  10400. var leftVal = min.width.left.value;
  10401. if (min.width.left.units === 'px' && min.width.val > 0) {
  10402. leftVal = leftVal * 100 / min.width.val;
  10403. }
  10404. var rightVal = min.width.right.value;
  10405. if (min.width.right.units === 'px' && min.width.val > 0) {
  10406. rightVal = rightVal * 100 / min.width.val;
  10407. }
  10408. var topVal = min.height.top.value;
  10409. if (min.height.top.units === 'px' && min.height.val > 0) {
  10410. topVal = topVal * 100 / min.height.val;
  10411. }
  10412. var bottomVal = min.height.bottom.value;
  10413. if (min.height.bottom.units === 'px' && min.height.val > 0) {
  10414. bottomVal = bottomVal * 100 / min.height.val;
  10415. }
  10416. var widthBiasDiffs = computeBiasValues(min.width.val - bb.w, leftVal, rightVal);
  10417. var diffLeft = widthBiasDiffs.biasDiff;
  10418. var diffRight = widthBiasDiffs.biasComplementDiff;
  10419. var heightBiasDiffs = computeBiasValues(min.height.val - bb.h, topVal, bottomVal);
  10420. var diffTop = heightBiasDiffs.biasDiff;
  10421. var diffBottom = heightBiasDiffs.biasComplementDiff;
  10422. _p.autoPadding = computePaddingValues(bb.w, bb.h, parent.pstyle('padding'), parent.pstyle('padding-relative-to').value);
  10423. _p.autoWidth = Math.max(bb.w, min.width.val);
  10424. pos.x = (-diffLeft + bb.x1 + bb.x2 + diffRight) / 2;
  10425. _p.autoHeight = Math.max(bb.h, min.height.val);
  10426. pos.y = (-diffTop + bb.y1 + bb.y2 + diffBottom) / 2;
  10427. }
  10428. for (var i = 0; i < this.length; i++) {
  10429. var ele = this[i];
  10430. var _p = ele._private;
  10431. if (!_p.compoundBoundsClean || force) {
  10432. update(ele);
  10433. if (!cy.batching()) {
  10434. _p.compoundBoundsClean = true;
  10435. }
  10436. }
  10437. }
  10438. return this;
  10439. };
  10440. var noninf = function noninf(x) {
  10441. if (x === Infinity || x === -Infinity) {
  10442. return 0;
  10443. }
  10444. return x;
  10445. };
  10446. var updateBounds = function updateBounds(b, x1, y1, x2, y2) {
  10447. // don't update with zero area boxes
  10448. if (x2 - x1 === 0 || y2 - y1 === 0) {
  10449. return;
  10450. }
  10451. // don't update with null dim
  10452. if (x1 == null || y1 == null || x2 == null || y2 == null) {
  10453. return;
  10454. }
  10455. b.x1 = x1 < b.x1 ? x1 : b.x1;
  10456. b.x2 = x2 > b.x2 ? x2 : b.x2;
  10457. b.y1 = y1 < b.y1 ? y1 : b.y1;
  10458. b.y2 = y2 > b.y2 ? y2 : b.y2;
  10459. b.w = b.x2 - b.x1;
  10460. b.h = b.y2 - b.y1;
  10461. };
  10462. var updateBoundsFromBox = function updateBoundsFromBox(b, b2) {
  10463. if (b2 == null) {
  10464. return b;
  10465. }
  10466. return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);
  10467. };
  10468. var prefixedProperty = function prefixedProperty(obj, field, prefix) {
  10469. return getPrefixedProperty(obj, field, prefix);
  10470. };
  10471. var updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {
  10472. if (ele.cy().headless()) {
  10473. return;
  10474. }
  10475. var _p = ele._private;
  10476. var rstyle = _p.rstyle;
  10477. var halfArW = rstyle.arrowWidth / 2;
  10478. var arrowType = ele.pstyle(prefix + '-arrow-shape').value;
  10479. var x;
  10480. var y;
  10481. if (arrowType !== 'none') {
  10482. if (prefix === 'source') {
  10483. x = rstyle.srcX;
  10484. y = rstyle.srcY;
  10485. } else if (prefix === 'target') {
  10486. x = rstyle.tgtX;
  10487. y = rstyle.tgtY;
  10488. } else {
  10489. x = rstyle.midX;
  10490. y = rstyle.midY;
  10491. }
  10492. // always store the individual arrow bounds
  10493. var bbs = _p.arrowBounds = _p.arrowBounds || {};
  10494. var bb = bbs[prefix] = bbs[prefix] || {};
  10495. bb.x1 = x - halfArW;
  10496. bb.y1 = y - halfArW;
  10497. bb.x2 = x + halfArW;
  10498. bb.y2 = y + halfArW;
  10499. bb.w = bb.x2 - bb.x1;
  10500. bb.h = bb.y2 - bb.y1;
  10501. expandBoundingBox(bb, 1);
  10502. updateBounds(bounds, bb.x1, bb.y1, bb.x2, bb.y2);
  10503. }
  10504. };
  10505. var updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {
  10506. if (ele.cy().headless()) {
  10507. return;
  10508. }
  10509. var prefixDash;
  10510. if (prefix) {
  10511. prefixDash = prefix + '-';
  10512. } else {
  10513. prefixDash = '';
  10514. }
  10515. var _p = ele._private;
  10516. var rstyle = _p.rstyle;
  10517. var label = ele.pstyle(prefixDash + 'label').strValue;
  10518. if (label) {
  10519. var halign = ele.pstyle('text-halign');
  10520. var valign = ele.pstyle('text-valign');
  10521. var labelWidth = prefixedProperty(rstyle, 'labelWidth', prefix);
  10522. var labelHeight = prefixedProperty(rstyle, 'labelHeight', prefix);
  10523. var labelX = prefixedProperty(rstyle, 'labelX', prefix);
  10524. var labelY = prefixedProperty(rstyle, 'labelY', prefix);
  10525. var marginX = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  10526. var marginY = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  10527. var isEdge = ele.isEdge();
  10528. var rotation = ele.pstyle(prefixDash + 'text-rotation');
  10529. var outlineWidth = ele.pstyle('text-outline-width').pfValue;
  10530. var borderWidth = ele.pstyle('text-border-width').pfValue;
  10531. var halfBorderWidth = borderWidth / 2;
  10532. var padding = ele.pstyle('text-background-padding').pfValue;
  10533. var marginOfError = 2; // expand to work around browser dimension inaccuracies
  10534. var lh = labelHeight;
  10535. var lw = labelWidth;
  10536. var lw_2 = lw / 2;
  10537. var lh_2 = lh / 2;
  10538. var lx1, lx2, ly1, ly2;
  10539. if (isEdge) {
  10540. lx1 = labelX - lw_2;
  10541. lx2 = labelX + lw_2;
  10542. ly1 = labelY - lh_2;
  10543. ly2 = labelY + lh_2;
  10544. } else {
  10545. switch (halign.value) {
  10546. case 'left':
  10547. lx1 = labelX - lw;
  10548. lx2 = labelX;
  10549. break;
  10550. case 'center':
  10551. lx1 = labelX - lw_2;
  10552. lx2 = labelX + lw_2;
  10553. break;
  10554. case 'right':
  10555. lx1 = labelX;
  10556. lx2 = labelX + lw;
  10557. break;
  10558. }
  10559. switch (valign.value) {
  10560. case 'top':
  10561. ly1 = labelY - lh;
  10562. ly2 = labelY;
  10563. break;
  10564. case 'center':
  10565. ly1 = labelY - lh_2;
  10566. ly2 = labelY + lh_2;
  10567. break;
  10568. case 'bottom':
  10569. ly1 = labelY;
  10570. ly2 = labelY + lh;
  10571. break;
  10572. }
  10573. }
  10574. // shift by margin and expand by outline and border
  10575. var leftPad = marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
  10576. var rightPad = marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
  10577. var topPad = marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
  10578. var botPad = marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
  10579. lx1 += leftPad;
  10580. lx2 += rightPad;
  10581. ly1 += topPad;
  10582. ly2 += botPad;
  10583. // always store the unrotated label bounds separately
  10584. var bbPrefix = prefix || 'main';
  10585. var bbs = _p.labelBounds;
  10586. var bb = bbs[bbPrefix] = bbs[bbPrefix] || {};
  10587. bb.x1 = lx1;
  10588. bb.y1 = ly1;
  10589. bb.x2 = lx2;
  10590. bb.y2 = ly2;
  10591. bb.w = lx2 - lx1;
  10592. bb.h = ly2 - ly1;
  10593. bb.leftPad = leftPad;
  10594. bb.rightPad = rightPad;
  10595. bb.topPad = topPad;
  10596. bb.botPad = botPad;
  10597. var isAutorotate = isEdge && rotation.strValue === 'autorotate';
  10598. var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;
  10599. if (isAutorotate || isPfValue) {
  10600. var theta = isAutorotate ? prefixedProperty(_p.rstyle, 'labelAngle', prefix) : rotation.pfValue;
  10601. var cos = Math.cos(theta);
  10602. var sin = Math.sin(theta);
  10603. // rotation point (default value for center-center)
  10604. var xo = (lx1 + lx2) / 2;
  10605. var yo = (ly1 + ly2) / 2;
  10606. if (!isEdge) {
  10607. switch (halign.value) {
  10608. case 'left':
  10609. xo = lx2;
  10610. break;
  10611. case 'right':
  10612. xo = lx1;
  10613. break;
  10614. }
  10615. switch (valign.value) {
  10616. case 'top':
  10617. yo = ly2;
  10618. break;
  10619. case 'bottom':
  10620. yo = ly1;
  10621. break;
  10622. }
  10623. }
  10624. var rotate = function rotate(x, y) {
  10625. x = x - xo;
  10626. y = y - yo;
  10627. return {
  10628. x: x * cos - y * sin + xo,
  10629. y: x * sin + y * cos + yo
  10630. };
  10631. };
  10632. var px1y1 = rotate(lx1, ly1);
  10633. var px1y2 = rotate(lx1, ly2);
  10634. var px2y1 = rotate(lx2, ly1);
  10635. var px2y2 = rotate(lx2, ly2);
  10636. lx1 = Math.min(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
  10637. lx2 = Math.max(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
  10638. ly1 = Math.min(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
  10639. ly2 = Math.max(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
  10640. }
  10641. var bbPrefixRot = bbPrefix + 'Rot';
  10642. var bbRot = bbs[bbPrefixRot] = bbs[bbPrefixRot] || {};
  10643. bbRot.x1 = lx1;
  10644. bbRot.y1 = ly1;
  10645. bbRot.x2 = lx2;
  10646. bbRot.y2 = ly2;
  10647. bbRot.w = lx2 - lx1;
  10648. bbRot.h = ly2 - ly1;
  10649. updateBounds(bounds, lx1, ly1, lx2, ly2);
  10650. updateBounds(_p.labelBounds.all, lx1, ly1, lx2, ly2);
  10651. }
  10652. return bounds;
  10653. };
  10654. var updateBoundsFromOutline = function updateBoundsFromOutline(bounds, ele) {
  10655. if (ele.cy().headless()) {
  10656. return;
  10657. }
  10658. var outlineOpacity = ele.pstyle('outline-opacity').value;
  10659. var outlineWidth = ele.pstyle('outline-width').value;
  10660. var outlineOffset = ele.pstyle('outline-offset').value;
  10661. var expansion = outlineWidth + outlineOffset;
  10662. updateBoundsFromMiter(bounds, ele, outlineOpacity, expansion, 'outside', expansion / 2);
  10663. };
  10664. var updateBoundsFromMiter = function updateBoundsFromMiter(bounds, ele, opacity, expansionSize, expansionPosition, useFallbackValue) {
  10665. if (opacity === 0 || expansionSize <= 0 || expansionPosition === 'inside') {
  10666. return;
  10667. }
  10668. var cy = ele.cy();
  10669. var r = cy.renderer();
  10670. var rshape = r.nodeShapes[r.getNodeShape(ele)];
  10671. if (!rshape) {
  10672. return;
  10673. }
  10674. var _ele$position = ele.position(),
  10675. x = _ele$position.x,
  10676. y = _ele$position.y;
  10677. var w = ele.width();
  10678. var h = ele.height();
  10679. if (rshape.hasMiterBounds) {
  10680. if (expansionPosition === 'center') {
  10681. expansionSize /= 2;
  10682. }
  10683. var mbb = rshape.miterBounds(x, y, w, h, expansionSize);
  10684. updateBoundsFromBox(bounds, mbb);
  10685. } else if (useFallbackValue != null && useFallbackValue > 0) {
  10686. expandBoundingBoxSides(bounds, [useFallbackValue, useFallbackValue, useFallbackValue, useFallbackValue]);
  10687. }
  10688. };
  10689. var updateBoundsFromMiterBorder = function updateBoundsFromMiterBorder(bounds, ele) {
  10690. if (ele.cy().headless()) {
  10691. return;
  10692. }
  10693. var borderOpacity = ele.pstyle('border-opacity').value;
  10694. var borderWidth = ele.pstyle('border-width').pfValue;
  10695. var borderPosition = ele.pstyle('border-position').value;
  10696. updateBoundsFromMiter(bounds, ele, borderOpacity, borderWidth, borderPosition);
  10697. };
  10698. // get the bounding box of the elements (in raw model position)
  10699. var boundingBoxImpl = function boundingBoxImpl(ele, options) {
  10700. var cy = ele._private.cy;
  10701. var styleEnabled = cy.styleEnabled();
  10702. var headless = cy.headless();
  10703. var bounds = makeBoundingBox();
  10704. var _p = ele._private;
  10705. var isNode = ele.isNode();
  10706. var isEdge = ele.isEdge();
  10707. var ex1, ex2, ey1, ey2; // extrema of body / lines
  10708. var x, y; // node pos
  10709. var rstyle = _p.rstyle;
  10710. var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0];
  10711. // must use `display` prop only, as reading `compound.width()` causes recursion
  10712. // (other factors like width values will be considered later in this function anyway)
  10713. var isDisplayed = function isDisplayed(ele) {
  10714. return ele.pstyle('display').value !== 'none';
  10715. };
  10716. var displayed = !styleEnabled || isDisplayed(ele)
  10717. // must take into account connected nodes b/c of implicit edge hiding on display:none node
  10718. && (!isEdge || isDisplayed(ele.source()) && isDisplayed(ele.target()));
  10719. if (displayed) {
  10720. // displayed suffices, since we will find zero area eles anyway
  10721. var overlayOpacity = 0;
  10722. var overlayPadding = 0;
  10723. if (styleEnabled && options.includeOverlays) {
  10724. overlayOpacity = ele.pstyle('overlay-opacity').value;
  10725. if (overlayOpacity !== 0) {
  10726. overlayPadding = ele.pstyle('overlay-padding').value;
  10727. }
  10728. }
  10729. var underlayOpacity = 0;
  10730. var underlayPadding = 0;
  10731. if (styleEnabled && options.includeUnderlays) {
  10732. underlayOpacity = ele.pstyle('underlay-opacity').value;
  10733. if (underlayOpacity !== 0) {
  10734. underlayPadding = ele.pstyle('underlay-padding').value;
  10735. }
  10736. }
  10737. var padding = Math.max(overlayPadding, underlayPadding);
  10738. var w = 0;
  10739. var wHalf = 0;
  10740. if (styleEnabled) {
  10741. w = ele.pstyle('width').pfValue;
  10742. wHalf = w / 2;
  10743. }
  10744. if (isNode && options.includeNodes) {
  10745. var pos = ele.position();
  10746. x = pos.x;
  10747. y = pos.y;
  10748. var _w = ele.outerWidth();
  10749. var halfW = _w / 2;
  10750. var h = ele.outerHeight();
  10751. var halfH = h / 2;
  10752. // handle node dimensions
  10753. /////////////////////////
  10754. ex1 = x - halfW;
  10755. ex2 = x + halfW;
  10756. ey1 = y - halfH;
  10757. ey2 = y + halfH;
  10758. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10759. if (styleEnabled) {
  10760. updateBoundsFromOutline(bounds, ele);
  10761. }
  10762. if (styleEnabled && options.includeOutlines && !headless) {
  10763. updateBoundsFromOutline(bounds, ele);
  10764. }
  10765. if (styleEnabled) {
  10766. updateBoundsFromMiterBorder(bounds, ele);
  10767. }
  10768. } else if (isEdge && options.includeEdges) {
  10769. if (styleEnabled && !headless) {
  10770. var curveStyle = ele.pstyle('curve-style').strValue;
  10771. // handle edge dimensions (rough box estimate)
  10772. //////////////////////////////////////////////
  10773. ex1 = Math.min(rstyle.srcX, rstyle.midX, rstyle.tgtX);
  10774. ex2 = Math.max(rstyle.srcX, rstyle.midX, rstyle.tgtX);
  10775. ey1 = Math.min(rstyle.srcY, rstyle.midY, rstyle.tgtY);
  10776. ey2 = Math.max(rstyle.srcY, rstyle.midY, rstyle.tgtY);
  10777. // take into account edge width
  10778. ex1 -= wHalf;
  10779. ex2 += wHalf;
  10780. ey1 -= wHalf;
  10781. ey2 += wHalf;
  10782. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10783. // precise edges
  10784. ////////////////
  10785. if (curveStyle === 'haystack') {
  10786. var hpts = rstyle.haystackPts;
  10787. if (hpts && hpts.length === 2) {
  10788. ex1 = hpts[0].x;
  10789. ey1 = hpts[0].y;
  10790. ex2 = hpts[1].x;
  10791. ey2 = hpts[1].y;
  10792. if (ex1 > ex2) {
  10793. var temp = ex1;
  10794. ex1 = ex2;
  10795. ex2 = temp;
  10796. }
  10797. if (ey1 > ey2) {
  10798. var _temp = ey1;
  10799. ey1 = ey2;
  10800. ey2 = _temp;
  10801. }
  10802. updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);
  10803. }
  10804. } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || endsWith(curveStyle, 'taxi')) {
  10805. var pts;
  10806. switch (curveStyle) {
  10807. case 'bezier':
  10808. case 'unbundled-bezier':
  10809. pts = rstyle.bezierPts;
  10810. break;
  10811. case 'segments':
  10812. case 'taxi':
  10813. case 'round-segments':
  10814. case 'round-taxi':
  10815. pts = rstyle.linePts;
  10816. break;
  10817. }
  10818. if (pts != null) {
  10819. for (var j = 0; j < pts.length; j++) {
  10820. var pt = pts[j];
  10821. ex1 = pt.x - wHalf;
  10822. ex2 = pt.x + wHalf;
  10823. ey1 = pt.y - wHalf;
  10824. ey2 = pt.y + wHalf;
  10825. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10826. }
  10827. }
  10828. } // bezier-like or segment-like edge
  10829. } else {
  10830. // headless or style disabled
  10831. // fallback on source and target positions
  10832. //////////////////////////////////////////
  10833. var n1 = ele.source();
  10834. var n1pos = n1.position();
  10835. var n2 = ele.target();
  10836. var n2pos = n2.position();
  10837. ex1 = n1pos.x;
  10838. ex2 = n2pos.x;
  10839. ey1 = n1pos.y;
  10840. ey2 = n2pos.y;
  10841. if (ex1 > ex2) {
  10842. var _temp2 = ex1;
  10843. ex1 = ex2;
  10844. ex2 = _temp2;
  10845. }
  10846. if (ey1 > ey2) {
  10847. var _temp3 = ey1;
  10848. ey1 = ey2;
  10849. ey2 = _temp3;
  10850. }
  10851. // take into account edge width
  10852. ex1 -= wHalf;
  10853. ex2 += wHalf;
  10854. ey1 -= wHalf;
  10855. ey2 += wHalf;
  10856. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10857. } // headless or style disabled
  10858. } // edges
  10859. // handle edge arrow size
  10860. /////////////////////////
  10861. if (styleEnabled && options.includeEdges && isEdge) {
  10862. updateBoundsFromArrow(bounds, ele, 'mid-source');
  10863. updateBoundsFromArrow(bounds, ele, 'mid-target');
  10864. updateBoundsFromArrow(bounds, ele, 'source');
  10865. updateBoundsFromArrow(bounds, ele, 'target');
  10866. }
  10867. // ghost
  10868. ////////
  10869. if (styleEnabled) {
  10870. var ghost = ele.pstyle('ghost').value === 'yes';
  10871. if (ghost) {
  10872. var gx = ele.pstyle('ghost-offset-x').pfValue;
  10873. var gy = ele.pstyle('ghost-offset-y').pfValue;
  10874. updateBounds(bounds, bounds.x1 + gx, bounds.y1 + gy, bounds.x2 + gx, bounds.y2 + gy);
  10875. }
  10876. }
  10877. // always store the body bounds separately from the labels
  10878. var bbBody = _p.bodyBounds = _p.bodyBounds || {};
  10879. assignBoundingBox(bbBody, bounds);
  10880. expandBoundingBoxSides(bbBody, manualExpansion);
  10881. expandBoundingBox(bbBody, 1); // expand to work around browser dimension inaccuracies
  10882. // overlay
  10883. //////////
  10884. if (styleEnabled) {
  10885. ex1 = bounds.x1;
  10886. ex2 = bounds.x2;
  10887. ey1 = bounds.y1;
  10888. ey2 = bounds.y2;
  10889. updateBounds(bounds, ex1 - padding, ey1 - padding, ex2 + padding, ey2 + padding);
  10890. }
  10891. // always store the body bounds separately from the labels
  10892. var bbOverlay = _p.overlayBounds = _p.overlayBounds || {};
  10893. assignBoundingBox(bbOverlay, bounds);
  10894. expandBoundingBoxSides(bbOverlay, manualExpansion);
  10895. expandBoundingBox(bbOverlay, 1); // expand to work around browser dimension inaccuracies
  10896. // handle label dimensions
  10897. //////////////////////////
  10898. var bbLabels = _p.labelBounds = _p.labelBounds || {};
  10899. if (bbLabels.all != null) {
  10900. clearBoundingBox(bbLabels.all);
  10901. } else {
  10902. bbLabels.all = makeBoundingBox();
  10903. }
  10904. if (styleEnabled && options.includeLabels) {
  10905. if (options.includeMainLabels) {
  10906. updateBoundsFromLabel(bounds, ele, null);
  10907. }
  10908. if (isEdge) {
  10909. if (options.includeSourceLabels) {
  10910. updateBoundsFromLabel(bounds, ele, 'source');
  10911. }
  10912. if (options.includeTargetLabels) {
  10913. updateBoundsFromLabel(bounds, ele, 'target');
  10914. }
  10915. }
  10916. } // style enabled for labels
  10917. } // if displayed
  10918. bounds.x1 = noninf(bounds.x1);
  10919. bounds.y1 = noninf(bounds.y1);
  10920. bounds.x2 = noninf(bounds.x2);
  10921. bounds.y2 = noninf(bounds.y2);
  10922. bounds.w = noninf(bounds.x2 - bounds.x1);
  10923. bounds.h = noninf(bounds.y2 - bounds.y1);
  10924. if (bounds.w > 0 && bounds.h > 0 && displayed) {
  10925. expandBoundingBoxSides(bounds, manualExpansion);
  10926. // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides
  10927. expandBoundingBox(bounds, 1);
  10928. }
  10929. return bounds;
  10930. };
  10931. var getKey = function getKey(opts) {
  10932. var i = 0;
  10933. var tf = function tf(val) {
  10934. return (val ? 1 : 0) << i++;
  10935. };
  10936. var key = 0;
  10937. key += tf(opts.incudeNodes);
  10938. key += tf(opts.includeEdges);
  10939. key += tf(opts.includeLabels);
  10940. key += tf(opts.includeMainLabels);
  10941. key += tf(opts.includeSourceLabels);
  10942. key += tf(opts.includeTargetLabels);
  10943. key += tf(opts.includeOverlays);
  10944. key += tf(opts.includeOutlines);
  10945. return key;
  10946. };
  10947. var getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {
  10948. var r = function r(x) {
  10949. return Math.round(x);
  10950. };
  10951. if (ele.isEdge()) {
  10952. var p1 = ele.source().position();
  10953. var p2 = ele.target().position();
  10954. return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);
  10955. } else {
  10956. var p = ele.position();
  10957. return hashIntsArray([r(p.x), r(p.y)]);
  10958. }
  10959. };
  10960. var cachedBoundingBoxImpl = function cachedBoundingBoxImpl(ele, opts) {
  10961. var _p = ele._private;
  10962. var bb;
  10963. var isEdge = ele.isEdge();
  10964. var key = opts == null ? defBbOptsKey : getKey(opts);
  10965. var usingDefOpts = key === defBbOptsKey;
  10966. if (_p.bbCache == null) {
  10967. bb = boundingBoxImpl(ele, defBbOpts);
  10968. _p.bbCache = bb;
  10969. _p.bbCachePosKey = getBoundingBoxPosKey(ele);
  10970. } else {
  10971. bb = _p.bbCache;
  10972. }
  10973. // not using def opts => need to build up bb from combination of sub bbs
  10974. if (!usingDefOpts) {
  10975. var isNode = ele.isNode();
  10976. bb = makeBoundingBox();
  10977. if (opts.includeNodes && isNode || opts.includeEdges && !isNode) {
  10978. if (opts.includeOverlays) {
  10979. updateBoundsFromBox(bb, _p.overlayBounds);
  10980. } else {
  10981. updateBoundsFromBox(bb, _p.bodyBounds);
  10982. }
  10983. }
  10984. if (opts.includeLabels) {
  10985. if (opts.includeMainLabels && (!isEdge || opts.includeSourceLabels && opts.includeTargetLabels)) {
  10986. updateBoundsFromBox(bb, _p.labelBounds.all);
  10987. } else {
  10988. if (opts.includeMainLabels) {
  10989. updateBoundsFromBox(bb, _p.labelBounds.mainRot);
  10990. }
  10991. if (opts.includeSourceLabels) {
  10992. updateBoundsFromBox(bb, _p.labelBounds.sourceRot);
  10993. }
  10994. if (opts.includeTargetLabels) {
  10995. updateBoundsFromBox(bb, _p.labelBounds.targetRot);
  10996. }
  10997. }
  10998. }
  10999. bb.w = bb.x2 - bb.x1;
  11000. bb.h = bb.y2 - bb.y1;
  11001. }
  11002. return bb;
  11003. };
  11004. var defBbOpts = {
  11005. includeNodes: true,
  11006. includeEdges: true,
  11007. includeLabels: true,
  11008. includeMainLabels: true,
  11009. includeSourceLabels: true,
  11010. includeTargetLabels: true,
  11011. includeOverlays: true,
  11012. includeUnderlays: true,
  11013. includeOutlines: true,
  11014. useCache: true
  11015. };
  11016. var defBbOptsKey = getKey(defBbOpts);
  11017. var filledBbOpts = defaults$g(defBbOpts);
  11018. elesfn$b.boundingBox = function (options) {
  11019. var bounds;
  11020. var useCache = options === undefined || options.useCache === undefined || options.useCache === true;
  11021. var isDirty = memoize(function (ele) {
  11022. var _p = ele._private;
  11023. return _p.bbCache == null || _p.styleDirty || _p.bbCachePosKey !== getBoundingBoxPosKey(ele);
  11024. }, function (ele) {
  11025. return ele.id();
  11026. });
  11027. // the main usecase is ele.boundingBox() for a single element with no/def options
  11028. // specified s.t. the cache is used, so check for this case to make it faster by
  11029. // avoiding the overhead of the rest of the function
  11030. if (useCache && this.length === 1 && !isDirty(this[0])) {
  11031. if (options === undefined) {
  11032. options = defBbOpts;
  11033. } else {
  11034. options = filledBbOpts(options);
  11035. }
  11036. bounds = cachedBoundingBoxImpl(this[0], options);
  11037. } else {
  11038. bounds = makeBoundingBox();
  11039. options = options || defBbOpts;
  11040. var opts = filledBbOpts(options);
  11041. var eles = this;
  11042. var cy = eles.cy();
  11043. var styleEnabled = cy.styleEnabled();
  11044. // cache the isDirty state for all eles, edges first since they depend on node state
  11045. this.edges().forEach(isDirty);
  11046. this.nodes().forEach(isDirty);
  11047. if (styleEnabled) {
  11048. this.recalculateRenderedStyle(useCache);
  11049. }
  11050. this.updateCompoundBounds(!useCache);
  11051. for (var i = 0; i < eles.length; i++) {
  11052. var ele = eles[i];
  11053. if (isDirty(ele)) {
  11054. ele.dirtyBoundingBoxCache();
  11055. }
  11056. updateBoundsFromBox(bounds, cachedBoundingBoxImpl(ele, opts));
  11057. }
  11058. }
  11059. bounds.x1 = noninf(bounds.x1);
  11060. bounds.y1 = noninf(bounds.y1);
  11061. bounds.x2 = noninf(bounds.x2);
  11062. bounds.y2 = noninf(bounds.y2);
  11063. bounds.w = noninf(bounds.x2 - bounds.x1);
  11064. bounds.h = noninf(bounds.y2 - bounds.y1);
  11065. return bounds;
  11066. };
  11067. elesfn$b.dirtyBoundingBoxCache = function () {
  11068. for (var i = 0; i < this.length; i++) {
  11069. var _p = this[i]._private;
  11070. _p.bbCache = null;
  11071. _p.bbCachePosKey = null;
  11072. _p.bodyBounds = null;
  11073. _p.overlayBounds = null;
  11074. _p.labelBounds.all = null;
  11075. _p.labelBounds.source = null;
  11076. _p.labelBounds.target = null;
  11077. _p.labelBounds.main = null;
  11078. _p.labelBounds.sourceRot = null;
  11079. _p.labelBounds.targetRot = null;
  11080. _p.labelBounds.mainRot = null;
  11081. _p.arrowBounds.source = null;
  11082. _p.arrowBounds.target = null;
  11083. _p.arrowBounds['mid-source'] = null;
  11084. _p.arrowBounds['mid-target'] = null;
  11085. }
  11086. this.emitAndNotify('bounds');
  11087. return this;
  11088. };
  11089. // private helper to get bounding box for custom node positions
  11090. // - good for perf in certain cases but currently requires dirtying the rendered style
  11091. // - would be better to not modify the nodes but the nodes are read directly everywhere in the renderer...
  11092. // - try to use for only things like discrete layouts where the node position would change anyway
  11093. elesfn$b.boundingBoxAt = function (fn) {
  11094. var nodes = this.nodes();
  11095. var cy = this.cy();
  11096. var hasCompoundNodes = cy.hasCompoundNodes();
  11097. var parents = cy.collection();
  11098. if (hasCompoundNodes) {
  11099. parents = nodes.filter(function (node) {
  11100. return node.isParent();
  11101. });
  11102. nodes = nodes.not(parents);
  11103. }
  11104. if (plainObject(fn)) {
  11105. var obj = fn;
  11106. fn = function fn() {
  11107. return obj;
  11108. };
  11109. }
  11110. var storeOldPos = function storeOldPos(node, i) {
  11111. return node._private.bbAtOldPos = fn(node, i);
  11112. };
  11113. var getOldPos = function getOldPos(node) {
  11114. return node._private.bbAtOldPos;
  11115. };
  11116. cy.startBatch();
  11117. nodes.forEach(storeOldPos).silentPositions(fn);
  11118. if (hasCompoundNodes) {
  11119. parents.dirtyCompoundBoundsCache();
  11120. parents.dirtyBoundingBoxCache();
  11121. parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  11122. }
  11123. var bb = copyBoundingBox(this.boundingBox({
  11124. useCache: false
  11125. }));
  11126. nodes.silentPositions(getOldPos);
  11127. if (hasCompoundNodes) {
  11128. parents.dirtyCompoundBoundsCache();
  11129. parents.dirtyBoundingBoxCache();
  11130. parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  11131. }
  11132. cy.endBatch();
  11133. return bb;
  11134. };
  11135. fn$3.boundingbox = fn$3.bb = fn$3.boundingBox;
  11136. fn$3.renderedBoundingbox = fn$3.renderedBoundingBox;
  11137. var bounds = elesfn$b;
  11138. var fn$2, elesfn$a;
  11139. fn$2 = elesfn$a = {};
  11140. var defineDimFns = function defineDimFns(opts) {
  11141. opts.uppercaseName = capitalize(opts.name);
  11142. opts.autoName = 'auto' + opts.uppercaseName;
  11143. opts.labelName = 'label' + opts.uppercaseName;
  11144. opts.outerName = 'outer' + opts.uppercaseName;
  11145. opts.uppercaseOuterName = capitalize(opts.outerName);
  11146. fn$2[opts.name] = function dimImpl() {
  11147. var ele = this[0];
  11148. var _p = ele._private;
  11149. var cy = _p.cy;
  11150. var styleEnabled = cy._private.styleEnabled;
  11151. if (ele) {
  11152. if (styleEnabled) {
  11153. if (ele.isParent()) {
  11154. ele.updateCompoundBounds();
  11155. return _p[opts.autoName] || 0;
  11156. }
  11157. var d = ele.pstyle(opts.name);
  11158. switch (d.strValue) {
  11159. case 'label':
  11160. ele.recalculateRenderedStyle();
  11161. return _p.rstyle[opts.labelName] || 0;
  11162. default:
  11163. return d.pfValue;
  11164. }
  11165. } else {
  11166. return 1;
  11167. }
  11168. }
  11169. };
  11170. fn$2['outer' + opts.uppercaseName] = function outerDimImpl() {
  11171. var ele = this[0];
  11172. var _p = ele._private;
  11173. var cy = _p.cy;
  11174. var styleEnabled = cy._private.styleEnabled;
  11175. if (ele) {
  11176. if (styleEnabled) {
  11177. var dim = ele[opts.name]();
  11178. var borderPos = ele.pstyle('border-position').value;
  11179. var border;
  11180. if (borderPos === 'center') {
  11181. border = ele.pstyle('border-width').pfValue; // n.b. 1/2 each side
  11182. } else if (borderPos === 'outside') {
  11183. border = 2 * ele.pstyle('border-width').pfValue;
  11184. } else {
  11185. // 'inside'
  11186. border = 0;
  11187. }
  11188. var padding = 2 * ele.padding();
  11189. return dim + border + padding;
  11190. } else {
  11191. return 1;
  11192. }
  11193. }
  11194. };
  11195. fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {
  11196. var ele = this[0];
  11197. if (ele) {
  11198. var d = ele[opts.name]();
  11199. return d * this.cy().zoom();
  11200. }
  11201. };
  11202. fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {
  11203. var ele = this[0];
  11204. if (ele) {
  11205. var od = ele[opts.outerName]();
  11206. return od * this.cy().zoom();
  11207. }
  11208. };
  11209. };
  11210. defineDimFns({
  11211. name: 'width'
  11212. });
  11213. defineDimFns({
  11214. name: 'height'
  11215. });
  11216. elesfn$a.padding = function () {
  11217. var ele = this[0];
  11218. var _p = ele._private;
  11219. if (ele.isParent()) {
  11220. ele.updateCompoundBounds();
  11221. if (_p.autoPadding !== undefined) {
  11222. return _p.autoPadding;
  11223. } else {
  11224. return ele.pstyle('padding').pfValue;
  11225. }
  11226. } else {
  11227. return ele.pstyle('padding').pfValue;
  11228. }
  11229. };
  11230. elesfn$a.paddedHeight = function () {
  11231. var ele = this[0];
  11232. return ele.height() + 2 * ele.padding();
  11233. };
  11234. elesfn$a.paddedWidth = function () {
  11235. var ele = this[0];
  11236. return ele.width() + 2 * ele.padding();
  11237. };
  11238. var widthHeight = elesfn$a;
  11239. var ifEdge = function ifEdge(ele, getValue) {
  11240. if (ele.isEdge() && ele.takesUpSpace()) {
  11241. return getValue(ele);
  11242. }
  11243. };
  11244. var ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {
  11245. if (ele.isEdge() && ele.takesUpSpace()) {
  11246. var cy = ele.cy();
  11247. return modelToRenderedPosition$1(getPoint(ele), cy.zoom(), cy.pan());
  11248. }
  11249. };
  11250. var ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {
  11251. if (ele.isEdge() && ele.takesUpSpace()) {
  11252. var cy = ele.cy();
  11253. var pan = cy.pan();
  11254. var zoom = cy.zoom();
  11255. return getPoints(ele).map(function (p) {
  11256. return modelToRenderedPosition$1(p, zoom, pan);
  11257. });
  11258. }
  11259. };
  11260. var controlPoints = function controlPoints(ele) {
  11261. return ele.renderer().getControlPoints(ele);
  11262. };
  11263. var segmentPoints = function segmentPoints(ele) {
  11264. return ele.renderer().getSegmentPoints(ele);
  11265. };
  11266. var sourceEndpoint = function sourceEndpoint(ele) {
  11267. return ele.renderer().getSourceEndpoint(ele);
  11268. };
  11269. var targetEndpoint = function targetEndpoint(ele) {
  11270. return ele.renderer().getTargetEndpoint(ele);
  11271. };
  11272. var midpoint = function midpoint(ele) {
  11273. return ele.renderer().getEdgeMidpoint(ele);
  11274. };
  11275. var pts = {
  11276. controlPoints: {
  11277. get: controlPoints,
  11278. mult: true
  11279. },
  11280. segmentPoints: {
  11281. get: segmentPoints,
  11282. mult: true
  11283. },
  11284. sourceEndpoint: {
  11285. get: sourceEndpoint
  11286. },
  11287. targetEndpoint: {
  11288. get: targetEndpoint
  11289. },
  11290. midpoint: {
  11291. get: midpoint
  11292. }
  11293. };
  11294. var renderedName = function renderedName(name) {
  11295. return 'rendered' + name[0].toUpperCase() + name.substr(1);
  11296. };
  11297. var edgePoints = Object.keys(pts).reduce(function (obj, name) {
  11298. var spec = pts[name];
  11299. var rName = renderedName(name);
  11300. obj[name] = function () {
  11301. return ifEdge(this, spec.get);
  11302. };
  11303. if (spec.mult) {
  11304. obj[rName] = function () {
  11305. return ifEdgeRenderedPositions(this, spec.get);
  11306. };
  11307. } else {
  11308. obj[rName] = function () {
  11309. return ifEdgeRenderedPosition(this, spec.get);
  11310. };
  11311. }
  11312. return obj;
  11313. }, {});
  11314. var dimensions = extend({}, position, bounds, widthHeight, edgePoints);
  11315. /*!
  11316. Event object based on jQuery events, MIT license
  11317. https://jquery.org/license/
  11318. https://tldrlegal.com/license/mit-license
  11319. https://github.com/jquery/jquery/blob/master/src/event.js
  11320. */
  11321. var Event = function Event(src, props) {
  11322. this.recycle(src, props);
  11323. };
  11324. function returnFalse() {
  11325. return false;
  11326. }
  11327. function returnTrue() {
  11328. return true;
  11329. }
  11330. // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  11331. Event.prototype = {
  11332. instanceString: function instanceString() {
  11333. return 'event';
  11334. },
  11335. recycle: function recycle(src, props) {
  11336. this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;
  11337. if (src != null && src.preventDefault) {
  11338. // Browser Event object
  11339. this.type = src.type;
  11340. // Events bubbling up the document may have been marked as prevented
  11341. // by a handler lower down the tree; reflect the correct value.
  11342. this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse;
  11343. } else if (src != null && src.type) {
  11344. // Plain object containing all event details
  11345. props = src;
  11346. } else {
  11347. // Event string
  11348. this.type = src;
  11349. }
  11350. // Put explicitly provided properties onto the event object
  11351. if (props != null) {
  11352. // more efficient to manually copy fields we use
  11353. this.originalEvent = props.originalEvent;
  11354. this.type = props.type != null ? props.type : this.type;
  11355. this.cy = props.cy;
  11356. this.target = props.target;
  11357. this.position = props.position;
  11358. this.renderedPosition = props.renderedPosition;
  11359. this.namespace = props.namespace;
  11360. this.layout = props.layout;
  11361. }
  11362. if (this.cy != null && this.position != null && this.renderedPosition == null) {
  11363. // create a rendered position based on the passed position
  11364. var pos = this.position;
  11365. var zoom = this.cy.zoom();
  11366. var pan = this.cy.pan();
  11367. this.renderedPosition = {
  11368. x: pos.x * zoom + pan.x,
  11369. y: pos.y * zoom + pan.y
  11370. };
  11371. }
  11372. // Create a timestamp if incoming event doesn't have one
  11373. this.timeStamp = src && src.timeStamp || Date.now();
  11374. },
  11375. preventDefault: function preventDefault() {
  11376. this.isDefaultPrevented = returnTrue;
  11377. var e = this.originalEvent;
  11378. if (!e) {
  11379. return;
  11380. }
  11381. // if preventDefault exists run it on the original event
  11382. if (e.preventDefault) {
  11383. e.preventDefault();
  11384. }
  11385. },
  11386. stopPropagation: function stopPropagation() {
  11387. this.isPropagationStopped = returnTrue;
  11388. var e = this.originalEvent;
  11389. if (!e) {
  11390. return;
  11391. }
  11392. // if stopPropagation exists run it on the original event
  11393. if (e.stopPropagation) {
  11394. e.stopPropagation();
  11395. }
  11396. },
  11397. stopImmediatePropagation: function stopImmediatePropagation() {
  11398. this.isImmediatePropagationStopped = returnTrue;
  11399. this.stopPropagation();
  11400. },
  11401. isDefaultPrevented: returnFalse,
  11402. isPropagationStopped: returnFalse,
  11403. isImmediatePropagationStopped: returnFalse
  11404. };
  11405. var eventRegex = /^([^.]+)(\.(?:[^.]+))?$/; // regex for matching event strings (e.g. "click.namespace")
  11406. var universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally
  11407. var defaults$8 = {
  11408. qualifierCompare: function qualifierCompare(q1, q2) {
  11409. return q1 === q2;
  11410. },
  11411. eventMatches: function eventMatches(/*context, listener, eventObj*/
  11412. ) {
  11413. return true;
  11414. },
  11415. addEventFields: function addEventFields(/*context, evt*/
  11416. ) {},
  11417. callbackContext: function callbackContext(context /*, listener, eventObj*/) {
  11418. return context;
  11419. },
  11420. beforeEmit: function beforeEmit(/* context, listener, eventObj */
  11421. ) {},
  11422. afterEmit: function afterEmit(/* context, listener, eventObj */
  11423. ) {},
  11424. bubble: function bubble(/*context*/
  11425. ) {
  11426. return false;
  11427. },
  11428. parent: function parent(/*context*/
  11429. ) {
  11430. return null;
  11431. },
  11432. context: null
  11433. };
  11434. var defaultsKeys = Object.keys(defaults$8);
  11435. var emptyOpts = {};
  11436. function Emitter() {
  11437. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;
  11438. var context = arguments.length > 1 ? arguments[1] : undefined;
  11439. // micro-optimisation vs Object.assign() -- reduces Element instantiation time
  11440. for (var i = 0; i < defaultsKeys.length; i++) {
  11441. var key = defaultsKeys[i];
  11442. this[key] = opts[key] || defaults$8[key];
  11443. }
  11444. this.context = context || this.context;
  11445. this.listeners = [];
  11446. this.emitting = 0;
  11447. }
  11448. var p = Emitter.prototype;
  11449. var forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {
  11450. if (fn$6(qualifier)) {
  11451. callback = qualifier;
  11452. qualifier = null;
  11453. }
  11454. if (confOverrides) {
  11455. if (conf == null) {
  11456. conf = confOverrides;
  11457. } else {
  11458. conf = extend({}, conf, confOverrides);
  11459. }
  11460. }
  11461. var eventList = array(events) ? events : events.split(/\s+/);
  11462. for (var i = 0; i < eventList.length; i++) {
  11463. var evt = eventList[i];
  11464. if (emptyString(evt)) {
  11465. continue;
  11466. }
  11467. var match = evt.match(eventRegex); // type[.namespace]
  11468. if (match) {
  11469. var type = match[1];
  11470. var namespace = match[2] ? match[2] : null;
  11471. var ret = handler(self, evt, type, namespace, qualifier, callback, conf);
  11472. if (ret === false) {
  11473. break;
  11474. } // allow exiting early
  11475. }
  11476. }
  11477. };
  11478. var makeEventObj = function makeEventObj(self, obj) {
  11479. self.addEventFields(self.context, obj);
  11480. return new Event(obj.type, obj);
  11481. };
  11482. var forEachEventObj = function forEachEventObj(self, handler, events) {
  11483. if (event(events)) {
  11484. handler(self, events);
  11485. return;
  11486. } else if (plainObject(events)) {
  11487. handler(self, makeEventObj(self, events));
  11488. return;
  11489. }
  11490. var eventList = array(events) ? events : events.split(/\s+/);
  11491. for (var i = 0; i < eventList.length; i++) {
  11492. var evt = eventList[i];
  11493. if (emptyString(evt)) {
  11494. continue;
  11495. }
  11496. var match = evt.match(eventRegex); // type[.namespace]
  11497. if (match) {
  11498. var type = match[1];
  11499. var namespace = match[2] ? match[2] : null;
  11500. var eventObj = makeEventObj(self, {
  11501. type: type,
  11502. namespace: namespace,
  11503. target: self.context
  11504. });
  11505. handler(self, eventObj);
  11506. }
  11507. }
  11508. };
  11509. p.on = p.addListener = function (events, qualifier, callback, conf, confOverrides) {
  11510. forEachEvent(this, function (self, event, type, namespace, qualifier, callback, conf) {
  11511. if (fn$6(callback)) {
  11512. self.listeners.push({
  11513. event: event,
  11514. // full event string
  11515. callback: callback,
  11516. // callback to run
  11517. type: type,
  11518. // the event type (e.g. 'click')
  11519. namespace: namespace,
  11520. // the event namespace (e.g. ".foo")
  11521. qualifier: qualifier,
  11522. // a restriction on whether to match this emitter
  11523. conf: conf // additional configuration
  11524. });
  11525. }
  11526. }, events, qualifier, callback, conf, confOverrides);
  11527. return this;
  11528. };
  11529. p.one = function (events, qualifier, callback, conf) {
  11530. return this.on(events, qualifier, callback, conf, {
  11531. one: true
  11532. });
  11533. };
  11534. p.removeListener = p.off = function (events, qualifier, callback, conf) {
  11535. var _this = this;
  11536. if (this.emitting !== 0) {
  11537. this.listeners = copyArray(this.listeners);
  11538. }
  11539. var listeners = this.listeners;
  11540. var _loop = function _loop(i) {
  11541. var listener = listeners[i];
  11542. forEachEvent(_this, function (self, event, type, namespace, qualifier, callback /*, conf*/) {
  11543. if ((listener.type === type || events === '*') && (!namespace && listener.namespace !== '.*' || listener.namespace === namespace) && (!qualifier || self.qualifierCompare(listener.qualifier, qualifier)) && (!callback || listener.callback === callback)) {
  11544. listeners.splice(i, 1);
  11545. return false;
  11546. }
  11547. }, events, qualifier, callback, conf);
  11548. };
  11549. for (var i = listeners.length - 1; i >= 0; i--) {
  11550. _loop(i);
  11551. }
  11552. return this;
  11553. };
  11554. p.removeAllListeners = function () {
  11555. return this.removeListener('*');
  11556. };
  11557. p.emit = p.trigger = function (events, extraParams, manualCallback) {
  11558. var listeners = this.listeners;
  11559. var numListenersBeforeEmit = listeners.length;
  11560. this.emitting++;
  11561. if (!array(extraParams)) {
  11562. extraParams = [extraParams];
  11563. }
  11564. forEachEventObj(this, function (self, eventObj) {
  11565. if (manualCallback != null) {
  11566. listeners = [{
  11567. event: eventObj.event,
  11568. type: eventObj.type,
  11569. namespace: eventObj.namespace,
  11570. callback: manualCallback
  11571. }];
  11572. numListenersBeforeEmit = listeners.length;
  11573. }
  11574. var _loop2 = function _loop2() {
  11575. var listener = listeners[i];
  11576. if (listener.type === eventObj.type && (!listener.namespace || listener.namespace === eventObj.namespace || listener.namespace === universalNamespace) && self.eventMatches(self.context, listener, eventObj)) {
  11577. var args = [eventObj];
  11578. if (extraParams != null) {
  11579. push(args, extraParams);
  11580. }
  11581. self.beforeEmit(self.context, listener, eventObj);
  11582. if (listener.conf && listener.conf.one) {
  11583. self.listeners = self.listeners.filter(function (l) {
  11584. return l !== listener;
  11585. });
  11586. }
  11587. var context = self.callbackContext(self.context, listener, eventObj);
  11588. var ret = listener.callback.apply(context, args);
  11589. self.afterEmit(self.context, listener, eventObj);
  11590. if (ret === false) {
  11591. eventObj.stopPropagation();
  11592. eventObj.preventDefault();
  11593. }
  11594. } // if listener matches
  11595. };
  11596. for (var i = 0; i < numListenersBeforeEmit; i++) {
  11597. _loop2();
  11598. } // for listener
  11599. if (self.bubble(self.context) && !eventObj.isPropagationStopped()) {
  11600. self.parent(self.context).emit(eventObj, extraParams);
  11601. }
  11602. }, events);
  11603. this.emitting--;
  11604. return this;
  11605. };
  11606. var emitterOptions$1 = {
  11607. qualifierCompare: function qualifierCompare(selector1, selector2) {
  11608. if (selector1 == null || selector2 == null) {
  11609. return selector1 == null && selector2 == null;
  11610. } else {
  11611. return selector1.sameText(selector2);
  11612. }
  11613. },
  11614. eventMatches: function eventMatches(ele, listener, eventObj) {
  11615. var selector = listener.qualifier;
  11616. if (selector != null) {
  11617. return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
  11618. }
  11619. return true;
  11620. },
  11621. addEventFields: function addEventFields(ele, evt) {
  11622. evt.cy = ele.cy();
  11623. evt.target = ele;
  11624. },
  11625. callbackContext: function callbackContext(ele, listener, eventObj) {
  11626. return listener.qualifier != null ? eventObj.target : ele;
  11627. },
  11628. beforeEmit: function beforeEmit(context, listener /*, eventObj*/) {
  11629. if (listener.conf && listener.conf.once) {
  11630. listener.conf.onceCollection.removeListener(listener.event, listener.qualifier, listener.callback);
  11631. }
  11632. },
  11633. bubble: function bubble() {
  11634. return true;
  11635. },
  11636. parent: function parent(ele) {
  11637. return ele.isChild() ? ele.parent() : ele.cy();
  11638. }
  11639. };
  11640. var argSelector$1 = function argSelector(arg) {
  11641. if (string(arg)) {
  11642. return new Selector(arg);
  11643. } else {
  11644. return arg;
  11645. }
  11646. };
  11647. var elesfn$9 = {
  11648. createEmitter: function createEmitter() {
  11649. for (var i = 0; i < this.length; i++) {
  11650. var ele = this[i];
  11651. var _p = ele._private;
  11652. if (!_p.emitter) {
  11653. _p.emitter = new Emitter(emitterOptions$1, ele);
  11654. }
  11655. }
  11656. return this;
  11657. },
  11658. emitter: function emitter() {
  11659. return this._private.emitter;
  11660. },
  11661. on: function on(events, selector, callback) {
  11662. var argSel = argSelector$1(selector);
  11663. for (var i = 0; i < this.length; i++) {
  11664. var ele = this[i];
  11665. ele.emitter().on(events, argSel, callback);
  11666. }
  11667. return this;
  11668. },
  11669. removeListener: function removeListener(events, selector, callback) {
  11670. var argSel = argSelector$1(selector);
  11671. for (var i = 0; i < this.length; i++) {
  11672. var ele = this[i];
  11673. ele.emitter().removeListener(events, argSel, callback);
  11674. }
  11675. return this;
  11676. },
  11677. removeAllListeners: function removeAllListeners() {
  11678. for (var i = 0; i < this.length; i++) {
  11679. var ele = this[i];
  11680. ele.emitter().removeAllListeners();
  11681. }
  11682. return this;
  11683. },
  11684. one: function one(events, selector, callback) {
  11685. var argSel = argSelector$1(selector);
  11686. for (var i = 0; i < this.length; i++) {
  11687. var ele = this[i];
  11688. ele.emitter().one(events, argSel, callback);
  11689. }
  11690. return this;
  11691. },
  11692. once: function once(events, selector, callback) {
  11693. var argSel = argSelector$1(selector);
  11694. for (var i = 0; i < this.length; i++) {
  11695. var ele = this[i];
  11696. ele.emitter().on(events, argSel, callback, {
  11697. once: true,
  11698. onceCollection: this
  11699. });
  11700. }
  11701. },
  11702. emit: function emit(events, extraParams) {
  11703. for (var i = 0; i < this.length; i++) {
  11704. var ele = this[i];
  11705. ele.emitter().emit(events, extraParams);
  11706. }
  11707. return this;
  11708. },
  11709. emitAndNotify: function emitAndNotify(event, extraParams) {
  11710. // for internal use only
  11711. if (this.length === 0) {
  11712. return;
  11713. } // empty collections don't need to notify anything
  11714. // notify renderer
  11715. this.cy().notify(event, this);
  11716. this.emit(event, extraParams);
  11717. return this;
  11718. }
  11719. };
  11720. define.eventAliasesOn(elesfn$9);
  11721. var elesfn$8 = {
  11722. nodes: function nodes(selector) {
  11723. return this.filter(function (ele) {
  11724. return ele.isNode();
  11725. }).filter(selector);
  11726. },
  11727. edges: function edges(selector) {
  11728. return this.filter(function (ele) {
  11729. return ele.isEdge();
  11730. }).filter(selector);
  11731. },
  11732. // internal helper to get nodes and edges as separate collections with single iteration over elements
  11733. byGroup: function byGroup() {
  11734. var nodes = this.spawn();
  11735. var edges = this.spawn();
  11736. for (var i = 0; i < this.length; i++) {
  11737. var ele = this[i];
  11738. if (ele.isNode()) {
  11739. nodes.push(ele);
  11740. } else {
  11741. edges.push(ele);
  11742. }
  11743. }
  11744. return {
  11745. nodes: nodes,
  11746. edges: edges
  11747. };
  11748. },
  11749. filter: function filter(_filter, thisArg) {
  11750. if (_filter === undefined) {
  11751. // check this first b/c it's the most common/performant case
  11752. return this;
  11753. } else if (string(_filter) || elementOrCollection(_filter)) {
  11754. return new Selector(_filter).filter(this);
  11755. } else if (fn$6(_filter)) {
  11756. var filterEles = this.spawn();
  11757. var eles = this;
  11758. for (var i = 0; i < eles.length; i++) {
  11759. var ele = eles[i];
  11760. var include = thisArg ? _filter.apply(thisArg, [ele, i, eles]) : _filter(ele, i, eles);
  11761. if (include) {
  11762. filterEles.push(ele);
  11763. }
  11764. }
  11765. return filterEles;
  11766. }
  11767. return this.spawn(); // if not handled by above, give 'em an empty collection
  11768. },
  11769. not: function not(toRemove) {
  11770. if (!toRemove) {
  11771. return this;
  11772. } else {
  11773. if (string(toRemove)) {
  11774. toRemove = this.filter(toRemove);
  11775. }
  11776. var elements = this.spawn();
  11777. for (var i = 0; i < this.length; i++) {
  11778. var element = this[i];
  11779. var remove = toRemove.has(element);
  11780. if (!remove) {
  11781. elements.push(element);
  11782. }
  11783. }
  11784. return elements;
  11785. }
  11786. },
  11787. absoluteComplement: function absoluteComplement() {
  11788. var cy = this.cy();
  11789. return cy.mutableElements().not(this);
  11790. },
  11791. intersect: function intersect(other) {
  11792. // if a selector is specified, then filter by it instead
  11793. if (string(other)) {
  11794. var selector = other;
  11795. return this.filter(selector);
  11796. }
  11797. var elements = this.spawn();
  11798. var col1 = this;
  11799. var col2 = other;
  11800. var col1Smaller = this.length < other.length;
  11801. var colS = col1Smaller ? col1 : col2;
  11802. var colL = col1Smaller ? col2 : col1;
  11803. for (var i = 0; i < colS.length; i++) {
  11804. var ele = colS[i];
  11805. if (colL.has(ele)) {
  11806. elements.push(ele);
  11807. }
  11808. }
  11809. return elements;
  11810. },
  11811. xor: function xor(other) {
  11812. var cy = this._private.cy;
  11813. if (string(other)) {
  11814. other = cy.$(other);
  11815. }
  11816. var elements = this.spawn();
  11817. var col1 = this;
  11818. var col2 = other;
  11819. var add = function add(col, other) {
  11820. for (var i = 0; i < col.length; i++) {
  11821. var ele = col[i];
  11822. var id = ele._private.data.id;
  11823. var inOther = other.hasElementWithId(id);
  11824. if (!inOther) {
  11825. elements.push(ele);
  11826. }
  11827. }
  11828. };
  11829. add(col1, col2);
  11830. add(col2, col1);
  11831. return elements;
  11832. },
  11833. diff: function diff(other) {
  11834. var cy = this._private.cy;
  11835. if (string(other)) {
  11836. other = cy.$(other);
  11837. }
  11838. var left = this.spawn();
  11839. var right = this.spawn();
  11840. var both = this.spawn();
  11841. var col1 = this;
  11842. var col2 = other;
  11843. var add = function add(col, other, retEles) {
  11844. for (var i = 0; i < col.length; i++) {
  11845. var ele = col[i];
  11846. var id = ele._private.data.id;
  11847. var inOther = other.hasElementWithId(id);
  11848. if (inOther) {
  11849. both.merge(ele);
  11850. } else {
  11851. retEles.push(ele);
  11852. }
  11853. }
  11854. };
  11855. add(col1, col2, left);
  11856. add(col2, col1, right);
  11857. return {
  11858. left: left,
  11859. right: right,
  11860. both: both
  11861. };
  11862. },
  11863. add: function add(toAdd) {
  11864. var cy = this._private.cy;
  11865. if (!toAdd) {
  11866. return this;
  11867. }
  11868. if (string(toAdd)) {
  11869. var selector = toAdd;
  11870. toAdd = cy.mutableElements().filter(selector);
  11871. }
  11872. var elements = this.spawnSelf();
  11873. for (var i = 0; i < toAdd.length; i++) {
  11874. var ele = toAdd[i];
  11875. var add = !this.has(ele);
  11876. if (add) {
  11877. elements.push(ele);
  11878. }
  11879. }
  11880. return elements;
  11881. },
  11882. // in place merge on calling collection
  11883. merge: function merge(toAdd) {
  11884. var _p = this._private;
  11885. var cy = _p.cy;
  11886. if (!toAdd) {
  11887. return this;
  11888. }
  11889. if (toAdd && string(toAdd)) {
  11890. var selector = toAdd;
  11891. toAdd = cy.mutableElements().filter(selector);
  11892. }
  11893. var map = _p.map;
  11894. for (var i = 0; i < toAdd.length; i++) {
  11895. var toAddEle = toAdd[i];
  11896. var id = toAddEle._private.data.id;
  11897. var add = !map.has(id);
  11898. if (add) {
  11899. var index = this.length++;
  11900. this[index] = toAddEle;
  11901. map.set(id, {
  11902. ele: toAddEle,
  11903. index: index
  11904. });
  11905. }
  11906. }
  11907. return this; // chaining
  11908. },
  11909. unmergeAt: function unmergeAt(i) {
  11910. var ele = this[i];
  11911. var id = ele.id();
  11912. var _p = this._private;
  11913. var map = _p.map;
  11914. // remove ele
  11915. this[i] = undefined;
  11916. map["delete"](id);
  11917. var unmergedLastEle = i === this.length - 1;
  11918. // replace empty spot with last ele in collection
  11919. if (this.length > 1 && !unmergedLastEle) {
  11920. var lastEleI = this.length - 1;
  11921. var lastEle = this[lastEleI];
  11922. var lastEleId = lastEle._private.data.id;
  11923. this[lastEleI] = undefined;
  11924. this[i] = lastEle;
  11925. map.set(lastEleId, {
  11926. ele: lastEle,
  11927. index: i
  11928. });
  11929. }
  11930. // the collection is now 1 ele smaller
  11931. this.length--;
  11932. return this;
  11933. },
  11934. // remove single ele in place in calling collection
  11935. unmergeOne: function unmergeOne(ele) {
  11936. ele = ele[0];
  11937. var _p = this._private;
  11938. var id = ele._private.data.id;
  11939. var map = _p.map;
  11940. var entry = map.get(id);
  11941. if (!entry) {
  11942. return this; // no need to remove
  11943. }
  11944. var i = entry.index;
  11945. this.unmergeAt(i);
  11946. return this;
  11947. },
  11948. // remove eles in place on calling collection
  11949. unmerge: function unmerge(toRemove) {
  11950. var cy = this._private.cy;
  11951. if (!toRemove) {
  11952. return this;
  11953. }
  11954. if (toRemove && string(toRemove)) {
  11955. var selector = toRemove;
  11956. toRemove = cy.mutableElements().filter(selector);
  11957. }
  11958. for (var i = 0; i < toRemove.length; i++) {
  11959. this.unmergeOne(toRemove[i]);
  11960. }
  11961. return this; // chaining
  11962. },
  11963. unmergeBy: function unmergeBy(toRmFn) {
  11964. for (var i = this.length - 1; i >= 0; i--) {
  11965. var ele = this[i];
  11966. if (toRmFn(ele)) {
  11967. this.unmergeAt(i);
  11968. }
  11969. }
  11970. return this;
  11971. },
  11972. map: function map(mapFn, thisArg) {
  11973. var arr = [];
  11974. var eles = this;
  11975. for (var i = 0; i < eles.length; i++) {
  11976. var ele = eles[i];
  11977. var ret = thisArg ? mapFn.apply(thisArg, [ele, i, eles]) : mapFn(ele, i, eles);
  11978. arr.push(ret);
  11979. }
  11980. return arr;
  11981. },
  11982. reduce: function reduce(fn, initialValue) {
  11983. var val = initialValue;
  11984. var eles = this;
  11985. for (var i = 0; i < eles.length; i++) {
  11986. val = fn(val, eles[i], i, eles);
  11987. }
  11988. return val;
  11989. },
  11990. max: function max(valFn, thisArg) {
  11991. var max = -Infinity;
  11992. var maxEle;
  11993. var eles = this;
  11994. for (var i = 0; i < eles.length; i++) {
  11995. var ele = eles[i];
  11996. var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
  11997. if (val > max) {
  11998. max = val;
  11999. maxEle = ele;
  12000. }
  12001. }
  12002. return {
  12003. value: max,
  12004. ele: maxEle
  12005. };
  12006. },
  12007. min: function min(valFn, thisArg) {
  12008. var min = Infinity;
  12009. var minEle;
  12010. var eles = this;
  12011. for (var i = 0; i < eles.length; i++) {
  12012. var ele = eles[i];
  12013. var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
  12014. if (val < min) {
  12015. min = val;
  12016. minEle = ele;
  12017. }
  12018. }
  12019. return {
  12020. value: min,
  12021. ele: minEle
  12022. };
  12023. }
  12024. };
  12025. // aliases
  12026. var fn$1 = elesfn$8;
  12027. fn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;
  12028. fn$1['\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;
  12029. fn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;
  12030. fn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;
  12031. fn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;
  12032. fn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;
  12033. var elesfn$7 = {
  12034. isNode: function isNode() {
  12035. return this.group() === 'nodes';
  12036. },
  12037. isEdge: function isEdge() {
  12038. return this.group() === 'edges';
  12039. },
  12040. isLoop: function isLoop() {
  12041. return this.isEdge() && this.source()[0] === this.target()[0];
  12042. },
  12043. isSimple: function isSimple() {
  12044. return this.isEdge() && this.source()[0] !== this.target()[0];
  12045. },
  12046. group: function group() {
  12047. var ele = this[0];
  12048. if (ele) {
  12049. return ele._private.group;
  12050. }
  12051. }
  12052. };
  12053. /**
  12054. * Elements are drawn in a specific order based on compound depth (low to high), the element type (nodes above edges),
  12055. * and z-index (low to high). These styles affect how this applies:
  12056. *
  12057. * z-compound-depth: May be `bottom | orphan | auto | top`. The first drawn is `bottom`, then `orphan` which is the
  12058. * same depth as the root of the compound graph, followed by the default value `auto` which draws in order from
  12059. * root to leaves of the compound graph. The last drawn is `top`.
  12060. * z-index-compare: May be `auto | manual`. The default value is `auto` which always draws edges under nodes.
  12061. * `manual` ignores this convention and draws based on the `z-index` value setting.
  12062. * z-index: An integer value that affects the relative draw order of elements. In general, an element with a higher
  12063. * `z-index` will be drawn on top of an element with a lower `z-index`.
  12064. */
  12065. var zIndexSort = function zIndexSort(a, b) {
  12066. var cy = a.cy();
  12067. var hasCompoundNodes = cy.hasCompoundNodes();
  12068. function getDepth(ele) {
  12069. var style = ele.pstyle('z-compound-depth');
  12070. if (style.value === 'auto') {
  12071. return hasCompoundNodes ? ele.zDepth() : 0;
  12072. } else if (style.value === 'bottom') {
  12073. return -1;
  12074. } else if (style.value === 'top') {
  12075. return MAX_INT$1;
  12076. }
  12077. // 'orphan'
  12078. return 0;
  12079. }
  12080. var depthDiff = getDepth(a) - getDepth(b);
  12081. if (depthDiff !== 0) {
  12082. return depthDiff;
  12083. }
  12084. function getEleDepth(ele) {
  12085. var style = ele.pstyle('z-index-compare');
  12086. if (style.value === 'auto') {
  12087. return ele.isNode() ? 1 : 0;
  12088. }
  12089. // 'manual'
  12090. return 0;
  12091. }
  12092. var eleDiff = getEleDepth(a) - getEleDepth(b);
  12093. if (eleDiff !== 0) {
  12094. return eleDiff;
  12095. }
  12096. var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;
  12097. if (zDiff !== 0) {
  12098. return zDiff;
  12099. }
  12100. // compare indices in the core (order added to graph w/ last on top)
  12101. return a.poolIndex() - b.poolIndex();
  12102. };
  12103. var elesfn$6 = {
  12104. forEach: function forEach(fn, thisArg) {
  12105. if (fn$6(fn)) {
  12106. var N = this.length;
  12107. for (var i = 0; i < N; i++) {
  12108. var ele = this[i];
  12109. var ret = thisArg ? fn.apply(thisArg, [ele, i, this]) : fn(ele, i, this);
  12110. if (ret === false) {
  12111. break;
  12112. } // exit each early on return false
  12113. }
  12114. }
  12115. return this;
  12116. },
  12117. toArray: function toArray() {
  12118. var array = [];
  12119. for (var i = 0; i < this.length; i++) {
  12120. array.push(this[i]);
  12121. }
  12122. return array;
  12123. },
  12124. slice: function slice(start, end) {
  12125. var array = [];
  12126. var thisSize = this.length;
  12127. if (end == null) {
  12128. end = thisSize;
  12129. }
  12130. if (start == null) {
  12131. start = 0;
  12132. }
  12133. if (start < 0) {
  12134. start = thisSize + start;
  12135. }
  12136. if (end < 0) {
  12137. end = thisSize + end;
  12138. }
  12139. for (var i = start; i >= 0 && i < end && i < thisSize; i++) {
  12140. array.push(this[i]);
  12141. }
  12142. return this.spawn(array);
  12143. },
  12144. size: function size() {
  12145. return this.length;
  12146. },
  12147. eq: function eq(i) {
  12148. return this[i] || this.spawn();
  12149. },
  12150. first: function first() {
  12151. return this[0] || this.spawn();
  12152. },
  12153. last: function last() {
  12154. return this[this.length - 1] || this.spawn();
  12155. },
  12156. empty: function empty() {
  12157. return this.length === 0;
  12158. },
  12159. nonempty: function nonempty() {
  12160. return !this.empty();
  12161. },
  12162. sort: function sort(sortFn) {
  12163. if (!fn$6(sortFn)) {
  12164. return this;
  12165. }
  12166. var sorted = this.toArray().sort(sortFn);
  12167. return this.spawn(sorted);
  12168. },
  12169. sortByZIndex: function sortByZIndex() {
  12170. return this.sort(zIndexSort);
  12171. },
  12172. zDepth: function zDepth() {
  12173. var ele = this[0];
  12174. if (!ele) {
  12175. return undefined;
  12176. }
  12177. // let cy = ele.cy();
  12178. var _p = ele._private;
  12179. var group = _p.group;
  12180. if (group === 'nodes') {
  12181. var depth = _p.data.parent ? ele.parents().size() : 0;
  12182. if (!ele.isParent()) {
  12183. return MAX_INT$1 - 1; // childless nodes always on top
  12184. }
  12185. return depth;
  12186. } else {
  12187. var src = _p.source;
  12188. var tgt = _p.target;
  12189. var srcDepth = src.zDepth();
  12190. var tgtDepth = tgt.zDepth();
  12191. return Math.max(srcDepth, tgtDepth, 0); // depth of deepest parent
  12192. }
  12193. }
  12194. };
  12195. elesfn$6.each = elesfn$6.forEach;
  12196. var defineSymbolIterator = function defineSymbolIterator() {
  12197. var typeofUndef = "undefined" ;
  12198. var isIteratorSupported = (typeof Symbol === "undefined" ? "undefined" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef;
  12199. if (isIteratorSupported) {
  12200. elesfn$6[Symbol.iterator] = function () {
  12201. var _this = this;
  12202. var entry = {
  12203. value: undefined,
  12204. done: false
  12205. };
  12206. var i = 0;
  12207. var length = this.length;
  12208. return _defineProperty$1({
  12209. next: function next() {
  12210. if (i < length) {
  12211. entry.value = _this[i++];
  12212. } else {
  12213. entry.value = undefined;
  12214. entry.done = true;
  12215. }
  12216. return entry;
  12217. }
  12218. }, Symbol.iterator, function () {
  12219. return this;
  12220. });
  12221. };
  12222. }
  12223. };
  12224. defineSymbolIterator();
  12225. var getLayoutDimensionOptions = defaults$g({
  12226. nodeDimensionsIncludeLabels: false
  12227. });
  12228. var elesfn$5 = {
  12229. // Calculates and returns node dimensions { x, y } based on options given
  12230. layoutDimensions: function layoutDimensions(options) {
  12231. options = getLayoutDimensionOptions(options);
  12232. var dims;
  12233. if (!this.takesUpSpace()) {
  12234. dims = {
  12235. w: 0,
  12236. h: 0
  12237. };
  12238. } else if (options.nodeDimensionsIncludeLabels) {
  12239. var bbDim = this.boundingBox();
  12240. dims = {
  12241. w: bbDim.w,
  12242. h: bbDim.h
  12243. };
  12244. } else {
  12245. dims = {
  12246. w: this.outerWidth(),
  12247. h: this.outerHeight()
  12248. };
  12249. }
  12250. // sanitise the dimensions for external layouts (avoid division by zero)
  12251. if (dims.w === 0 || dims.h === 0) {
  12252. dims.w = dims.h = 1;
  12253. }
  12254. return dims;
  12255. },
  12256. // using standard layout options, apply position function (w/ or w/o animation)
  12257. layoutPositions: function layoutPositions(layout, options, fn) {
  12258. var nodes = this.nodes().filter(function (n) {
  12259. return !n.isParent();
  12260. });
  12261. var cy = this.cy();
  12262. var layoutEles = options.eles; // nodes & edges
  12263. var getMemoizeKey = function getMemoizeKey(node) {
  12264. return node.id();
  12265. };
  12266. var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function
  12267. layout.emit({
  12268. type: 'layoutstart',
  12269. layout: layout
  12270. });
  12271. layout.animations = [];
  12272. var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) {
  12273. var center = {
  12274. x: nodesBb.x1 + nodesBb.w / 2,
  12275. y: nodesBb.y1 + nodesBb.h / 2
  12276. };
  12277. var spacingVector = {
  12278. // scale from center of bounding box (not necessarily 0,0)
  12279. x: (pos.x - center.x) * spacing,
  12280. y: (pos.y - center.y) * spacing
  12281. };
  12282. return {
  12283. x: center.x + spacingVector.x,
  12284. y: center.y + spacingVector.y
  12285. };
  12286. };
  12287. var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;
  12288. var spacingBb = function spacingBb() {
  12289. if (!useSpacingFactor) {
  12290. return null;
  12291. }
  12292. var bb = makeBoundingBox();
  12293. for (var i = 0; i < nodes.length; i++) {
  12294. var node = nodes[i];
  12295. var pos = fnMem(node, i);
  12296. expandBoundingBoxByPoint(bb, pos.x, pos.y);
  12297. }
  12298. return bb;
  12299. };
  12300. var bb = spacingBb();
  12301. var getFinalPos = memoize(function (node, i) {
  12302. var newPos = fnMem(node, i);
  12303. if (useSpacingFactor) {
  12304. var spacing = Math.abs(options.spacingFactor);
  12305. newPos = calculateSpacing(spacing, bb, newPos);
  12306. }
  12307. if (options.transform != null) {
  12308. newPos = options.transform(node, newPos);
  12309. }
  12310. return newPos;
  12311. }, getMemoizeKey);
  12312. if (options.animate) {
  12313. for (var i = 0; i < nodes.length; i++) {
  12314. var node = nodes[i];
  12315. var newPos = getFinalPos(node, i);
  12316. var animateNode = options.animateFilter == null || options.animateFilter(node, i);
  12317. if (animateNode) {
  12318. var ani = node.animation({
  12319. position: newPos,
  12320. duration: options.animationDuration,
  12321. easing: options.animationEasing
  12322. });
  12323. layout.animations.push(ani);
  12324. } else {
  12325. node.position(newPos);
  12326. }
  12327. }
  12328. if (options.fit) {
  12329. var fitAni = cy.animation({
  12330. fit: {
  12331. boundingBox: layoutEles.boundingBoxAt(getFinalPos),
  12332. padding: options.padding
  12333. },
  12334. duration: options.animationDuration,
  12335. easing: options.animationEasing
  12336. });
  12337. layout.animations.push(fitAni);
  12338. } else if (options.zoom !== undefined && options.pan !== undefined) {
  12339. var zoomPanAni = cy.animation({
  12340. zoom: options.zoom,
  12341. pan: options.pan,
  12342. duration: options.animationDuration,
  12343. easing: options.animationEasing
  12344. });
  12345. layout.animations.push(zoomPanAni);
  12346. }
  12347. layout.animations.forEach(function (ani) {
  12348. return ani.play();
  12349. });
  12350. layout.one('layoutready', options.ready);
  12351. layout.emit({
  12352. type: 'layoutready',
  12353. layout: layout
  12354. });
  12355. Promise$1.all(layout.animations.map(function (ani) {
  12356. return ani.promise();
  12357. })).then(function () {
  12358. layout.one('layoutstop', options.stop);
  12359. layout.emit({
  12360. type: 'layoutstop',
  12361. layout: layout
  12362. });
  12363. });
  12364. } else {
  12365. nodes.positions(getFinalPos);
  12366. if (options.fit) {
  12367. cy.fit(options.eles, options.padding);
  12368. }
  12369. if (options.zoom != null) {
  12370. cy.zoom(options.zoom);
  12371. }
  12372. if (options.pan) {
  12373. cy.pan(options.pan);
  12374. }
  12375. layout.one('layoutready', options.ready);
  12376. layout.emit({
  12377. type: 'layoutready',
  12378. layout: layout
  12379. });
  12380. layout.one('layoutstop', options.stop);
  12381. layout.emit({
  12382. type: 'layoutstop',
  12383. layout: layout
  12384. });
  12385. }
  12386. return this; // chaining
  12387. },
  12388. layout: function layout(options) {
  12389. var cy = this.cy();
  12390. return cy.makeLayout(extend({}, options, {
  12391. eles: this
  12392. }));
  12393. }
  12394. };
  12395. // aliases:
  12396. elesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;
  12397. function styleCache(key, fn, ele) {
  12398. var _p = ele._private;
  12399. var cache = _p.styleCache = _p.styleCache || [];
  12400. var val;
  12401. if ((val = cache[key]) != null) {
  12402. return val;
  12403. } else {
  12404. val = cache[key] = fn(ele);
  12405. return val;
  12406. }
  12407. }
  12408. function cacheStyleFunction(key, fn) {
  12409. key = hashString(key);
  12410. return function cachedStyleFunction(ele) {
  12411. return styleCache(key, fn, ele);
  12412. };
  12413. }
  12414. function cachePrototypeStyleFunction(key, fn) {
  12415. key = hashString(key);
  12416. var selfFn = function selfFn(ele) {
  12417. return fn.call(ele);
  12418. };
  12419. return function cachedPrototypeStyleFunction() {
  12420. var ele = this[0];
  12421. if (ele) {
  12422. return styleCache(key, selfFn, ele);
  12423. }
  12424. };
  12425. }
  12426. var elesfn$4 = {
  12427. recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {
  12428. var cy = this.cy();
  12429. var renderer = cy.renderer();
  12430. var styleEnabled = cy.styleEnabled();
  12431. if (renderer && styleEnabled) {
  12432. renderer.recalculateRenderedStyle(this, useCache);
  12433. }
  12434. return this;
  12435. },
  12436. dirtyStyleCache: function dirtyStyleCache() {
  12437. var cy = this.cy();
  12438. var dirty = function dirty(ele) {
  12439. return ele._private.styleCache = null;
  12440. };
  12441. if (cy.hasCompoundNodes()) {
  12442. var eles;
  12443. eles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
  12444. eles.merge(eles.connectedEdges());
  12445. eles.forEach(dirty);
  12446. } else {
  12447. this.forEach(function (ele) {
  12448. dirty(ele);
  12449. ele.connectedEdges().forEach(dirty);
  12450. });
  12451. }
  12452. return this;
  12453. },
  12454. // fully updates (recalculates) the style for the elements
  12455. updateStyle: function updateStyle(notifyRenderer) {
  12456. var cy = this._private.cy;
  12457. if (!cy.styleEnabled()) {
  12458. return this;
  12459. }
  12460. if (cy.batching()) {
  12461. var bEles = cy._private.batchStyleEles;
  12462. bEles.merge(this);
  12463. return this; // chaining and exit early when batching
  12464. }
  12465. var hasCompounds = cy.hasCompoundNodes();
  12466. var updatedEles = this;
  12467. notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;
  12468. if (hasCompounds) {
  12469. // then add everything up and down for compound selector checks
  12470. updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
  12471. }
  12472. // let changedEles = style.apply( updatedEles );
  12473. var changedEles = updatedEles;
  12474. if (notifyRenderer) {
  12475. changedEles.emitAndNotify('style'); // let renderer know we changed style
  12476. } else {
  12477. changedEles.emit('style'); // just fire the event
  12478. }
  12479. updatedEles.forEach(function (ele) {
  12480. return ele._private.styleDirty = true;
  12481. });
  12482. return this; // chaining
  12483. },
  12484. // private: clears dirty flag and recalculates style
  12485. cleanStyle: function cleanStyle() {
  12486. var cy = this.cy();
  12487. if (!cy.styleEnabled()) {
  12488. return;
  12489. }
  12490. for (var i = 0; i < this.length; i++) {
  12491. var ele = this[i];
  12492. if (ele._private.styleDirty) {
  12493. // n.b. this flag should be set before apply() to avoid potential infinite recursion
  12494. ele._private.styleDirty = false;
  12495. cy.style().apply(ele);
  12496. }
  12497. }
  12498. },
  12499. // get the internal parsed style object for the specified property
  12500. parsedStyle: function parsedStyle(property) {
  12501. var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  12502. var ele = this[0];
  12503. var cy = ele.cy();
  12504. if (!cy.styleEnabled()) {
  12505. return;
  12506. }
  12507. if (ele) {
  12508. // this.cleanStyle();
  12509. // Inline the important part of cleanStyle(), for raw performance
  12510. if (ele._private.styleDirty) {
  12511. // n.b. this flag should be set before apply() to avoid potential infinite recursion
  12512. ele._private.styleDirty = false;
  12513. cy.style().apply(ele);
  12514. }
  12515. var overriddenStyle = ele._private.style[property];
  12516. if (overriddenStyle != null) {
  12517. return overriddenStyle;
  12518. } else if (includeNonDefault) {
  12519. return cy.style().getDefaultProperty(property);
  12520. } else {
  12521. return null;
  12522. }
  12523. }
  12524. },
  12525. numericStyle: function numericStyle(property) {
  12526. var ele = this[0];
  12527. if (!ele.cy().styleEnabled()) {
  12528. return;
  12529. }
  12530. if (ele) {
  12531. var pstyle = ele.pstyle(property);
  12532. return pstyle.pfValue !== undefined ? pstyle.pfValue : pstyle.value;
  12533. }
  12534. },
  12535. numericStyleUnits: function numericStyleUnits(property) {
  12536. var ele = this[0];
  12537. if (!ele.cy().styleEnabled()) {
  12538. return;
  12539. }
  12540. if (ele) {
  12541. return ele.pstyle(property).units;
  12542. }
  12543. },
  12544. // get the specified css property as a rendered value (i.e. on-screen value)
  12545. // or get the whole rendered style if no property specified (NB doesn't allow setting)
  12546. renderedStyle: function renderedStyle(property) {
  12547. var cy = this.cy();
  12548. if (!cy.styleEnabled()) {
  12549. return this;
  12550. }
  12551. var ele = this[0];
  12552. if (ele) {
  12553. return cy.style().getRenderedStyle(ele, property);
  12554. }
  12555. },
  12556. // read the calculated css style of the element or override the style (via a bypass)
  12557. style: function style(name, value) {
  12558. var cy = this.cy();
  12559. if (!cy.styleEnabled()) {
  12560. return this;
  12561. }
  12562. var updateTransitions = false;
  12563. var style = cy.style();
  12564. if (plainObject(name)) {
  12565. // then extend the bypass
  12566. var props = name;
  12567. style.applyBypass(this, props, updateTransitions);
  12568. this.emitAndNotify('style'); // let the renderer know we've updated style
  12569. } else if (string(name)) {
  12570. if (value === undefined) {
  12571. // then get the property from the style
  12572. var ele = this[0];
  12573. if (ele) {
  12574. return style.getStylePropertyValue(ele, name);
  12575. } else {
  12576. // empty collection => can't get any value
  12577. return;
  12578. }
  12579. } else {
  12580. // then set the bypass with the property value
  12581. style.applyBypass(this, name, value, updateTransitions);
  12582. this.emitAndNotify('style'); // let the renderer know we've updated style
  12583. }
  12584. } else if (name === undefined) {
  12585. var _ele = this[0];
  12586. if (_ele) {
  12587. return style.getRawStyle(_ele);
  12588. } else {
  12589. // empty collection => can't get any value
  12590. return;
  12591. }
  12592. }
  12593. return this; // chaining
  12594. },
  12595. removeStyle: function removeStyle(names) {
  12596. var cy = this.cy();
  12597. if (!cy.styleEnabled()) {
  12598. return this;
  12599. }
  12600. var updateTransitions = false;
  12601. var style = cy.style();
  12602. var eles = this;
  12603. if (names === undefined) {
  12604. for (var i = 0; i < eles.length; i++) {
  12605. var ele = eles[i];
  12606. style.removeAllBypasses(ele, updateTransitions);
  12607. }
  12608. } else {
  12609. names = names.split(/\s+/);
  12610. for (var _i = 0; _i < eles.length; _i++) {
  12611. var _ele2 = eles[_i];
  12612. style.removeBypasses(_ele2, names, updateTransitions);
  12613. }
  12614. }
  12615. this.emitAndNotify('style'); // let the renderer know we've updated style
  12616. return this; // chaining
  12617. },
  12618. show: function show() {
  12619. this.css('display', 'element');
  12620. return this; // chaining
  12621. },
  12622. hide: function hide() {
  12623. this.css('display', 'none');
  12624. return this; // chaining
  12625. },
  12626. effectiveOpacity: function effectiveOpacity() {
  12627. var cy = this.cy();
  12628. if (!cy.styleEnabled()) {
  12629. return 1;
  12630. }
  12631. var hasCompoundNodes = cy.hasCompoundNodes();
  12632. var ele = this[0];
  12633. if (ele) {
  12634. var _p = ele._private;
  12635. var parentOpacity = ele.pstyle('opacity').value;
  12636. if (!hasCompoundNodes) {
  12637. return parentOpacity;
  12638. }
  12639. var parents = !_p.data.parent ? null : ele.parents();
  12640. if (parents) {
  12641. for (var i = 0; i < parents.length; i++) {
  12642. var parent = parents[i];
  12643. var opacity = parent.pstyle('opacity').value;
  12644. parentOpacity = opacity * parentOpacity;
  12645. }
  12646. }
  12647. return parentOpacity;
  12648. }
  12649. },
  12650. transparent: function transparent() {
  12651. var cy = this.cy();
  12652. if (!cy.styleEnabled()) {
  12653. return false;
  12654. }
  12655. var ele = this[0];
  12656. var hasCompoundNodes = ele.cy().hasCompoundNodes();
  12657. if (ele) {
  12658. if (!hasCompoundNodes) {
  12659. return ele.pstyle('opacity').value === 0;
  12660. } else {
  12661. return ele.effectiveOpacity() === 0;
  12662. }
  12663. }
  12664. },
  12665. backgrounding: function backgrounding() {
  12666. var cy = this.cy();
  12667. if (!cy.styleEnabled()) {
  12668. return false;
  12669. }
  12670. var ele = this[0];
  12671. return ele._private.backgrounding ? true : false;
  12672. }
  12673. };
  12674. function checkCompound(ele, parentOk) {
  12675. var _p = ele._private;
  12676. var parents = _p.data.parent ? ele.parents() : null;
  12677. if (parents) {
  12678. for (var i = 0; i < parents.length; i++) {
  12679. var parent = parents[i];
  12680. if (!parentOk(parent)) {
  12681. return false;
  12682. }
  12683. }
  12684. }
  12685. return true;
  12686. }
  12687. function defineDerivedStateFunction(specs) {
  12688. var ok = specs.ok;
  12689. var edgeOkViaNode = specs.edgeOkViaNode || specs.ok;
  12690. var parentOk = specs.parentOk || specs.ok;
  12691. return function () {
  12692. var cy = this.cy();
  12693. if (!cy.styleEnabled()) {
  12694. return true;
  12695. }
  12696. var ele = this[0];
  12697. var hasCompoundNodes = cy.hasCompoundNodes();
  12698. if (ele) {
  12699. var _p = ele._private;
  12700. if (!ok(ele)) {
  12701. return false;
  12702. }
  12703. if (ele.isNode()) {
  12704. return !hasCompoundNodes || checkCompound(ele, parentOk);
  12705. } else {
  12706. var src = _p.source;
  12707. var tgt = _p.target;
  12708. return edgeOkViaNode(src) && (!hasCompoundNodes || checkCompound(src, edgeOkViaNode)) && (src === tgt || edgeOkViaNode(tgt) && (!hasCompoundNodes || checkCompound(tgt, edgeOkViaNode)));
  12709. }
  12710. }
  12711. };
  12712. }
  12713. var eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {
  12714. return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);
  12715. });
  12716. elesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({
  12717. ok: eleTakesUpSpace
  12718. }));
  12719. var eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {
  12720. return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);
  12721. });
  12722. var parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {
  12723. return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);
  12724. });
  12725. elesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({
  12726. ok: eleInteractive,
  12727. parentOk: parentInteractive,
  12728. edgeOkViaNode: eleTakesUpSpace
  12729. }));
  12730. elesfn$4.noninteractive = function () {
  12731. var ele = this[0];
  12732. if (ele) {
  12733. return !ele.interactive();
  12734. }
  12735. };
  12736. var eleVisible = cacheStyleFunction('eleVisible', function (ele) {
  12737. return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);
  12738. });
  12739. var edgeVisibleViaNode = eleTakesUpSpace;
  12740. elesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({
  12741. ok: eleVisible,
  12742. edgeOkViaNode: edgeVisibleViaNode
  12743. }));
  12744. elesfn$4.hidden = function () {
  12745. var ele = this[0];
  12746. if (ele) {
  12747. return !ele.visible();
  12748. }
  12749. };
  12750. elesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {
  12751. if (!this.cy().styleEnabled()) {
  12752. return false;
  12753. }
  12754. return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();
  12755. });
  12756. elesfn$4.bypass = elesfn$4.css = elesfn$4.style;
  12757. elesfn$4.renderedCss = elesfn$4.renderedStyle;
  12758. elesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;
  12759. elesfn$4.pstyle = elesfn$4.parsedStyle;
  12760. var elesfn$3 = {};
  12761. function defineSwitchFunction(params) {
  12762. return function () {
  12763. var args = arguments;
  12764. var changedEles = [];
  12765. // e.g. cy.nodes().select( data, handler )
  12766. if (args.length === 2) {
  12767. var data = args[0];
  12768. var handler = args[1];
  12769. this.on(params.event, data, handler);
  12770. }
  12771. // e.g. cy.nodes().select( handler )
  12772. else if (args.length === 1 && fn$6(args[0])) {
  12773. var _handler = args[0];
  12774. this.on(params.event, _handler);
  12775. }
  12776. // e.g. cy.nodes().select()
  12777. // e.g. (private) cy.nodes().select(['tapselect'])
  12778. else if (args.length === 0 || args.length === 1 && array(args[0])) {
  12779. var addlEvents = args.length === 1 ? args[0] : null;
  12780. for (var i = 0; i < this.length; i++) {
  12781. var ele = this[i];
  12782. var able = !params.ableField || ele._private[params.ableField];
  12783. var changed = ele._private[params.field] != params.value;
  12784. if (params.overrideAble) {
  12785. var overrideAble = params.overrideAble(ele);
  12786. if (overrideAble !== undefined) {
  12787. able = overrideAble;
  12788. if (!overrideAble) {
  12789. return this;
  12790. } // to save cycles assume not able for all on override
  12791. }
  12792. }
  12793. if (able) {
  12794. ele._private[params.field] = params.value;
  12795. if (changed) {
  12796. changedEles.push(ele);
  12797. }
  12798. }
  12799. }
  12800. var changedColl = this.spawn(changedEles);
  12801. changedColl.updateStyle(); // change of state => possible change of style
  12802. changedColl.emit(params.event);
  12803. if (addlEvents) {
  12804. changedColl.emit(addlEvents);
  12805. }
  12806. }
  12807. return this;
  12808. };
  12809. }
  12810. function defineSwitchSet(params) {
  12811. elesfn$3[params.field] = function () {
  12812. var ele = this[0];
  12813. if (ele) {
  12814. if (params.overrideField) {
  12815. var val = params.overrideField(ele);
  12816. if (val !== undefined) {
  12817. return val;
  12818. }
  12819. }
  12820. return ele._private[params.field];
  12821. }
  12822. };
  12823. elesfn$3[params.on] = defineSwitchFunction({
  12824. event: params.on,
  12825. field: params.field,
  12826. ableField: params.ableField,
  12827. overrideAble: params.overrideAble,
  12828. value: true
  12829. });
  12830. elesfn$3[params.off] = defineSwitchFunction({
  12831. event: params.off,
  12832. field: params.field,
  12833. ableField: params.ableField,
  12834. overrideAble: params.overrideAble,
  12835. value: false
  12836. });
  12837. }
  12838. defineSwitchSet({
  12839. field: 'locked',
  12840. overrideField: function overrideField(ele) {
  12841. return ele.cy().autolock() ? true : undefined;
  12842. },
  12843. on: 'lock',
  12844. off: 'unlock'
  12845. });
  12846. defineSwitchSet({
  12847. field: 'grabbable',
  12848. overrideField: function overrideField(ele) {
  12849. return ele.cy().autoungrabify() || ele.pannable() ? false : undefined;
  12850. },
  12851. on: 'grabify',
  12852. off: 'ungrabify'
  12853. });
  12854. defineSwitchSet({
  12855. field: 'selected',
  12856. ableField: 'selectable',
  12857. overrideAble: function overrideAble(ele) {
  12858. return ele.cy().autounselectify() ? false : undefined;
  12859. },
  12860. on: 'select',
  12861. off: 'unselect'
  12862. });
  12863. defineSwitchSet({
  12864. field: 'selectable',
  12865. overrideField: function overrideField(ele) {
  12866. return ele.cy().autounselectify() ? false : undefined;
  12867. },
  12868. on: 'selectify',
  12869. off: 'unselectify'
  12870. });
  12871. elesfn$3.deselect = elesfn$3.unselect;
  12872. elesfn$3.grabbed = function () {
  12873. var ele = this[0];
  12874. if (ele) {
  12875. return ele._private.grabbed;
  12876. }
  12877. };
  12878. defineSwitchSet({
  12879. field: 'active',
  12880. on: 'activate',
  12881. off: 'unactivate'
  12882. });
  12883. defineSwitchSet({
  12884. field: 'pannable',
  12885. on: 'panify',
  12886. off: 'unpanify'
  12887. });
  12888. elesfn$3.inactive = function () {
  12889. var ele = this[0];
  12890. if (ele) {
  12891. return !ele._private.active;
  12892. }
  12893. };
  12894. var elesfn$2 = {};
  12895. // DAG functions
  12896. ////////////////
  12897. var defineDagExtremity = function defineDagExtremity(params) {
  12898. return function dagExtremityImpl(selector) {
  12899. var eles = this;
  12900. var ret = [];
  12901. for (var i = 0; i < eles.length; i++) {
  12902. var ele = eles[i];
  12903. if (!ele.isNode()) {
  12904. continue;
  12905. }
  12906. var disqualified = false;
  12907. var edges = ele.connectedEdges();
  12908. for (var j = 0; j < edges.length; j++) {
  12909. var edge = edges[j];
  12910. var src = edge.source();
  12911. var tgt = edge.target();
  12912. if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {
  12913. disqualified = true;
  12914. break;
  12915. }
  12916. }
  12917. if (!disqualified) {
  12918. ret.push(ele);
  12919. }
  12920. }
  12921. return this.spawn(ret, true).filter(selector);
  12922. };
  12923. };
  12924. var defineDagOneHop = function defineDagOneHop(params) {
  12925. return function (selector) {
  12926. var eles = this;
  12927. var oEles = [];
  12928. for (var i = 0; i < eles.length; i++) {
  12929. var ele = eles[i];
  12930. if (!ele.isNode()) {
  12931. continue;
  12932. }
  12933. var edges = ele.connectedEdges();
  12934. for (var j = 0; j < edges.length; j++) {
  12935. var edge = edges[j];
  12936. var src = edge.source();
  12937. var tgt = edge.target();
  12938. if (params.outgoing && src === ele) {
  12939. oEles.push(edge);
  12940. oEles.push(tgt);
  12941. } else if (params.incoming && tgt === ele) {
  12942. oEles.push(edge);
  12943. oEles.push(src);
  12944. }
  12945. }
  12946. }
  12947. return this.spawn(oEles, true).filter(selector);
  12948. };
  12949. };
  12950. var defineDagAllHops = function defineDagAllHops(params) {
  12951. return function (selector) {
  12952. var eles = this;
  12953. var sEles = [];
  12954. var sElesIds = {};
  12955. for (;;) {
  12956. var next = params.outgoing ? eles.outgoers() : eles.incomers();
  12957. if (next.length === 0) {
  12958. break;
  12959. } // done if none left
  12960. var newNext = false;
  12961. for (var i = 0; i < next.length; i++) {
  12962. var n = next[i];
  12963. var nid = n.id();
  12964. if (!sElesIds[nid]) {
  12965. sElesIds[nid] = true;
  12966. sEles.push(n);
  12967. newNext = true;
  12968. }
  12969. }
  12970. if (!newNext) {
  12971. break;
  12972. } // done if touched all outgoers already
  12973. eles = next;
  12974. }
  12975. return this.spawn(sEles, true).filter(selector);
  12976. };
  12977. };
  12978. elesfn$2.clearTraversalCache = function () {
  12979. for (var i = 0; i < this.length; i++) {
  12980. this[i]._private.traversalCache = null;
  12981. }
  12982. };
  12983. extend(elesfn$2, {
  12984. // get the root nodes in the DAG
  12985. roots: defineDagExtremity({
  12986. noIncomingEdges: true
  12987. }),
  12988. // get the leaf nodes in the DAG
  12989. leaves: defineDagExtremity({
  12990. noOutgoingEdges: true
  12991. }),
  12992. // normally called children in graph theory
  12993. // these nodes =edges=> outgoing nodes
  12994. outgoers: cache(defineDagOneHop({
  12995. outgoing: true
  12996. }), 'outgoers'),
  12997. // aka DAG descendants
  12998. successors: defineDagAllHops({
  12999. outgoing: true
  13000. }),
  13001. // normally called parents in graph theory
  13002. // these nodes <=edges= incoming nodes
  13003. incomers: cache(defineDagOneHop({
  13004. incoming: true
  13005. }), 'incomers'),
  13006. // aka DAG ancestors
  13007. predecessors: defineDagAllHops({
  13008. })
  13009. });
  13010. // Neighbourhood functions
  13011. //////////////////////////
  13012. extend(elesfn$2, {
  13013. neighborhood: cache(function (selector) {
  13014. var elements = [];
  13015. var nodes = this.nodes();
  13016. for (var i = 0; i < nodes.length; i++) {
  13017. // for all nodes
  13018. var node = nodes[i];
  13019. var connectedEdges = node.connectedEdges();
  13020. // for each connected edge, add the edge and the other node
  13021. for (var j = 0; j < connectedEdges.length; j++) {
  13022. var edge = connectedEdges[j];
  13023. var src = edge.source();
  13024. var tgt = edge.target();
  13025. var otherNode = node === src ? tgt : src;
  13026. // need check in case of loop
  13027. if (otherNode.length > 0) {
  13028. elements.push(otherNode[0]); // add node 1 hop away
  13029. }
  13030. // add connected edge
  13031. elements.push(edge[0]);
  13032. }
  13033. }
  13034. return this.spawn(elements, true).filter(selector);
  13035. }, 'neighborhood'),
  13036. closedNeighborhood: function closedNeighborhood(selector) {
  13037. return this.neighborhood().add(this).filter(selector);
  13038. },
  13039. openNeighborhood: function openNeighborhood(selector) {
  13040. return this.neighborhood(selector);
  13041. }
  13042. });
  13043. // aliases
  13044. elesfn$2.neighbourhood = elesfn$2.neighborhood;
  13045. elesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;
  13046. elesfn$2.openNeighbourhood = elesfn$2.openNeighborhood;
  13047. // Edge functions
  13048. /////////////////
  13049. extend(elesfn$2, {
  13050. source: cache(function sourceImpl(selector) {
  13051. var ele = this[0];
  13052. var src;
  13053. if (ele) {
  13054. src = ele._private.source || ele.cy().collection();
  13055. }
  13056. return src && selector ? src.filter(selector) : src;
  13057. }, 'source'),
  13058. target: cache(function targetImpl(selector) {
  13059. var ele = this[0];
  13060. var tgt;
  13061. if (ele) {
  13062. tgt = ele._private.target || ele.cy().collection();
  13063. }
  13064. return tgt && selector ? tgt.filter(selector) : tgt;
  13065. }, 'target'),
  13066. sources: defineSourceFunction({
  13067. attr: 'source'
  13068. }),
  13069. targets: defineSourceFunction({
  13070. attr: 'target'
  13071. })
  13072. });
  13073. function defineSourceFunction(params) {
  13074. return function sourceImpl(selector) {
  13075. var sources = [];
  13076. for (var i = 0; i < this.length; i++) {
  13077. var ele = this[i];
  13078. var src = ele._private[params.attr];
  13079. if (src) {
  13080. sources.push(src);
  13081. }
  13082. }
  13083. return this.spawn(sources, true).filter(selector);
  13084. };
  13085. }
  13086. extend(elesfn$2, {
  13087. edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),
  13088. edgesTo: cache(defineEdgesWithFunction({
  13089. thisIsSrc: true
  13090. }), 'edgesTo')
  13091. });
  13092. function defineEdgesWithFunction(params) {
  13093. return function edgesWithImpl(otherNodes) {
  13094. var elements = [];
  13095. var cy = this._private.cy;
  13096. var p = params || {};
  13097. // get elements if a selector is specified
  13098. if (string(otherNodes)) {
  13099. otherNodes = cy.$(otherNodes);
  13100. }
  13101. for (var h = 0; h < otherNodes.length; h++) {
  13102. var edges = otherNodes[h]._private.edges;
  13103. for (var i = 0; i < edges.length; i++) {
  13104. var edge = edges[i];
  13105. var edgeData = edge._private.data;
  13106. var thisToOther = this.hasElementWithId(edgeData.source) && otherNodes.hasElementWithId(edgeData.target);
  13107. var otherToThis = otherNodes.hasElementWithId(edgeData.source) && this.hasElementWithId(edgeData.target);
  13108. var edgeConnectsThisAndOther = thisToOther || otherToThis;
  13109. if (!edgeConnectsThisAndOther) {
  13110. continue;
  13111. }
  13112. if (p.thisIsSrc || p.thisIsTgt) {
  13113. if (p.thisIsSrc && !thisToOther) {
  13114. continue;
  13115. }
  13116. if (p.thisIsTgt && !otherToThis) {
  13117. continue;
  13118. }
  13119. }
  13120. elements.push(edge);
  13121. }
  13122. }
  13123. return this.spawn(elements, true);
  13124. };
  13125. }
  13126. extend(elesfn$2, {
  13127. connectedEdges: cache(function (selector) {
  13128. var retEles = [];
  13129. var eles = this;
  13130. for (var i = 0; i < eles.length; i++) {
  13131. var node = eles[i];
  13132. if (!node.isNode()) {
  13133. continue;
  13134. }
  13135. var edges = node._private.edges;
  13136. for (var j = 0; j < edges.length; j++) {
  13137. var edge = edges[j];
  13138. retEles.push(edge);
  13139. }
  13140. }
  13141. return this.spawn(retEles, true).filter(selector);
  13142. }, 'connectedEdges'),
  13143. connectedNodes: cache(function (selector) {
  13144. var retEles = [];
  13145. var eles = this;
  13146. for (var i = 0; i < eles.length; i++) {
  13147. var edge = eles[i];
  13148. if (!edge.isEdge()) {
  13149. continue;
  13150. }
  13151. retEles.push(edge.source()[0]);
  13152. retEles.push(edge.target()[0]);
  13153. }
  13154. return this.spawn(retEles, true).filter(selector);
  13155. }, 'connectedNodes'),
  13156. parallelEdges: cache(defineParallelEdgesFunction(), 'parallelEdges'),
  13157. codirectedEdges: cache(defineParallelEdgesFunction({
  13158. codirected: true
  13159. }), 'codirectedEdges')
  13160. });
  13161. function defineParallelEdgesFunction(params) {
  13162. var defaults = {
  13163. codirected: false
  13164. };
  13165. params = extend({}, defaults, params);
  13166. return function parallelEdgesImpl(selector) {
  13167. // micro-optimised for renderer
  13168. var elements = [];
  13169. var edges = this.edges();
  13170. var p = params;
  13171. // look at all the edges in the collection
  13172. for (var i = 0; i < edges.length; i++) {
  13173. var edge1 = edges[i];
  13174. var edge1_p = edge1._private;
  13175. var src1 = edge1_p.source;
  13176. var srcid1 = src1._private.data.id;
  13177. var tgtid1 = edge1_p.data.target;
  13178. var srcEdges1 = src1._private.edges;
  13179. // look at edges connected to the src node of this edge
  13180. for (var j = 0; j < srcEdges1.length; j++) {
  13181. var edge2 = srcEdges1[j];
  13182. var edge2data = edge2._private.data;
  13183. var tgtid2 = edge2data.target;
  13184. var srcid2 = edge2data.source;
  13185. var codirected = tgtid2 === tgtid1 && srcid2 === srcid1;
  13186. var oppdirected = srcid1 === tgtid2 && tgtid1 === srcid2;
  13187. if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {
  13188. elements.push(edge2);
  13189. }
  13190. }
  13191. }
  13192. return this.spawn(elements, true).filter(selector);
  13193. };
  13194. }
  13195. // Misc functions
  13196. /////////////////
  13197. extend(elesfn$2, {
  13198. components: function components(root) {
  13199. var self = this;
  13200. var cy = self.cy();
  13201. var visited = cy.collection();
  13202. var unvisited = root == null ? self.nodes() : root.nodes();
  13203. var components = [];
  13204. if (root != null && unvisited.empty()) {
  13205. // root may contain only edges
  13206. unvisited = root.sources(); // doesn't matter which node to use (undirected), so just use the source sides
  13207. }
  13208. var visitInComponent = function visitInComponent(node, component) {
  13209. visited.merge(node);
  13210. unvisited.unmerge(node);
  13211. component.merge(node);
  13212. };
  13213. if (unvisited.empty()) {
  13214. return self.spawn();
  13215. }
  13216. var _loop = function _loop() {
  13217. // each iteration yields a component
  13218. var cmpt = cy.collection();
  13219. components.push(cmpt);
  13220. var root = unvisited[0];
  13221. visitInComponent(root, cmpt);
  13222. self.bfs({
  13223. directed: false,
  13224. roots: root,
  13225. visit: function visit(v) {
  13226. return visitInComponent(v, cmpt);
  13227. }
  13228. });
  13229. cmpt.forEach(function (node) {
  13230. node.connectedEdges().forEach(function (e) {
  13231. // connectedEdges() usually cached
  13232. if (self.has(e) && cmpt.has(e.source()) && cmpt.has(e.target())) {
  13233. // has() is cheap
  13234. cmpt.merge(e); // forEach() only considers nodes -- sets N at call time
  13235. }
  13236. });
  13237. });
  13238. };
  13239. do {
  13240. _loop();
  13241. } while (unvisited.length > 0);
  13242. return components;
  13243. },
  13244. component: function component() {
  13245. var ele = this[0];
  13246. return ele.cy().mutableElements().components(ele)[0];
  13247. }
  13248. });
  13249. elesfn$2.componentsOf = elesfn$2.components;
  13250. // represents a set of nodes, edges, or both together
  13251. var Collection = function Collection(cy, elements) {
  13252. var unique = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  13253. var removed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  13254. if (cy === undefined) {
  13255. error('A collection must have a reference to the core');
  13256. return;
  13257. }
  13258. var map = new Map$1();
  13259. var createdElements = false;
  13260. if (!elements) {
  13261. elements = [];
  13262. } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {
  13263. createdElements = true;
  13264. // make elements from json and restore all at once later
  13265. var eles = [];
  13266. var elesIds = new Set$1();
  13267. for (var i = 0, l = elements.length; i < l; i++) {
  13268. var json = elements[i];
  13269. if (json.data == null) {
  13270. json.data = {};
  13271. }
  13272. var _data = json.data;
  13273. // make sure newly created elements have valid ids
  13274. if (_data.id == null) {
  13275. _data.id = uuid();
  13276. } else if (cy.hasElementWithId(_data.id) || elesIds.has(_data.id)) {
  13277. continue; // can't create element if prior id already exists
  13278. }
  13279. var ele = new Element(cy, json, false);
  13280. eles.push(ele);
  13281. elesIds.add(_data.id);
  13282. }
  13283. elements = eles;
  13284. }
  13285. this.length = 0;
  13286. for (var _i = 0, _l = elements.length; _i < _l; _i++) {
  13287. var element$1 = elements[_i][0]; // [0] in case elements is an array of collections, rather than array of elements
  13288. if (element$1 == null) {
  13289. continue;
  13290. }
  13291. var id = element$1._private.data.id;
  13292. if (!unique || !map.has(id)) {
  13293. if (unique) {
  13294. map.set(id, {
  13295. index: this.length,
  13296. ele: element$1
  13297. });
  13298. }
  13299. this[this.length] = element$1;
  13300. this.length++;
  13301. }
  13302. }
  13303. this._private = {
  13304. eles: this,
  13305. cy: cy,
  13306. get map() {
  13307. if (this.lazyMap == null) {
  13308. this.rebuildMap();
  13309. }
  13310. return this.lazyMap;
  13311. },
  13312. set map(m) {
  13313. this.lazyMap = m;
  13314. },
  13315. rebuildMap: function rebuildMap() {
  13316. var m = this.lazyMap = new Map$1();
  13317. var eles = this.eles;
  13318. for (var _i2 = 0; _i2 < eles.length; _i2++) {
  13319. var _ele = eles[_i2];
  13320. m.set(_ele.id(), {
  13321. index: _i2,
  13322. ele: _ele
  13323. });
  13324. }
  13325. }
  13326. };
  13327. if (unique) {
  13328. this._private.map = map;
  13329. }
  13330. // restore the elements if we created them from json
  13331. if (createdElements && !removed) {
  13332. this.restore();
  13333. }
  13334. };
  13335. // Functions
  13336. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13337. // keep the prototypes in sync (an element has the same functions as a collection)
  13338. // and use elefn and elesfn as shorthands to the prototypes
  13339. var elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);
  13340. elesfn$1.instanceString = function () {
  13341. return 'collection';
  13342. };
  13343. elesfn$1.spawn = function (eles, unique) {
  13344. return new Collection(this.cy(), eles, unique);
  13345. };
  13346. elesfn$1.spawnSelf = function () {
  13347. return this.spawn(this);
  13348. };
  13349. elesfn$1.cy = function () {
  13350. return this._private.cy;
  13351. };
  13352. elesfn$1.renderer = function () {
  13353. return this._private.cy.renderer();
  13354. };
  13355. elesfn$1.element = function () {
  13356. return this[0];
  13357. };
  13358. elesfn$1.collection = function () {
  13359. if (collection(this)) {
  13360. return this;
  13361. } else {
  13362. // an element
  13363. return new Collection(this._private.cy, [this]);
  13364. }
  13365. };
  13366. elesfn$1.unique = function () {
  13367. return new Collection(this._private.cy, this, true);
  13368. };
  13369. elesfn$1.hasElementWithId = function (id) {
  13370. id = '' + id; // id must be string
  13371. return this._private.map.has(id);
  13372. };
  13373. elesfn$1.getElementById = function (id) {
  13374. id = '' + id; // id must be string
  13375. var cy = this._private.cy;
  13376. var entry = this._private.map.get(id);
  13377. return entry ? entry.ele : new Collection(cy); // get ele or empty collection
  13378. };
  13379. elesfn$1.$id = elesfn$1.getElementById;
  13380. elesfn$1.poolIndex = function () {
  13381. var cy = this._private.cy;
  13382. var eles = cy._private.elements;
  13383. var id = this[0]._private.data.id;
  13384. return eles._private.map.get(id).index;
  13385. };
  13386. elesfn$1.indexOf = function (ele) {
  13387. var id = ele[0]._private.data.id;
  13388. return this._private.map.get(id).index;
  13389. };
  13390. elesfn$1.indexOfId = function (id) {
  13391. id = '' + id; // id must be string
  13392. return this._private.map.get(id).index;
  13393. };
  13394. elesfn$1.json = function (obj) {
  13395. var ele = this.element();
  13396. var cy = this.cy();
  13397. if (ele == null && obj) {
  13398. return this;
  13399. } // can't set to no eles
  13400. if (ele == null) {
  13401. return undefined;
  13402. } // can't get from no eles
  13403. var p = ele._private;
  13404. if (plainObject(obj)) {
  13405. // set
  13406. cy.startBatch();
  13407. if (obj.data) {
  13408. ele.data(obj.data);
  13409. var _data2 = p.data;
  13410. if (ele.isEdge()) {
  13411. // source and target are immutable via data()
  13412. var move = false;
  13413. var spec = {};
  13414. var src = obj.data.source;
  13415. var tgt = obj.data.target;
  13416. if (src != null && src != _data2.source) {
  13417. spec.source = '' + src; // id must be string
  13418. move = true;
  13419. }
  13420. if (tgt != null && tgt != _data2.target) {
  13421. spec.target = '' + tgt; // id must be string
  13422. move = true;
  13423. }
  13424. if (move) {
  13425. ele = ele.move(spec);
  13426. }
  13427. } else {
  13428. // parent is immutable via data()
  13429. var newParentValSpecd = 'parent' in obj.data;
  13430. var parent = obj.data.parent;
  13431. if (newParentValSpecd && (parent != null || _data2.parent != null) && parent != _data2.parent) {
  13432. if (parent === undefined) {
  13433. // can't set undefined imperatively, so use null
  13434. parent = null;
  13435. }
  13436. if (parent != null) {
  13437. parent = '' + parent; // id must be string
  13438. }
  13439. ele = ele.move({
  13440. parent: parent
  13441. });
  13442. }
  13443. }
  13444. }
  13445. if (obj.position) {
  13446. ele.position(obj.position);
  13447. }
  13448. // ignore group -- immutable
  13449. var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {
  13450. var obj_k = obj[k];
  13451. if (obj_k != null && obj_k !== p[k]) {
  13452. if (obj_k) {
  13453. ele[trueFnName]();
  13454. } else {
  13455. ele[falseFnName]();
  13456. }
  13457. }
  13458. };
  13459. checkSwitch('removed', 'remove', 'restore');
  13460. checkSwitch('selected', 'select', 'unselect');
  13461. checkSwitch('selectable', 'selectify', 'unselectify');
  13462. checkSwitch('locked', 'lock', 'unlock');
  13463. checkSwitch('grabbable', 'grabify', 'ungrabify');
  13464. checkSwitch('pannable', 'panify', 'unpanify');
  13465. if (obj.classes != null) {
  13466. ele.classes(obj.classes);
  13467. }
  13468. cy.endBatch();
  13469. return this;
  13470. } else if (obj === undefined) {
  13471. // get
  13472. var json = {
  13473. data: copy(p.data),
  13474. position: copy(p.position),
  13475. group: p.group,
  13476. removed: p.removed,
  13477. selected: p.selected,
  13478. selectable: p.selectable,
  13479. locked: p.locked,
  13480. grabbable: p.grabbable,
  13481. pannable: p.pannable,
  13482. classes: null
  13483. };
  13484. json.classes = '';
  13485. var i = 0;
  13486. p.classes.forEach(function (cls) {
  13487. return json.classes += i++ === 0 ? cls : ' ' + cls;
  13488. });
  13489. return json;
  13490. }
  13491. };
  13492. elesfn$1.jsons = function () {
  13493. var jsons = [];
  13494. for (var i = 0; i < this.length; i++) {
  13495. var ele = this[i];
  13496. var json = ele.json();
  13497. jsons.push(json);
  13498. }
  13499. return jsons;
  13500. };
  13501. elesfn$1.clone = function () {
  13502. var cy = this.cy();
  13503. var elesArr = [];
  13504. for (var i = 0; i < this.length; i++) {
  13505. var ele = this[i];
  13506. var json = ele.json();
  13507. var clone = new Element(cy, json, false); // NB no restore
  13508. elesArr.push(clone);
  13509. }
  13510. return new Collection(cy, elesArr);
  13511. };
  13512. elesfn$1.copy = elesfn$1.clone;
  13513. elesfn$1.restore = function () {
  13514. var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  13515. var addToPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  13516. var self = this;
  13517. var cy = self.cy();
  13518. var cy_p = cy._private;
  13519. // create arrays of nodes and edges, since we need to
  13520. // restore the nodes first
  13521. var nodes = [];
  13522. var edges = [];
  13523. var elements;
  13524. for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {
  13525. var ele = self[_i3];
  13526. if (addToPool && !ele.removed()) {
  13527. // don't need to handle this ele
  13528. continue;
  13529. }
  13530. // keep nodes first in the array and edges after
  13531. if (ele.isNode()) {
  13532. // put to front of array if node
  13533. nodes.push(ele);
  13534. } else {
  13535. // put to end of array if edge
  13536. edges.push(ele);
  13537. }
  13538. }
  13539. elements = nodes.concat(edges);
  13540. var i;
  13541. var removeFromElements = function removeFromElements() {
  13542. elements.splice(i, 1);
  13543. i--;
  13544. };
  13545. // now, restore each element
  13546. for (i = 0; i < elements.length; i++) {
  13547. var _ele2 = elements[i];
  13548. var _private = _ele2._private;
  13549. var _data3 = _private.data;
  13550. // the traversal cache should start fresh when ele is added
  13551. _ele2.clearTraversalCache();
  13552. // set id and validate
  13553. if (!addToPool && !_private.removed) ; else if (_data3.id === undefined) {
  13554. _data3.id = uuid();
  13555. } else if (number$1(_data3.id)) {
  13556. _data3.id = '' + _data3.id; // now it's a string
  13557. } else if (emptyString(_data3.id) || !string(_data3.id)) {
  13558. error('Can not create element with invalid string ID `' + _data3.id + '`');
  13559. // can't create element if it has empty string as id or non-string id
  13560. removeFromElements();
  13561. continue;
  13562. } else if (cy.hasElementWithId(_data3.id)) {
  13563. error('Can not create second element with ID `' + _data3.id + '`');
  13564. // can't create element if one already has that id
  13565. removeFromElements();
  13566. continue;
  13567. }
  13568. var id = _data3.id; // id is finalised, now let's keep a ref
  13569. if (_ele2.isNode()) {
  13570. // extra checks for nodes
  13571. var pos = _private.position;
  13572. // make sure the nodes have a defined position
  13573. if (pos.x == null) {
  13574. pos.x = 0;
  13575. }
  13576. if (pos.y == null) {
  13577. pos.y = 0;
  13578. }
  13579. }
  13580. if (_ele2.isEdge()) {
  13581. // extra checks for edges
  13582. var edge = _ele2;
  13583. var fields = ['source', 'target'];
  13584. var fieldsLength = fields.length;
  13585. var badSourceOrTarget = false;
  13586. for (var j = 0; j < fieldsLength; j++) {
  13587. var field = fields[j];
  13588. var val = _data3[field];
  13589. if (number$1(val)) {
  13590. val = _data3[field] = '' + _data3[field]; // now string
  13591. }
  13592. if (val == null || val === '') {
  13593. // can't create if source or target is not defined properly
  13594. error('Can not create edge `' + id + '` with unspecified ' + field);
  13595. badSourceOrTarget = true;
  13596. } else if (!cy.hasElementWithId(val)) {
  13597. // can't create edge if one of its nodes doesn't exist
  13598. error('Can not create edge `' + id + '` with nonexistent ' + field + ' `' + val + '`');
  13599. badSourceOrTarget = true;
  13600. }
  13601. }
  13602. if (badSourceOrTarget) {
  13603. removeFromElements();
  13604. continue;
  13605. } // can't create this
  13606. var src = cy.getElementById(_data3.source);
  13607. var tgt = cy.getElementById(_data3.target);
  13608. // only one edge in node if loop
  13609. if (src.same(tgt)) {
  13610. src._private.edges.push(edge);
  13611. } else {
  13612. src._private.edges.push(edge);
  13613. tgt._private.edges.push(edge);
  13614. }
  13615. edge._private.source = src;
  13616. edge._private.target = tgt;
  13617. } // if is edge
  13618. // create mock ids / indexes maps for element so it can be used like collections
  13619. _private.map = new Map$1();
  13620. _private.map.set(id, {
  13621. ele: _ele2,
  13622. index: 0
  13623. });
  13624. _private.removed = false;
  13625. if (addToPool) {
  13626. cy.addToPool(_ele2);
  13627. }
  13628. } // for each element
  13629. // do compound node sanity checks
  13630. for (var _i4 = 0; _i4 < nodes.length; _i4++) {
  13631. // each node
  13632. var node = nodes[_i4];
  13633. var _data4 = node._private.data;
  13634. if (number$1(_data4.parent)) {
  13635. // then automake string
  13636. _data4.parent = '' + _data4.parent;
  13637. }
  13638. var parentId = _data4.parent;
  13639. var specifiedParent = parentId != null;
  13640. if (specifiedParent || node._private.parent) {
  13641. var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);
  13642. if (parent.empty()) {
  13643. // non-existant parent; just remove it
  13644. _data4.parent = undefined;
  13645. } else if (parent[0].removed()) {
  13646. warn('Node added with missing parent, reference to parent removed');
  13647. _data4.parent = undefined;
  13648. node._private.parent = null;
  13649. } else {
  13650. var selfAsParent = false;
  13651. var ancestor = parent;
  13652. while (!ancestor.empty()) {
  13653. if (node.same(ancestor)) {
  13654. // mark self as parent and remove from data
  13655. selfAsParent = true;
  13656. _data4.parent = undefined; // remove parent reference
  13657. // exit or we loop forever
  13658. break;
  13659. }
  13660. ancestor = ancestor.parent();
  13661. }
  13662. if (!selfAsParent) {
  13663. // connect with children
  13664. parent[0]._private.children.push(node);
  13665. node._private.parent = parent[0];
  13666. // let the core know we have a compound graph
  13667. cy_p.hasCompoundNodes = true;
  13668. }
  13669. } // else
  13670. } // if specified parent
  13671. } // for each node
  13672. if (elements.length > 0) {
  13673. var restored = elements.length === self.length ? self : new Collection(cy, elements);
  13674. for (var _i5 = 0; _i5 < restored.length; _i5++) {
  13675. var _ele3 = restored[_i5];
  13676. if (_ele3.isNode()) {
  13677. continue;
  13678. }
  13679. // adding an edge invalidates the traversal caches for the parallel edges
  13680. _ele3.parallelEdges().clearTraversalCache();
  13681. // adding an edge invalidates the traversal cache for the connected nodes
  13682. _ele3.source().clearTraversalCache();
  13683. _ele3.target().clearTraversalCache();
  13684. }
  13685. var toUpdateStyle;
  13686. if (cy_p.hasCompoundNodes) {
  13687. toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());
  13688. } else {
  13689. toUpdateStyle = restored;
  13690. }
  13691. toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);
  13692. if (notifyRenderer) {
  13693. restored.emitAndNotify('add');
  13694. } else if (addToPool) {
  13695. restored.emit('add');
  13696. }
  13697. }
  13698. return self; // chainability
  13699. };
  13700. elesfn$1.removed = function () {
  13701. var ele = this[0];
  13702. return ele && ele._private.removed;
  13703. };
  13704. elesfn$1.inside = function () {
  13705. var ele = this[0];
  13706. return ele && !ele._private.removed;
  13707. };
  13708. elesfn$1.remove = function () {
  13709. var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  13710. var removeFromPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  13711. var self = this;
  13712. var elesToRemove = [];
  13713. var elesToRemoveIds = {};
  13714. var cy = self._private.cy;
  13715. // add connected edges
  13716. function addConnectedEdges(node) {
  13717. var edges = node._private.edges;
  13718. for (var i = 0; i < edges.length; i++) {
  13719. add(edges[i]);
  13720. }
  13721. }
  13722. // add descendant nodes
  13723. function addChildren(node) {
  13724. var children = node._private.children;
  13725. for (var i = 0; i < children.length; i++) {
  13726. add(children[i]);
  13727. }
  13728. }
  13729. function add(ele) {
  13730. var alreadyAdded = elesToRemoveIds[ele.id()];
  13731. if (removeFromPool && ele.removed() || alreadyAdded) {
  13732. return;
  13733. } else {
  13734. elesToRemoveIds[ele.id()] = true;
  13735. }
  13736. if (ele.isNode()) {
  13737. elesToRemove.push(ele); // nodes are removed last
  13738. addConnectedEdges(ele);
  13739. addChildren(ele);
  13740. } else {
  13741. elesToRemove.unshift(ele); // edges are removed first
  13742. }
  13743. }
  13744. // make the list of elements to remove
  13745. // (may be removing more than specified due to connected edges etc)
  13746. for (var i = 0, l = self.length; i < l; i++) {
  13747. var ele = self[i];
  13748. add(ele);
  13749. }
  13750. function removeEdgeRef(node, edge) {
  13751. var connectedEdges = node._private.edges;
  13752. removeFromArray(connectedEdges, edge);
  13753. // removing an edges invalidates the traversal cache for its nodes
  13754. node.clearTraversalCache();
  13755. }
  13756. function removeParallelRef(pllEdge) {
  13757. // removing an edge invalidates the traversal caches for the parallel edges
  13758. pllEdge.clearTraversalCache();
  13759. }
  13760. var alteredParents = [];
  13761. alteredParents.ids = {};
  13762. function removeChildRef(parent, ele) {
  13763. ele = ele[0];
  13764. parent = parent[0];
  13765. var children = parent._private.children;
  13766. var pid = parent.id();
  13767. removeFromArray(children, ele); // remove parent => child ref
  13768. ele._private.parent = null; // remove child => parent ref
  13769. if (!alteredParents.ids[pid]) {
  13770. alteredParents.ids[pid] = true;
  13771. alteredParents.push(parent);
  13772. }
  13773. }
  13774. self.dirtyCompoundBoundsCache();
  13775. if (removeFromPool) {
  13776. cy.removeFromPool(elesToRemove); // remove from core pool
  13777. }
  13778. for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {
  13779. var _ele4 = elesToRemove[_i6];
  13780. if (_ele4.isEdge()) {
  13781. // remove references to this edge in its connected nodes
  13782. var src = _ele4.source()[0];
  13783. var tgt = _ele4.target()[0];
  13784. removeEdgeRef(src, _ele4);
  13785. removeEdgeRef(tgt, _ele4);
  13786. var pllEdges = _ele4.parallelEdges();
  13787. for (var j = 0; j < pllEdges.length; j++) {
  13788. var pllEdge = pllEdges[j];
  13789. removeParallelRef(pllEdge);
  13790. if (pllEdge.isBundledBezier()) {
  13791. pllEdge.dirtyBoundingBoxCache();
  13792. }
  13793. }
  13794. } else {
  13795. // remove reference to parent
  13796. var parent = _ele4.parent();
  13797. if (parent.length !== 0) {
  13798. removeChildRef(parent, _ele4);
  13799. }
  13800. }
  13801. if (removeFromPool) {
  13802. // mark as removed
  13803. _ele4._private.removed = true;
  13804. }
  13805. }
  13806. // check to see if we have a compound graph or not
  13807. var elesStillInside = cy._private.elements;
  13808. cy._private.hasCompoundNodes = false;
  13809. for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {
  13810. var _ele5 = elesStillInside[_i7];
  13811. if (_ele5.isParent()) {
  13812. cy._private.hasCompoundNodes = true;
  13813. break;
  13814. }
  13815. }
  13816. var removedElements = new Collection(this.cy(), elesToRemove);
  13817. if (removedElements.size() > 0) {
  13818. // must manually notify since trigger won't do this automatically once removed
  13819. if (notifyRenderer) {
  13820. removedElements.emitAndNotify('remove');
  13821. } else if (removeFromPool) {
  13822. removedElements.emit('remove');
  13823. }
  13824. }
  13825. // the parents who were modified by the removal need their style updated
  13826. for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {
  13827. var _ele6 = alteredParents[_i8];
  13828. if (!removeFromPool || !_ele6.removed()) {
  13829. _ele6.updateStyle();
  13830. }
  13831. }
  13832. return removedElements;
  13833. };
  13834. elesfn$1.move = function (struct) {
  13835. var cy = this._private.cy;
  13836. var eles = this;
  13837. // just clean up refs, caches, etc. in the same way as when removing and then restoring
  13838. // (our calls to remove/restore do not remove from the graph or make events)
  13839. var notifyRenderer = false;
  13840. var modifyPool = false;
  13841. var toString = function toString(id) {
  13842. return id == null ? id : '' + id;
  13843. }; // id must be string
  13844. if (struct.source !== undefined || struct.target !== undefined) {
  13845. var srcId = toString(struct.source);
  13846. var tgtId = toString(struct.target);
  13847. var srcExists = srcId != null && cy.hasElementWithId(srcId);
  13848. var tgtExists = tgtId != null && cy.hasElementWithId(tgtId);
  13849. if (srcExists || tgtExists) {
  13850. cy.batch(function () {
  13851. // avoid duplicate style updates
  13852. eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
  13853. eles.emitAndNotify('moveout');
  13854. for (var i = 0; i < eles.length; i++) {
  13855. var ele = eles[i];
  13856. var _data5 = ele._private.data;
  13857. if (ele.isEdge()) {
  13858. if (srcExists) {
  13859. _data5.source = srcId;
  13860. }
  13861. if (tgtExists) {
  13862. _data5.target = tgtId;
  13863. }
  13864. }
  13865. }
  13866. eles.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
  13867. });
  13868. eles.emitAndNotify('move');
  13869. }
  13870. } else if (struct.parent !== undefined) {
  13871. // move node to new parent
  13872. var parentId = toString(struct.parent);
  13873. var parentExists = parentId === null || cy.hasElementWithId(parentId);
  13874. if (parentExists) {
  13875. var pidToAssign = parentId === null ? undefined : parentId;
  13876. cy.batch(function () {
  13877. // avoid duplicate style updates
  13878. var updated = eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
  13879. updated.emitAndNotify('moveout');
  13880. for (var i = 0; i < eles.length; i++) {
  13881. var ele = eles[i];
  13882. var _data6 = ele._private.data;
  13883. if (ele.isNode()) {
  13884. _data6.parent = pidToAssign;
  13885. }
  13886. }
  13887. updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
  13888. });
  13889. eles.emitAndNotify('move');
  13890. }
  13891. }
  13892. return this;
  13893. };
  13894. [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) {
  13895. extend(elesfn$1, props);
  13896. });
  13897. var corefn$9 = {
  13898. add: function add(opts) {
  13899. var elements;
  13900. var cy = this;
  13901. // add the elements
  13902. if (elementOrCollection(opts)) {
  13903. var eles = opts;
  13904. if (eles._private.cy === cy) {
  13905. // same instance => just restore
  13906. elements = eles.restore();
  13907. } else {
  13908. // otherwise, copy from json
  13909. var jsons = [];
  13910. for (var i = 0; i < eles.length; i++) {
  13911. var ele = eles[i];
  13912. jsons.push(ele.json());
  13913. }
  13914. elements = new Collection(cy, jsons);
  13915. }
  13916. }
  13917. // specify an array of options
  13918. else if (array(opts)) {
  13919. var _jsons = opts;
  13920. elements = new Collection(cy, _jsons);
  13921. }
  13922. // specify via opts.nodes and opts.edges
  13923. else if (plainObject(opts) && (array(opts.nodes) || array(opts.edges))) {
  13924. var elesByGroup = opts;
  13925. var _jsons2 = [];
  13926. var grs = ['nodes', 'edges'];
  13927. for (var _i = 0, il = grs.length; _i < il; _i++) {
  13928. var group = grs[_i];
  13929. var elesArray = elesByGroup[group];
  13930. if (array(elesArray)) {
  13931. for (var j = 0, jl = elesArray.length; j < jl; j++) {
  13932. var json = extend({
  13933. group: group
  13934. }, elesArray[j]);
  13935. _jsons2.push(json);
  13936. }
  13937. }
  13938. }
  13939. elements = new Collection(cy, _jsons2);
  13940. }
  13941. // specify options for one element
  13942. else {
  13943. var _json = opts;
  13944. elements = new Element(cy, _json).collection();
  13945. }
  13946. return elements;
  13947. },
  13948. remove: function remove(collection) {
  13949. if (elementOrCollection(collection)) ; else if (string(collection)) {
  13950. var selector = collection;
  13951. collection = this.$(selector);
  13952. }
  13953. return collection.remove();
  13954. }
  13955. };
  13956. /* global Float32Array */
  13957. /*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
  13958. function generateCubicBezier(mX1, mY1, mX2, mY2) {
  13959. var NEWTON_ITERATIONS = 4,
  13960. NEWTON_MIN_SLOPE = 0.001,
  13961. SUBDIVISION_PRECISION = 0.0000001,
  13962. SUBDIVISION_MAX_ITERATIONS = 10,
  13963. kSplineTableSize = 11,
  13964. kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
  13965. float32ArraySupported = typeof Float32Array !== 'undefined';
  13966. /* Must contain four arguments. */
  13967. if (arguments.length !== 4) {
  13968. return false;
  13969. }
  13970. /* Arguments must be numbers. */
  13971. for (var i = 0; i < 4; ++i) {
  13972. if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
  13973. return false;
  13974. }
  13975. }
  13976. /* X values must be in the [0, 1] range. */
  13977. mX1 = Math.min(mX1, 1);
  13978. mX2 = Math.min(mX2, 1);
  13979. mX1 = Math.max(mX1, 0);
  13980. mX2 = Math.max(mX2, 0);
  13981. var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  13982. function A(aA1, aA2) {
  13983. return 1.0 - 3.0 * aA2 + 3.0 * aA1;
  13984. }
  13985. function B(aA1, aA2) {
  13986. return 3.0 * aA2 - 6.0 * aA1;
  13987. }
  13988. function C(aA1) {
  13989. return 3.0 * aA1;
  13990. }
  13991. function calcBezier(aT, aA1, aA2) {
  13992. return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  13993. }
  13994. function getSlope(aT, aA1, aA2) {
  13995. return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  13996. }
  13997. function newtonRaphsonIterate(aX, aGuessT) {
  13998. for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {
  13999. var currentSlope = getSlope(aGuessT, mX1, mX2);
  14000. if (currentSlope === 0.0) {
  14001. return aGuessT;
  14002. }
  14003. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  14004. aGuessT -= currentX / currentSlope;
  14005. }
  14006. return aGuessT;
  14007. }
  14008. function calcSampleValues() {
  14009. for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {
  14010. mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);
  14011. }
  14012. }
  14013. function binarySubdivide(aX, aA, aB) {
  14014. var currentX,
  14015. currentT,
  14016. i = 0;
  14017. do {
  14018. currentT = aA + (aB - aA) / 2.0;
  14019. currentX = calcBezier(currentT, mX1, mX2) - aX;
  14020. if (currentX > 0.0) {
  14021. aB = currentT;
  14022. } else {
  14023. aA = currentT;
  14024. }
  14025. } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
  14026. return currentT;
  14027. }
  14028. function getTForX(aX) {
  14029. var intervalStart = 0.0,
  14030. currentSample = 1,
  14031. lastSample = kSplineTableSize - 1;
  14032. for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
  14033. intervalStart += kSampleStepSize;
  14034. }
  14035. --currentSample;
  14036. var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),
  14037. guessForT = intervalStart + dist * kSampleStepSize,
  14038. initialSlope = getSlope(guessForT, mX1, mX2);
  14039. if (initialSlope >= NEWTON_MIN_SLOPE) {
  14040. return newtonRaphsonIterate(aX, guessForT);
  14041. } else if (initialSlope === 0.0) {
  14042. return guessForT;
  14043. } else {
  14044. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
  14045. }
  14046. }
  14047. var _precomputed = false;
  14048. function precompute() {
  14049. _precomputed = true;
  14050. if (mX1 !== mY1 || mX2 !== mY2) {
  14051. calcSampleValues();
  14052. }
  14053. }
  14054. var f = function f(aX) {
  14055. if (!_precomputed) {
  14056. precompute();
  14057. }
  14058. if (mX1 === mY1 && mX2 === mY2) {
  14059. return aX;
  14060. }
  14061. if (aX === 0) {
  14062. return 0;
  14063. }
  14064. if (aX === 1) {
  14065. return 1;
  14066. }
  14067. return calcBezier(getTForX(aX), mY1, mY2);
  14068. };
  14069. f.getControlPoints = function () {
  14070. return [{
  14071. x: mX1,
  14072. y: mY1
  14073. }, {
  14074. x: mX2,
  14075. y: mY2
  14076. }];
  14077. };
  14078. var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
  14079. f.toString = function () {
  14080. return str;
  14081. };
  14082. return f;
  14083. }
  14084. /*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
  14085. /* 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
  14086. then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
  14087. var generateSpringRK4 = function () {
  14088. function springAccelerationForState(state) {
  14089. return -state.tension * state.x - state.friction * state.v;
  14090. }
  14091. function springEvaluateStateWithDerivative(initialState, dt, derivative) {
  14092. var state = {
  14093. x: initialState.x + derivative.dx * dt,
  14094. v: initialState.v + derivative.dv * dt,
  14095. tension: initialState.tension,
  14096. friction: initialState.friction
  14097. };
  14098. return {
  14099. dx: state.v,
  14100. dv: springAccelerationForState(state)
  14101. };
  14102. }
  14103. function springIntegrateState(state, dt) {
  14104. var a = {
  14105. dx: state.v,
  14106. dv: springAccelerationForState(state)
  14107. },
  14108. b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
  14109. c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
  14110. d = springEvaluateStateWithDerivative(state, dt, c),
  14111. dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
  14112. dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
  14113. state.x = state.x + dxdt * dt;
  14114. state.v = state.v + dvdt * dt;
  14115. return state;
  14116. }
  14117. return function springRK4Factory(tension, friction, duration) {
  14118. var initState = {
  14119. x: -1,
  14120. v: 0,
  14121. tension: null,
  14122. friction: null
  14123. },
  14124. path = [0],
  14125. time_lapsed = 0,
  14126. tolerance = 1 / 10000,
  14127. DT = 16 / 1000,
  14128. have_duration,
  14129. dt,
  14130. last_state;
  14131. tension = parseFloat(tension) || 500;
  14132. friction = parseFloat(friction) || 20;
  14133. duration = duration || null;
  14134. initState.tension = tension;
  14135. initState.friction = friction;
  14136. have_duration = duration !== null;
  14137. /* Calculate the actual time it takes for this animation to complete with the provided conditions. */
  14138. if (have_duration) {
  14139. /* Run the simulation without a duration. */
  14140. time_lapsed = springRK4Factory(tension, friction);
  14141. /* Compute the adjusted time delta. */
  14142. dt = time_lapsed / duration * DT;
  14143. } else {
  14144. dt = DT;
  14145. }
  14146. for (;;) {
  14147. /* Next/step function .*/
  14148. last_state = springIntegrateState(last_state || initState, dt);
  14149. /* Store the position. */
  14150. path.push(1 + last_state.x);
  14151. time_lapsed += 16;
  14152. /* If the change threshold is reached, break. */
  14153. if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
  14154. break;
  14155. }
  14156. }
  14157. /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
  14158. computed path and returns a snapshot of the position according to a given percentComplete. */
  14159. return !have_duration ? time_lapsed : function (percentComplete) {
  14160. return path[percentComplete * (path.length - 1) | 0];
  14161. };
  14162. };
  14163. }();
  14164. var cubicBezier = function cubicBezier(t1, p1, t2, p2) {
  14165. var bezier = generateCubicBezier(t1, p1, t2, p2);
  14166. return function (start, end, percent) {
  14167. return start + (end - start) * bezier(percent);
  14168. };
  14169. };
  14170. var easings = {
  14171. 'linear': function linear(start, end, percent) {
  14172. return start + (end - start) * percent;
  14173. },
  14174. // default easings
  14175. 'ease': cubicBezier(0.25, 0.1, 0.25, 1),
  14176. 'ease-in': cubicBezier(0.42, 0, 1, 1),
  14177. 'ease-out': cubicBezier(0, 0, 0.58, 1),
  14178. 'ease-in-out': cubicBezier(0.42, 0, 0.58, 1),
  14179. // sine
  14180. 'ease-in-sine': cubicBezier(0.47, 0, 0.745, 0.715),
  14181. 'ease-out-sine': cubicBezier(0.39, 0.575, 0.565, 1),
  14182. 'ease-in-out-sine': cubicBezier(0.445, 0.05, 0.55, 0.95),
  14183. // quad
  14184. 'ease-in-quad': cubicBezier(0.55, 0.085, 0.68, 0.53),
  14185. 'ease-out-quad': cubicBezier(0.25, 0.46, 0.45, 0.94),
  14186. 'ease-in-out-quad': cubicBezier(0.455, 0.03, 0.515, 0.955),
  14187. // cubic
  14188. 'ease-in-cubic': cubicBezier(0.55, 0.055, 0.675, 0.19),
  14189. 'ease-out-cubic': cubicBezier(0.215, 0.61, 0.355, 1),
  14190. 'ease-in-out-cubic': cubicBezier(0.645, 0.045, 0.355, 1),
  14191. // quart
  14192. 'ease-in-quart': cubicBezier(0.895, 0.03, 0.685, 0.22),
  14193. 'ease-out-quart': cubicBezier(0.165, 0.84, 0.44, 1),
  14194. 'ease-in-out-quart': cubicBezier(0.77, 0, 0.175, 1),
  14195. // quint
  14196. 'ease-in-quint': cubicBezier(0.755, 0.05, 0.855, 0.06),
  14197. 'ease-out-quint': cubicBezier(0.23, 1, 0.32, 1),
  14198. 'ease-in-out-quint': cubicBezier(0.86, 0, 0.07, 1),
  14199. // expo
  14200. 'ease-in-expo': cubicBezier(0.95, 0.05, 0.795, 0.035),
  14201. 'ease-out-expo': cubicBezier(0.19, 1, 0.22, 1),
  14202. 'ease-in-out-expo': cubicBezier(1, 0, 0, 1),
  14203. // circ
  14204. 'ease-in-circ': cubicBezier(0.6, 0.04, 0.98, 0.335),
  14205. 'ease-out-circ': cubicBezier(0.075, 0.82, 0.165, 1),
  14206. 'ease-in-out-circ': cubicBezier(0.785, 0.135, 0.15, 0.86),
  14207. // user param easings...
  14208. 'spring': function spring(tension, friction, duration) {
  14209. if (duration === 0) {
  14210. // can't get a spring w/ duration 0
  14211. return easings.linear; // duration 0 => jump to end so impl doesn't matter
  14212. }
  14213. var spring = generateSpringRK4(tension, friction, duration);
  14214. return function (start, end, percent) {
  14215. return start + (end - start) * spring(percent);
  14216. };
  14217. },
  14218. 'cubic-bezier': cubicBezier
  14219. };
  14220. function getEasedValue(type, start, end, percent, easingFn) {
  14221. if (percent === 1) {
  14222. return end;
  14223. }
  14224. if (start === end) {
  14225. return end;
  14226. }
  14227. var val = easingFn(start, end, percent);
  14228. if (type == null) {
  14229. return val;
  14230. }
  14231. if (type.roundValue || type.color) {
  14232. val = Math.round(val);
  14233. }
  14234. if (type.min !== undefined) {
  14235. val = Math.max(val, type.min);
  14236. }
  14237. if (type.max !== undefined) {
  14238. val = Math.min(val, type.max);
  14239. }
  14240. return val;
  14241. }
  14242. function getValue(prop, spec) {
  14243. if (prop.pfValue != null || prop.value != null) {
  14244. if (prop.pfValue != null && (spec == null || spec.type.units !== '%')) {
  14245. return prop.pfValue;
  14246. } else {
  14247. return prop.value;
  14248. }
  14249. } else {
  14250. return prop;
  14251. }
  14252. }
  14253. function ease(startProp, endProp, percent, easingFn, propSpec) {
  14254. var type = propSpec != null ? propSpec.type : null;
  14255. if (percent < 0) {
  14256. percent = 0;
  14257. } else if (percent > 1) {
  14258. percent = 1;
  14259. }
  14260. var start = getValue(startProp, propSpec);
  14261. var end = getValue(endProp, propSpec);
  14262. if (number$1(start) && number$1(end)) {
  14263. return getEasedValue(type, start, end, percent, easingFn);
  14264. } else if (array(start) && array(end)) {
  14265. var easedArr = [];
  14266. for (var i = 0; i < end.length; i++) {
  14267. var si = start[i];
  14268. var ei = end[i];
  14269. if (si != null && ei != null) {
  14270. var val = getEasedValue(type, si, ei, percent, easingFn);
  14271. easedArr.push(val);
  14272. } else {
  14273. easedArr.push(ei);
  14274. }
  14275. }
  14276. return easedArr;
  14277. }
  14278. return undefined;
  14279. }
  14280. function step$1(self, ani, now, isCore) {
  14281. var isEles = !isCore;
  14282. var _p = self._private;
  14283. var ani_p = ani._private;
  14284. var pEasing = ani_p.easing;
  14285. var startTime = ani_p.startTime;
  14286. var cy = isCore ? self : self.cy();
  14287. var style = cy.style();
  14288. if (!ani_p.easingImpl) {
  14289. if (pEasing == null) {
  14290. // use default
  14291. ani_p.easingImpl = easings['linear'];
  14292. } else {
  14293. // then define w/ name
  14294. var easingVals;
  14295. if (string(pEasing)) {
  14296. var easingProp = style.parse('transition-timing-function', pEasing);
  14297. easingVals = easingProp.value;
  14298. } else {
  14299. // then assume preparsed array
  14300. easingVals = pEasing;
  14301. }
  14302. var name, args;
  14303. if (string(easingVals)) {
  14304. name = easingVals;
  14305. args = [];
  14306. } else {
  14307. name = easingVals[1];
  14308. args = easingVals.slice(2).map(function (n) {
  14309. return +n;
  14310. });
  14311. }
  14312. if (args.length > 0) {
  14313. // create with args
  14314. if (name === 'spring') {
  14315. args.push(ani_p.duration); // need duration to generate spring
  14316. }
  14317. ani_p.easingImpl = easings[name].apply(null, args);
  14318. } else {
  14319. // static impl by name
  14320. ani_p.easingImpl = easings[name];
  14321. }
  14322. }
  14323. }
  14324. var easing = ani_p.easingImpl;
  14325. var percent;
  14326. if (ani_p.duration === 0) {
  14327. percent = 1;
  14328. } else {
  14329. percent = (now - startTime) / ani_p.duration;
  14330. }
  14331. if (ani_p.applying) {
  14332. percent = ani_p.progress;
  14333. }
  14334. if (percent < 0) {
  14335. percent = 0;
  14336. } else if (percent > 1) {
  14337. percent = 1;
  14338. }
  14339. if (ani_p.delay == null) {
  14340. // then update
  14341. var startPos = ani_p.startPosition;
  14342. var endPos = ani_p.position;
  14343. if (endPos && isEles && !self.locked()) {
  14344. var newPos = {};
  14345. if (valid(startPos.x, endPos.x)) {
  14346. newPos.x = ease(startPos.x, endPos.x, percent, easing);
  14347. }
  14348. if (valid(startPos.y, endPos.y)) {
  14349. newPos.y = ease(startPos.y, endPos.y, percent, easing);
  14350. }
  14351. self.position(newPos);
  14352. }
  14353. var startPan = ani_p.startPan;
  14354. var endPan = ani_p.pan;
  14355. var pan = _p.pan;
  14356. var animatingPan = endPan != null && isCore;
  14357. if (animatingPan) {
  14358. if (valid(startPan.x, endPan.x)) {
  14359. pan.x = ease(startPan.x, endPan.x, percent, easing);
  14360. }
  14361. if (valid(startPan.y, endPan.y)) {
  14362. pan.y = ease(startPan.y, endPan.y, percent, easing);
  14363. }
  14364. self.emit('pan');
  14365. }
  14366. var startZoom = ani_p.startZoom;
  14367. var endZoom = ani_p.zoom;
  14368. var animatingZoom = endZoom != null && isCore;
  14369. if (animatingZoom) {
  14370. if (valid(startZoom, endZoom)) {
  14371. _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);
  14372. }
  14373. self.emit('zoom');
  14374. }
  14375. if (animatingPan || animatingZoom) {
  14376. self.emit('viewport');
  14377. }
  14378. var props = ani_p.style;
  14379. if (props && props.length > 0 && isEles) {
  14380. for (var i = 0; i < props.length; i++) {
  14381. var prop = props[i];
  14382. var _name = prop.name;
  14383. var end = prop;
  14384. var start = ani_p.startStyle[_name];
  14385. var propSpec = style.properties[start.name];
  14386. var easedVal = ease(start, end, percent, easing, propSpec);
  14387. style.overrideBypass(self, _name, easedVal);
  14388. } // for props
  14389. self.emit('style');
  14390. } // if
  14391. }
  14392. ani_p.progress = percent;
  14393. return percent;
  14394. }
  14395. function valid(start, end) {
  14396. if (start == null || end == null) {
  14397. return false;
  14398. }
  14399. if (number$1(start) && number$1(end)) {
  14400. return true;
  14401. } else if (start && end) {
  14402. return true;
  14403. }
  14404. return false;
  14405. }
  14406. function startAnimation(self, ani, now, isCore) {
  14407. var ani_p = ani._private;
  14408. ani_p.started = true;
  14409. ani_p.startTime = now - ani_p.progress * ani_p.duration;
  14410. }
  14411. function stepAll(now, cy) {
  14412. var eles = cy._private.aniEles;
  14413. var doneEles = [];
  14414. function stepOne(ele, isCore) {
  14415. var _p = ele._private;
  14416. var current = _p.animation.current;
  14417. var queue = _p.animation.queue;
  14418. var ranAnis = false;
  14419. // if nothing currently animating, get something from the queue
  14420. if (current.length === 0) {
  14421. var next = queue.shift();
  14422. if (next) {
  14423. current.push(next);
  14424. }
  14425. }
  14426. var callbacks = function callbacks(_callbacks) {
  14427. for (var j = _callbacks.length - 1; j >= 0; j--) {
  14428. var cb = _callbacks[j];
  14429. cb();
  14430. }
  14431. _callbacks.splice(0, _callbacks.length);
  14432. };
  14433. // step and remove if done
  14434. for (var i = current.length - 1; i >= 0; i--) {
  14435. var ani = current[i];
  14436. var ani_p = ani._private;
  14437. if (ani_p.stopped) {
  14438. current.splice(i, 1);
  14439. ani_p.hooked = false;
  14440. ani_p.playing = false;
  14441. ani_p.started = false;
  14442. callbacks(ani_p.frames);
  14443. continue;
  14444. }
  14445. if (!ani_p.playing && !ani_p.applying) {
  14446. continue;
  14447. }
  14448. // an apply() while playing shouldn't do anything
  14449. if (ani_p.playing && ani_p.applying) {
  14450. ani_p.applying = false;
  14451. }
  14452. if (!ani_p.started) {
  14453. startAnimation(ele, ani, now);
  14454. }
  14455. step$1(ele, ani, now, isCore);
  14456. if (ani_p.applying) {
  14457. ani_p.applying = false;
  14458. }
  14459. callbacks(ani_p.frames);
  14460. if (ani_p.step != null) {
  14461. ani_p.step(now);
  14462. }
  14463. if (ani.completed()) {
  14464. current.splice(i, 1);
  14465. ani_p.hooked = false;
  14466. ani_p.playing = false;
  14467. ani_p.started = false;
  14468. callbacks(ani_p.completes);
  14469. }
  14470. ranAnis = true;
  14471. }
  14472. if (!isCore && current.length === 0 && queue.length === 0) {
  14473. doneEles.push(ele);
  14474. }
  14475. return ranAnis;
  14476. } // stepElement
  14477. // handle all eles
  14478. var ranEleAni = false;
  14479. for (var e = 0; e < eles.length; e++) {
  14480. var ele = eles[e];
  14481. var handledThisEle = stepOne(ele);
  14482. ranEleAni = ranEleAni || handledThisEle;
  14483. } // each element
  14484. var ranCoreAni = stepOne(cy, true);
  14485. // notify renderer
  14486. if (ranEleAni || ranCoreAni) {
  14487. if (eles.length > 0) {
  14488. cy.notify('draw', eles);
  14489. } else {
  14490. cy.notify('draw');
  14491. }
  14492. }
  14493. // remove elements from list of currently animating if its queues are empty
  14494. eles.unmerge(doneEles);
  14495. cy.emit('step');
  14496. } // stepAll
  14497. var corefn$8 = {
  14498. // pull in animation functions
  14499. animate: define.animate(),
  14500. animation: define.animation(),
  14501. animated: define.animated(),
  14502. clearQueue: define.clearQueue(),
  14503. delay: define.delay(),
  14504. delayAnimation: define.delayAnimation(),
  14505. stop: define.stop(),
  14506. addToAnimationPool: function addToAnimationPool(eles) {
  14507. var cy = this;
  14508. if (!cy.styleEnabled()) {
  14509. return;
  14510. } // save cycles when no style used
  14511. cy._private.aniEles.merge(eles);
  14512. },
  14513. stopAnimationLoop: function stopAnimationLoop() {
  14514. this._private.animationsRunning = false;
  14515. },
  14516. startAnimationLoop: function startAnimationLoop() {
  14517. var cy = this;
  14518. cy._private.animationsRunning = true;
  14519. if (!cy.styleEnabled()) {
  14520. return;
  14521. } // save cycles when no style used
  14522. // NB the animation loop will exec in headless environments if style enabled
  14523. // and explicit cy.destroy() is necessary to stop the loop
  14524. function headlessStep() {
  14525. if (!cy._private.animationsRunning) {
  14526. return;
  14527. }
  14528. requestAnimationFrame(function animationStep(now) {
  14529. stepAll(now, cy);
  14530. headlessStep();
  14531. });
  14532. }
  14533. var renderer = cy.renderer();
  14534. if (renderer && renderer.beforeRender) {
  14535. // let the renderer schedule animations
  14536. renderer.beforeRender(function rendererAnimationStep(willDraw, now) {
  14537. stepAll(now, cy);
  14538. }, renderer.beforeRenderPriorities.animations);
  14539. } else {
  14540. // manage the animation loop ourselves
  14541. headlessStep(); // first call
  14542. }
  14543. }
  14544. };
  14545. var emitterOptions = {
  14546. qualifierCompare: function qualifierCompare(selector1, selector2) {
  14547. if (selector1 == null || selector2 == null) {
  14548. return selector1 == null && selector2 == null;
  14549. } else {
  14550. return selector1.sameText(selector2);
  14551. }
  14552. },
  14553. eventMatches: function eventMatches(cy, listener, eventObj) {
  14554. var selector = listener.qualifier;
  14555. if (selector != null) {
  14556. return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
  14557. }
  14558. return true;
  14559. },
  14560. addEventFields: function addEventFields(cy, evt) {
  14561. evt.cy = cy;
  14562. evt.target = cy;
  14563. },
  14564. callbackContext: function callbackContext(cy, listener, eventObj) {
  14565. return listener.qualifier != null ? eventObj.target : cy;
  14566. }
  14567. };
  14568. var argSelector = function argSelector(arg) {
  14569. if (string(arg)) {
  14570. return new Selector(arg);
  14571. } else {
  14572. return arg;
  14573. }
  14574. };
  14575. var elesfn = {
  14576. createEmitter: function createEmitter() {
  14577. var _p = this._private;
  14578. if (!_p.emitter) {
  14579. _p.emitter = new Emitter(emitterOptions, this);
  14580. }
  14581. return this;
  14582. },
  14583. emitter: function emitter() {
  14584. return this._private.emitter;
  14585. },
  14586. on: function on(events, selector, callback) {
  14587. this.emitter().on(events, argSelector(selector), callback);
  14588. return this;
  14589. },
  14590. removeListener: function removeListener(events, selector, callback) {
  14591. this.emitter().removeListener(events, argSelector(selector), callback);
  14592. return this;
  14593. },
  14594. removeAllListeners: function removeAllListeners() {
  14595. this.emitter().removeAllListeners();
  14596. return this;
  14597. },
  14598. one: function one(events, selector, callback) {
  14599. this.emitter().one(events, argSelector(selector), callback);
  14600. return this;
  14601. },
  14602. once: function once(events, selector, callback) {
  14603. this.emitter().one(events, argSelector(selector), callback);
  14604. return this;
  14605. },
  14606. emit: function emit(events, extraParams) {
  14607. this.emitter().emit(events, extraParams);
  14608. return this;
  14609. },
  14610. emitAndNotify: function emitAndNotify(event, eles) {
  14611. this.emit(event);
  14612. this.notify(event, eles);
  14613. return this;
  14614. }
  14615. };
  14616. define.eventAliasesOn(elesfn);
  14617. var corefn$7 = {
  14618. png: function png(options) {
  14619. var renderer = this._private.renderer;
  14620. options = options || {};
  14621. return renderer.png(options);
  14622. },
  14623. jpg: function jpg(options) {
  14624. var renderer = this._private.renderer;
  14625. options = options || {};
  14626. options.bg = options.bg || '#fff';
  14627. return renderer.jpg(options);
  14628. }
  14629. };
  14630. corefn$7.jpeg = corefn$7.jpg;
  14631. var corefn$6 = {
  14632. layout: function layout(options) {
  14633. var cy = this;
  14634. if (options == null) {
  14635. error('Layout options must be specified to make a layout');
  14636. return;
  14637. }
  14638. if (options.name == null) {
  14639. error('A `name` must be specified to make a layout');
  14640. return;
  14641. }
  14642. var name = options.name;
  14643. var Layout = cy.extension('layout', name);
  14644. if (Layout == null) {
  14645. error('No such layout `' + name + '` found. Did you forget to import it and `cytoscape.use()` it?');
  14646. return;
  14647. }
  14648. var eles;
  14649. if (string(options.eles)) {
  14650. eles = cy.$(options.eles);
  14651. } else {
  14652. eles = options.eles != null ? options.eles : cy.$();
  14653. }
  14654. var layout = new Layout(extend({}, options, {
  14655. cy: cy,
  14656. eles: eles
  14657. }));
  14658. return layout;
  14659. }
  14660. };
  14661. corefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;
  14662. var corefn$5 = {
  14663. notify: function notify(eventName, eventEles) {
  14664. var _p = this._private;
  14665. if (this.batching()) {
  14666. _p.batchNotifications = _p.batchNotifications || {};
  14667. var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();
  14668. if (eventEles != null) {
  14669. eles.merge(eventEles);
  14670. }
  14671. return; // notifications are disabled during batching
  14672. }
  14673. if (!_p.notificationsEnabled) {
  14674. return;
  14675. } // exit on disabled
  14676. var renderer = this.renderer();
  14677. // exit if destroy() called on core or renderer in between frames #1499 #1528
  14678. if (this.destroyed() || !renderer) {
  14679. return;
  14680. }
  14681. renderer.notify(eventName, eventEles);
  14682. },
  14683. notifications: function notifications(bool) {
  14684. var p = this._private;
  14685. if (bool === undefined) {
  14686. return p.notificationsEnabled;
  14687. } else {
  14688. p.notificationsEnabled = bool ? true : false;
  14689. }
  14690. return this;
  14691. },
  14692. noNotifications: function noNotifications(callback) {
  14693. this.notifications(false);
  14694. callback();
  14695. this.notifications(true);
  14696. },
  14697. batching: function batching() {
  14698. return this._private.batchCount > 0;
  14699. },
  14700. startBatch: function startBatch() {
  14701. var _p = this._private;
  14702. if (_p.batchCount == null) {
  14703. _p.batchCount = 0;
  14704. }
  14705. if (_p.batchCount === 0) {
  14706. _p.batchStyleEles = this.collection();
  14707. _p.batchNotifications = {};
  14708. }
  14709. _p.batchCount++;
  14710. return this;
  14711. },
  14712. endBatch: function endBatch() {
  14713. var _p = this._private;
  14714. if (_p.batchCount === 0) {
  14715. return this;
  14716. }
  14717. _p.batchCount--;
  14718. if (_p.batchCount === 0) {
  14719. // update style for dirty eles
  14720. _p.batchStyleEles.updateStyle();
  14721. var renderer = this.renderer();
  14722. // notify the renderer of queued eles and event types
  14723. Object.keys(_p.batchNotifications).forEach(function (eventName) {
  14724. var eles = _p.batchNotifications[eventName];
  14725. if (eles.empty()) {
  14726. renderer.notify(eventName);
  14727. } else {
  14728. renderer.notify(eventName, eles);
  14729. }
  14730. });
  14731. }
  14732. return this;
  14733. },
  14734. batch: function batch(callback) {
  14735. this.startBatch();
  14736. callback();
  14737. this.endBatch();
  14738. return this;
  14739. },
  14740. // for backwards compatibility
  14741. batchData: function batchData(map) {
  14742. var cy = this;
  14743. return this.batch(function () {
  14744. var ids = Object.keys(map);
  14745. for (var i = 0; i < ids.length; i++) {
  14746. var id = ids[i];
  14747. var data = map[id];
  14748. var ele = cy.getElementById(id);
  14749. ele.data(data);
  14750. }
  14751. });
  14752. }
  14753. };
  14754. var rendererDefaults = defaults$g({
  14755. hideEdgesOnViewport: false,
  14756. textureOnViewport: false,
  14757. motionBlur: false,
  14758. motionBlurOpacity: 0.05,
  14759. pixelRatio: undefined,
  14760. desktopTapThreshold: 4,
  14761. touchTapThreshold: 8,
  14762. wheelSensitivity: 1,
  14763. debug: false,
  14764. showFps: false,
  14765. // webgl options
  14766. webgl: false,
  14767. webglDebug: false,
  14768. webglDebugShowAtlases: false,
  14769. // defaults good for mobile
  14770. webglTexSize: 2048,
  14771. webglTexRows: 36,
  14772. webglTexRowsNodes: 18,
  14773. webglBatchSize: 2048,
  14774. webglTexPerBatch: 14,
  14775. webglBgColor: [255, 255, 255]
  14776. });
  14777. var corefn$4 = {
  14778. renderTo: function renderTo(context, zoom, pan, pxRatio) {
  14779. var r = this._private.renderer;
  14780. r.renderTo(context, zoom, pan, pxRatio);
  14781. return this;
  14782. },
  14783. renderer: function renderer() {
  14784. return this._private.renderer;
  14785. },
  14786. forceRender: function forceRender() {
  14787. this.notify('draw');
  14788. return this;
  14789. },
  14790. resize: function resize() {
  14791. this.invalidateSize();
  14792. this.emitAndNotify('resize');
  14793. return this;
  14794. },
  14795. initRenderer: function initRenderer(options) {
  14796. var cy = this;
  14797. var RendererProto = cy.extension('renderer', options.name);
  14798. if (RendererProto == null) {
  14799. error("Can not initialise: No such renderer `".concat(options.name, "` found. Did you forget to import it and `cytoscape.use()` it?"));
  14800. return;
  14801. }
  14802. if (options.wheelSensitivity !== undefined) {
  14803. 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.");
  14804. }
  14805. var rOpts = rendererDefaults(options);
  14806. rOpts.cy = cy;
  14807. cy._private.renderer = new RendererProto(rOpts);
  14808. this.notify('init');
  14809. },
  14810. destroyRenderer: function destroyRenderer() {
  14811. var cy = this;
  14812. cy.notify('destroy'); // destroy the renderer
  14813. var domEle = cy.container();
  14814. if (domEle) {
  14815. domEle._cyreg = null;
  14816. while (domEle.childNodes.length > 0) {
  14817. domEle.removeChild(domEle.childNodes[0]);
  14818. }
  14819. }
  14820. cy._private.renderer = null; // to be extra safe, remove the ref
  14821. cy.mutableElements().forEach(function (ele) {
  14822. var _p = ele._private;
  14823. _p.rscratch = {};
  14824. _p.rstyle = {};
  14825. _p.animation.current = [];
  14826. _p.animation.queue = [];
  14827. });
  14828. },
  14829. onRender: function onRender(fn) {
  14830. return this.on('render', fn);
  14831. },
  14832. offRender: function offRender(fn) {
  14833. return this.off('render', fn);
  14834. }
  14835. };
  14836. corefn$4.invalidateDimensions = corefn$4.resize;
  14837. var corefn$3 = {
  14838. // get a collection
  14839. // - empty collection on no args
  14840. // - collection of elements in the graph on selector arg
  14841. // - guarantee a returned collection when elements or collection specified
  14842. collection: function collection(eles, opts) {
  14843. if (string(eles)) {
  14844. return this.$(eles);
  14845. } else if (elementOrCollection(eles)) {
  14846. return eles.collection();
  14847. } else if (array(eles)) {
  14848. if (!opts) {
  14849. opts = {};
  14850. }
  14851. return new Collection(this, eles, opts.unique, opts.removed);
  14852. }
  14853. return new Collection(this);
  14854. },
  14855. nodes: function nodes(selector) {
  14856. var nodes = this.$(function (ele) {
  14857. return ele.isNode();
  14858. });
  14859. if (selector) {
  14860. return nodes.filter(selector);
  14861. }
  14862. return nodes;
  14863. },
  14864. edges: function edges(selector) {
  14865. var edges = this.$(function (ele) {
  14866. return ele.isEdge();
  14867. });
  14868. if (selector) {
  14869. return edges.filter(selector);
  14870. }
  14871. return edges;
  14872. },
  14873. // search the graph like jQuery
  14874. $: function $(selector) {
  14875. var eles = this._private.elements;
  14876. if (selector) {
  14877. return eles.filter(selector);
  14878. } else {
  14879. return eles.spawnSelf();
  14880. }
  14881. },
  14882. mutableElements: function mutableElements() {
  14883. return this._private.elements;
  14884. }
  14885. };
  14886. // aliases
  14887. corefn$3.elements = corefn$3.filter = corefn$3.$;
  14888. var styfn$8 = {};
  14889. // keys for style blocks, e.g. ttfftt
  14890. var TRUE = 't';
  14891. var FALSE = 'f';
  14892. // (potentially expensive calculation)
  14893. // apply the style to the element based on
  14894. // - its bypass
  14895. // - what selectors match it
  14896. styfn$8.apply = function (eles) {
  14897. var self = this;
  14898. var _p = self._private;
  14899. var cy = _p.cy;
  14900. var updatedEles = cy.collection();
  14901. for (var ie = 0; ie < eles.length; ie++) {
  14902. var ele = eles[ie];
  14903. var cxtMeta = self.getContextMeta(ele);
  14904. if (cxtMeta.empty) {
  14905. continue;
  14906. }
  14907. var cxtStyle = self.getContextStyle(cxtMeta);
  14908. var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);
  14909. if (ele._private.appliedInitStyle) {
  14910. self.updateTransitions(ele, app.diffProps);
  14911. } else {
  14912. ele._private.appliedInitStyle = true;
  14913. }
  14914. var hintsDiff = self.updateStyleHints(ele);
  14915. if (hintsDiff) {
  14916. updatedEles.push(ele);
  14917. }
  14918. } // for elements
  14919. return updatedEles;
  14920. };
  14921. styfn$8.getPropertiesDiff = function (oldCxtKey, newCxtKey) {
  14922. var self = this;
  14923. var cache = self._private.propDiffs = self._private.propDiffs || {};
  14924. var dualCxtKey = oldCxtKey + '-' + newCxtKey;
  14925. var cachedVal = cache[dualCxtKey];
  14926. if (cachedVal) {
  14927. return cachedVal;
  14928. }
  14929. var diffProps = [];
  14930. var addedProp = {};
  14931. for (var i = 0; i < self.length; i++) {
  14932. var cxt = self[i];
  14933. var oldHasCxt = oldCxtKey[i] === TRUE;
  14934. var newHasCxt = newCxtKey[i] === TRUE;
  14935. var cxtHasDiffed = oldHasCxt !== newHasCxt;
  14936. var cxtHasMappedProps = cxt.mappedProperties.length > 0;
  14937. if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {
  14938. var props = undefined;
  14939. if (cxtHasDiffed && cxtHasMappedProps) {
  14940. props = cxt.properties; // suffices b/c mappedProperties is a subset of properties
  14941. } else if (cxtHasDiffed) {
  14942. props = cxt.properties; // need to check them all
  14943. } else if (cxtHasMappedProps) {
  14944. props = cxt.mappedProperties; // only need to check mapped
  14945. }
  14946. for (var j = 0; j < props.length; j++) {
  14947. var prop = props[j];
  14948. var name = prop.name;
  14949. // if a later context overrides this property, then the fact that this context has switched/diffed doesn't matter
  14950. // (semi expensive check since it makes this function O(n^2) on context length, but worth it since overall result
  14951. // is cached)
  14952. var laterCxtOverrides = false;
  14953. for (var k = i + 1; k < self.length; k++) {
  14954. var laterCxt = self[k];
  14955. var hasLaterCxt = newCxtKey[k] === TRUE;
  14956. if (!hasLaterCxt) {
  14957. continue;
  14958. } // can't override unless the context is active
  14959. laterCxtOverrides = laterCxt.properties[prop.name] != null;
  14960. if (laterCxtOverrides) {
  14961. break;
  14962. } // exit early as long as one later context overrides
  14963. }
  14964. if (!addedProp[name] && !laterCxtOverrides) {
  14965. addedProp[name] = true;
  14966. diffProps.push(name);
  14967. }
  14968. } // for props
  14969. } // if
  14970. } // for contexts
  14971. cache[dualCxtKey] = diffProps;
  14972. return diffProps;
  14973. };
  14974. styfn$8.getContextMeta = function (ele) {
  14975. var self = this;
  14976. var cxtKey = '';
  14977. var diffProps;
  14978. var prevKey = ele._private.styleCxtKey || '';
  14979. // get the cxt key
  14980. for (var i = 0; i < self.length; i++) {
  14981. var context = self[i];
  14982. var contextSelectorMatches = context.selector && context.selector.matches(ele); // NB: context.selector may be null for 'core'
  14983. if (contextSelectorMatches) {
  14984. cxtKey += TRUE;
  14985. } else {
  14986. cxtKey += FALSE;
  14987. }
  14988. } // for context
  14989. diffProps = self.getPropertiesDiff(prevKey, cxtKey);
  14990. ele._private.styleCxtKey = cxtKey;
  14991. return {
  14992. key: cxtKey,
  14993. diffPropNames: diffProps,
  14994. empty: diffProps.length === 0
  14995. };
  14996. };
  14997. // gets a computed ele style object based on matched contexts
  14998. styfn$8.getContextStyle = function (cxtMeta) {
  14999. var cxtKey = cxtMeta.key;
  15000. var self = this;
  15001. var cxtStyles = this._private.contextStyles = this._private.contextStyles || {};
  15002. // if already computed style, returned cached copy
  15003. if (cxtStyles[cxtKey]) {
  15004. return cxtStyles[cxtKey];
  15005. }
  15006. var style = {
  15007. _private: {
  15008. key: cxtKey
  15009. }
  15010. };
  15011. for (var i = 0; i < self.length; i++) {
  15012. var cxt = self[i];
  15013. var hasCxt = cxtKey[i] === TRUE;
  15014. if (!hasCxt) {
  15015. continue;
  15016. }
  15017. for (var j = 0; j < cxt.properties.length; j++) {
  15018. var prop = cxt.properties[j];
  15019. style[prop.name] = prop;
  15020. }
  15021. }
  15022. cxtStyles[cxtKey] = style;
  15023. return style;
  15024. };
  15025. styfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {
  15026. var self = this;
  15027. var diffProps = cxtMeta.diffPropNames;
  15028. var retDiffProps = {};
  15029. var types = self.types;
  15030. for (var i = 0; i < diffProps.length; i++) {
  15031. var diffPropName = diffProps[i];
  15032. var cxtProp = cxtStyle[diffPropName];
  15033. var eleProp = ele.pstyle(diffPropName);
  15034. if (!cxtProp) {
  15035. // no context prop means delete
  15036. if (!eleProp) {
  15037. continue; // no existing prop means nothing needs to be removed
  15038. // nb affects initial application on mapped values like control-point-distances
  15039. } else if (eleProp.bypass) {
  15040. cxtProp = {
  15041. name: diffPropName,
  15042. deleteBypassed: true
  15043. };
  15044. } else {
  15045. cxtProp = {
  15046. name: diffPropName,
  15047. "delete": true
  15048. };
  15049. }
  15050. }
  15051. // save cycles when the context prop doesn't need to be applied
  15052. if (eleProp === cxtProp) {
  15053. continue;
  15054. }
  15055. // save cycles when a mapped context prop doesn't need to be applied
  15056. if (cxtProp.mapped === types.fn // context prop is function mapper
  15057. && eleProp != null // some props can be null even by default (e.g. a prop that overrides another one)
  15058. && eleProp.mapping != null // ele prop is a concrete value from from a mapper
  15059. && eleProp.mapping.value === cxtProp.value // the current prop on the ele is a flat prop value for the function mapper
  15060. ) {
  15061. // NB don't write to cxtProp, as it's shared among eles (stored in stylesheet)
  15062. var mapping = eleProp.mapping; // can write to mapping, as it's a per-ele copy
  15063. var fnValue = mapping.fnValue = cxtProp.value(ele); // temporarily cache the value in case of a miss
  15064. if (fnValue === mapping.prevFnValue) {
  15065. continue;
  15066. }
  15067. }
  15068. var retDiffProp = retDiffProps[diffPropName] = {
  15069. prev: eleProp
  15070. };
  15071. self.applyParsedProperty(ele, cxtProp);
  15072. retDiffProp.next = ele.pstyle(diffPropName);
  15073. if (retDiffProp.next && retDiffProp.next.bypass) {
  15074. retDiffProp.next = retDiffProp.next.bypassed;
  15075. }
  15076. }
  15077. return {
  15078. diffProps: retDiffProps
  15079. };
  15080. };
  15081. styfn$8.updateStyleHints = function (ele) {
  15082. var _p = ele._private;
  15083. var self = this;
  15084. var propNames = self.propertyGroupNames;
  15085. var propGrKeys = self.propertyGroupKeys;
  15086. var propHash = function propHash(ele, propNames, seedKey) {
  15087. return self.getPropertiesHash(ele, propNames, seedKey);
  15088. };
  15089. var oldStyleKey = _p.styleKey;
  15090. if (ele.removed()) {
  15091. return false;
  15092. }
  15093. var isNode = _p.group === 'nodes';
  15094. // get the style key hashes per prop group
  15095. // but lazily -- only use non-default prop values to reduce the number of hashes
  15096. //
  15097. var overriddenStyles = ele._private.style;
  15098. propNames = Object.keys(overriddenStyles);
  15099. for (var i = 0; i < propGrKeys.length; i++) {
  15100. var grKey = propGrKeys[i];
  15101. _p.styleKeys[grKey] = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  15102. }
  15103. var updateGrKey1 = function updateGrKey1(val, grKey) {
  15104. return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);
  15105. };
  15106. var updateGrKey2 = function updateGrKey2(val, grKey) {
  15107. return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);
  15108. };
  15109. var updateGrKey = function updateGrKey(val, grKey) {
  15110. updateGrKey1(val, grKey);
  15111. updateGrKey2(val, grKey);
  15112. };
  15113. var updateGrKeyWStr = function updateGrKeyWStr(strVal, grKey) {
  15114. for (var j = 0; j < strVal.length; j++) {
  15115. var ch = strVal.charCodeAt(j);
  15116. updateGrKey1(ch, grKey);
  15117. updateGrKey2(ch, grKey);
  15118. }
  15119. };
  15120. // - hashing works on 32 bit ints b/c we use bitwise ops
  15121. // - small numbers get cut off (e.g. 0.123 is seen as 0 by the hashing function)
  15122. // - raise up small numbers so more significant digits are seen by hashing
  15123. // - make small numbers larger than a normal value to avoid collisions
  15124. // - works in practice and it's relatively cheap
  15125. var N = 2000000000;
  15126. var cleanNum = function cleanNum(val) {
  15127. return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;
  15128. };
  15129. for (var _i = 0; _i < propNames.length; _i++) {
  15130. var name = propNames[_i];
  15131. var parsedProp = overriddenStyles[name];
  15132. if (parsedProp == null) {
  15133. continue;
  15134. }
  15135. var propInfo = this.properties[name];
  15136. var type = propInfo.type;
  15137. var _grKey = propInfo.groupKey;
  15138. var normalizedNumberVal = undefined;
  15139. if (propInfo.hashOverride != null) {
  15140. normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);
  15141. } else if (parsedProp.pfValue != null) {
  15142. normalizedNumberVal = parsedProp.pfValue;
  15143. }
  15144. // might not be a number if it allows enums
  15145. var numberVal = propInfo.enums == null ? parsedProp.value : null;
  15146. var haveNormNum = normalizedNumberVal != null;
  15147. var haveUnitedNum = numberVal != null;
  15148. var haveNum = haveNormNum || haveUnitedNum;
  15149. var units = parsedProp.units;
  15150. // numbers are cheaper to hash than strings
  15151. // 1 hash op vs n hash ops (for length n string)
  15152. if (type.number && haveNum && !type.multiple) {
  15153. var v = haveNormNum ? normalizedNumberVal : numberVal;
  15154. updateGrKey(cleanNum(v), _grKey);
  15155. if (!haveNormNum && units != null) {
  15156. updateGrKeyWStr(units, _grKey);
  15157. }
  15158. } else {
  15159. updateGrKeyWStr(parsedProp.strValue, _grKey);
  15160. }
  15161. }
  15162. // overall style key
  15163. //
  15164. var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  15165. for (var _i2 = 0; _i2 < propGrKeys.length; _i2++) {
  15166. var _grKey2 = propGrKeys[_i2];
  15167. var grHash = _p.styleKeys[_grKey2];
  15168. hash[0] = hashInt(grHash[0], hash[0]);
  15169. hash[1] = hashIntAlt(grHash[1], hash[1]);
  15170. }
  15171. _p.styleKey = combineHashes(hash[0], hash[1]);
  15172. // label dims
  15173. //
  15174. var sk = _p.styleKeys;
  15175. _p.labelDimsKey = combineHashesArray(sk.labelDimensions);
  15176. var labelKeys = propHash(ele, ['label'], sk.labelDimensions);
  15177. _p.labelKey = combineHashesArray(labelKeys);
  15178. _p.labelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, labelKeys));
  15179. if (!isNode) {
  15180. var sourceLabelKeys = propHash(ele, ['source-label'], sk.labelDimensions);
  15181. _p.sourceLabelKey = combineHashesArray(sourceLabelKeys);
  15182. _p.sourceLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, sourceLabelKeys));
  15183. var targetLabelKeys = propHash(ele, ['target-label'], sk.labelDimensions);
  15184. _p.targetLabelKey = combineHashesArray(targetLabelKeys);
  15185. _p.targetLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, targetLabelKeys));
  15186. }
  15187. // node
  15188. //
  15189. if (isNode) {
  15190. var _p$styleKeys = _p.styleKeys,
  15191. nodeBody = _p$styleKeys.nodeBody,
  15192. nodeBorder = _p$styleKeys.nodeBorder,
  15193. nodeOutline = _p$styleKeys.nodeOutline,
  15194. backgroundImage = _p$styleKeys.backgroundImage,
  15195. compound = _p$styleKeys.compound,
  15196. pie = _p$styleKeys.pie,
  15197. stripe = _p$styleKeys.stripe;
  15198. var nodeKeys = [nodeBody, nodeBorder, nodeOutline, backgroundImage, compound, pie, stripe].filter(function (k) {
  15199. return k != null;
  15200. }).reduce(hashArrays, [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT]);
  15201. _p.nodeKey = combineHashesArray(nodeKeys);
  15202. _p.hasPie = pie != null && pie[0] !== DEFAULT_HASH_SEED && pie[1] !== DEFAULT_HASH_SEED_ALT;
  15203. _p.hasStripe = stripe != null && stripe[0] !== DEFAULT_HASH_SEED && stripe[1] !== DEFAULT_HASH_SEED_ALT;
  15204. }
  15205. return oldStyleKey !== _p.styleKey;
  15206. };
  15207. styfn$8.clearStyleHints = function (ele) {
  15208. var _p = ele._private;
  15209. _p.styleCxtKey = '';
  15210. _p.styleKeys = {};
  15211. _p.styleKey = null;
  15212. _p.labelKey = null;
  15213. _p.labelStyleKey = null;
  15214. _p.sourceLabelKey = null;
  15215. _p.sourceLabelStyleKey = null;
  15216. _p.targetLabelKey = null;
  15217. _p.targetLabelStyleKey = null;
  15218. _p.nodeKey = null;
  15219. _p.hasPie = null;
  15220. _p.hasStripe = null;
  15221. };
  15222. // apply a property to the style (for internal use)
  15223. // returns whether application was successful
  15224. //
  15225. // now, this function flattens the property, and here's how:
  15226. //
  15227. // for parsedProp:{ bypass: true, deleteBypass: true }
  15228. // no property is generated, instead the bypass property in the
  15229. // element's style is replaced by what's pointed to by the `bypassed`
  15230. // field in the bypass property (i.e. restoring the property the
  15231. // bypass was overriding)
  15232. //
  15233. // for parsedProp:{ mapped: truthy }
  15234. // the generated flattenedProp:{ mapping: prop }
  15235. //
  15236. // for parsedProp:{ bypass: true }
  15237. // the generated flattenedProp:{ bypassed: parsedProp }
  15238. styfn$8.applyParsedProperty = function (ele, parsedProp) {
  15239. var self = this;
  15240. var prop = parsedProp;
  15241. var style = ele._private.style;
  15242. var flatProp;
  15243. var types = self.types;
  15244. var type = self.properties[prop.name].type;
  15245. var propIsBypass = prop.bypass;
  15246. var origProp = style[prop.name];
  15247. var origPropIsBypass = origProp && origProp.bypass;
  15248. var _p = ele._private;
  15249. var flatPropMapping = 'mapping';
  15250. var getVal = function getVal(p) {
  15251. if (p == null) {
  15252. return null;
  15253. } else if (p.pfValue != null) {
  15254. return p.pfValue;
  15255. } else {
  15256. return p.value;
  15257. }
  15258. };
  15259. var checkTriggers = function checkTriggers() {
  15260. var fromVal = getVal(origProp);
  15261. var toVal = getVal(prop);
  15262. self.checkTriggers(ele, prop.name, fromVal, toVal);
  15263. };
  15264. // edge sanity checks to prevent the client from making serious mistakes
  15265. if (parsedProp.name === 'curve-style' && ele.isEdge() && (
  15266. // loops must be bundled beziers
  15267. parsedProp.value !== 'bezier' && ele.isLoop() ||
  15268. // edges connected to compound nodes can not be haystacks
  15269. parsedProp.value === 'haystack' && (ele.source().isParent() || ele.target().isParent()))) {
  15270. prop = parsedProp = this.parse(parsedProp.name, 'bezier', propIsBypass);
  15271. }
  15272. if (prop["delete"]) {
  15273. // delete the property and use the default value on falsey value
  15274. style[prop.name] = undefined;
  15275. checkTriggers();
  15276. return true;
  15277. }
  15278. if (prop.deleteBypassed) {
  15279. // delete the property that the
  15280. if (!origProp) {
  15281. checkTriggers();
  15282. return true; // can't delete if no prop
  15283. } else if (origProp.bypass) {
  15284. // delete bypassed
  15285. origProp.bypassed = undefined;
  15286. checkTriggers();
  15287. return true;
  15288. } else {
  15289. return false; // we're unsuccessful deleting the bypassed
  15290. }
  15291. }
  15292. // check if we need to delete the current bypass
  15293. if (prop.deleteBypass) {
  15294. // then this property is just here to indicate we need to delete
  15295. if (!origProp) {
  15296. checkTriggers();
  15297. return true; // property is already not defined
  15298. } else if (origProp.bypass) {
  15299. // then replace the bypass property with the original
  15300. // because the bypassed property was already applied (and therefore parsed), we can just replace it (no reapplying necessary)
  15301. style[prop.name] = origProp.bypassed;
  15302. checkTriggers();
  15303. return true;
  15304. } else {
  15305. return false; // we're unsuccessful deleting the bypass
  15306. }
  15307. }
  15308. var printMappingErr = function printMappingErr() {
  15309. 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');
  15310. };
  15311. // put the property in the style objects
  15312. switch (prop.mapped) {
  15313. // flatten the property if mapped
  15314. case types.mapData:
  15315. {
  15316. // flatten the field (e.g. data.foo.bar)
  15317. var fields = prop.field.split('.');
  15318. var fieldVal = _p.data;
  15319. for (var i = 0; i < fields.length && fieldVal; i++) {
  15320. var field = fields[i];
  15321. fieldVal = fieldVal[field];
  15322. }
  15323. if (fieldVal == null) {
  15324. printMappingErr();
  15325. return false;
  15326. }
  15327. var percent;
  15328. if (!number$1(fieldVal)) {
  15329. // then don't apply and fall back on the existing style
  15330. warn('Do not use continuous mappers without specifying numeric data (i.e. `' + prop.field + ': ' + fieldVal + '` for `' + ele.id() + '` is non-numeric)');
  15331. return false;
  15332. } else {
  15333. var fieldWidth = prop.fieldMax - prop.fieldMin;
  15334. if (fieldWidth === 0) {
  15335. // safety check -- not strictly necessary as no props of zero range should be passed here
  15336. percent = 0;
  15337. } else {
  15338. percent = (fieldVal - prop.fieldMin) / fieldWidth;
  15339. }
  15340. }
  15341. // make sure to bound percent value
  15342. if (percent < 0) {
  15343. percent = 0;
  15344. } else if (percent > 1) {
  15345. percent = 1;
  15346. }
  15347. if (type.color) {
  15348. var r1 = prop.valueMin[0];
  15349. var r2 = prop.valueMax[0];
  15350. var g1 = prop.valueMin[1];
  15351. var g2 = prop.valueMax[1];
  15352. var b1 = prop.valueMin[2];
  15353. var b2 = prop.valueMax[2];
  15354. var a1 = prop.valueMin[3] == null ? 1 : prop.valueMin[3];
  15355. var a2 = prop.valueMax[3] == null ? 1 : prop.valueMax[3];
  15356. 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)];
  15357. flatProp = {
  15358. // colours are simple, so just create the flat property instead of expensive string parsing
  15359. bypass: prop.bypass,
  15360. // we're a bypass if the mapping property is a bypass
  15361. name: prop.name,
  15362. value: clr,
  15363. strValue: 'rgb(' + clr[0] + ', ' + clr[1] + ', ' + clr[2] + ')'
  15364. };
  15365. } else if (type.number) {
  15366. var calcValue = prop.valueMin + (prop.valueMax - prop.valueMin) * percent;
  15367. flatProp = this.parse(prop.name, calcValue, prop.bypass, flatPropMapping);
  15368. } else {
  15369. return false; // can only map to colours and numbers
  15370. }
  15371. if (!flatProp) {
  15372. // if we can't flatten the property, then don't apply the property and fall back on the existing style
  15373. printMappingErr();
  15374. return false;
  15375. }
  15376. flatProp.mapping = prop; // keep a reference to the mapping
  15377. prop = flatProp; // the flattened (mapped) property is the one we want
  15378. break;
  15379. }
  15380. // direct mapping
  15381. case types.data:
  15382. {
  15383. // flatten the field (e.g. data.foo.bar)
  15384. var _fields = prop.field.split('.');
  15385. var _fieldVal = _p.data;
  15386. for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {
  15387. var _field = _fields[_i3];
  15388. _fieldVal = _fieldVal[_field];
  15389. }
  15390. if (_fieldVal != null) {
  15391. flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);
  15392. }
  15393. if (!flatProp) {
  15394. // if we can't flatten the property, then don't apply and fall back on the existing style
  15395. printMappingErr();
  15396. return false;
  15397. }
  15398. flatProp.mapping = prop; // keep a reference to the mapping
  15399. prop = flatProp; // the flattened (mapped) property is the one we want
  15400. break;
  15401. }
  15402. case types.fn:
  15403. {
  15404. var fn = prop.value;
  15405. var fnRetVal = prop.fnValue != null ? prop.fnValue : fn(ele); // check for cached value before calling function
  15406. prop.prevFnValue = fnRetVal;
  15407. if (fnRetVal == null) {
  15408. warn('Custom function mappers may not return null (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is null)');
  15409. return false;
  15410. }
  15411. flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);
  15412. if (!flatProp) {
  15413. warn('Custom function mappers may not return invalid values for the property type (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is invalid)');
  15414. return false;
  15415. }
  15416. flatProp.mapping = copy(prop); // keep a reference to the mapping
  15417. prop = flatProp; // the flattened (mapped) property is the one we want
  15418. break;
  15419. }
  15420. case undefined:
  15421. break;
  15422. // just set the property
  15423. default:
  15424. return false;
  15425. // not a valid mapping
  15426. }
  15427. // if the property is a bypass property, then link the resultant property to the original one
  15428. if (propIsBypass) {
  15429. if (origPropIsBypass) {
  15430. // then this bypass overrides the existing one
  15431. prop.bypassed = origProp.bypassed; // steal bypassed prop from old bypass
  15432. } else {
  15433. // then link the orig prop to the new bypass
  15434. prop.bypassed = origProp;
  15435. }
  15436. style[prop.name] = prop; // and set
  15437. } else {
  15438. // prop is not bypass
  15439. if (origPropIsBypass) {
  15440. // then keep the orig prop (since it's a bypass) and link to the new prop
  15441. origProp.bypassed = prop;
  15442. } else {
  15443. // then just replace the old prop with the new one
  15444. style[prop.name] = prop;
  15445. }
  15446. }
  15447. checkTriggers();
  15448. return true;
  15449. };
  15450. styfn$8.cleanElements = function (eles, keepBypasses) {
  15451. for (var i = 0; i < eles.length; i++) {
  15452. var ele = eles[i];
  15453. this.clearStyleHints(ele);
  15454. ele.dirtyCompoundBoundsCache();
  15455. ele.dirtyBoundingBoxCache();
  15456. if (!keepBypasses) {
  15457. ele._private.style = {};
  15458. } else {
  15459. var style = ele._private.style;
  15460. var propNames = Object.keys(style);
  15461. for (var j = 0; j < propNames.length; j++) {
  15462. var propName = propNames[j];
  15463. var eleProp = style[propName];
  15464. if (eleProp != null) {
  15465. if (eleProp.bypass) {
  15466. eleProp.bypassed = null;
  15467. } else {
  15468. style[propName] = null;
  15469. }
  15470. }
  15471. }
  15472. }
  15473. }
  15474. };
  15475. // updates the visual style for all elements (useful for manual style modification after init)
  15476. styfn$8.update = function () {
  15477. var cy = this._private.cy;
  15478. var eles = cy.mutableElements();
  15479. eles.updateStyle();
  15480. };
  15481. // diffProps : { name => { prev, next } }
  15482. styfn$8.updateTransitions = function (ele, diffProps) {
  15483. var self = this;
  15484. var _p = ele._private;
  15485. var props = ele.pstyle('transition-property').value;
  15486. var duration = ele.pstyle('transition-duration').pfValue;
  15487. var delay = ele.pstyle('transition-delay').pfValue;
  15488. if (props.length > 0 && duration > 0) {
  15489. var style = {};
  15490. // build up the style to animate towards
  15491. var anyPrev = false;
  15492. for (var i = 0; i < props.length; i++) {
  15493. var prop = props[i];
  15494. var styProp = ele.pstyle(prop);
  15495. var diffProp = diffProps[prop];
  15496. if (!diffProp) {
  15497. continue;
  15498. }
  15499. var prevProp = diffProp.prev;
  15500. var fromProp = prevProp;
  15501. var toProp = diffProp.next != null ? diffProp.next : styProp;
  15502. var diff = false;
  15503. var initVal = undefined;
  15504. var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)
  15505. if (!fromProp) {
  15506. continue;
  15507. }
  15508. // consider px values
  15509. if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {
  15510. diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy
  15511. initVal = fromProp.pfValue + initDt * diff;
  15512. // consider numerical values
  15513. } else if (number$1(fromProp.value) && number$1(toProp.value)) {
  15514. diff = toProp.value - fromProp.value; // nonzero is truthy
  15515. initVal = fromProp.value + initDt * diff;
  15516. // consider colour values
  15517. } else if (array(fromProp.value) && array(toProp.value)) {
  15518. diff = fromProp.value[0] !== toProp.value[0] || fromProp.value[1] !== toProp.value[1] || fromProp.value[2] !== toProp.value[2];
  15519. initVal = fromProp.strValue;
  15520. }
  15521. // the previous value is good for an animation only if it's different
  15522. if (diff) {
  15523. style[prop] = toProp.strValue; // to val
  15524. this.applyBypass(ele, prop, initVal); // from val
  15525. anyPrev = true;
  15526. }
  15527. } // end if props allow ani
  15528. // can't transition if there's nothing previous to transition from
  15529. if (!anyPrev) {
  15530. return;
  15531. }
  15532. _p.transitioning = true;
  15533. new Promise$1(function (resolve) {
  15534. if (delay > 0) {
  15535. ele.delayAnimation(delay).play().promise().then(resolve);
  15536. } else {
  15537. resolve();
  15538. }
  15539. }).then(function () {
  15540. return ele.animation({
  15541. style: style,
  15542. duration: duration,
  15543. easing: ele.pstyle('transition-timing-function').value,
  15544. queue: false
  15545. }).play().promise();
  15546. }).then(function () {
  15547. // if( !isBypass ){
  15548. self.removeBypasses(ele, props);
  15549. ele.emitAndNotify('style');
  15550. // }
  15551. _p.transitioning = false;
  15552. });
  15553. } else if (_p.transitioning) {
  15554. this.removeBypasses(ele, props);
  15555. ele.emitAndNotify('style');
  15556. _p.transitioning = false;
  15557. }
  15558. };
  15559. styfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {
  15560. var prop = this.properties[name];
  15561. var triggerCheck = getTrigger(prop);
  15562. if (ele.removed()) {
  15563. return;
  15564. }
  15565. if (triggerCheck != null && triggerCheck(fromValue, toValue, ele)) {
  15566. onTrigger(prop);
  15567. }
  15568. };
  15569. styfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {
  15570. var _this = this;
  15571. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15572. return prop.triggersZOrder;
  15573. }, function () {
  15574. _this._private.cy.notify('zorder', ele);
  15575. });
  15576. };
  15577. styfn$8.checkBoundsTrigger = function (ele, name, fromValue, toValue) {
  15578. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15579. return prop.triggersBounds;
  15580. }, function (prop) {
  15581. ele.dirtyCompoundBoundsCache();
  15582. ele.dirtyBoundingBoxCache();
  15583. });
  15584. };
  15585. styfn$8.checkConnectedEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  15586. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15587. return prop.triggersBoundsOfConnectedEdges;
  15588. }, function (prop) {
  15589. ele.connectedEdges().forEach(function (edge) {
  15590. edge.dirtyBoundingBoxCache();
  15591. });
  15592. });
  15593. };
  15594. styfn$8.checkParallelEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  15595. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15596. return prop.triggersBoundsOfParallelEdges;
  15597. }, function (prop) {
  15598. ele.parallelEdges().forEach(function (pllEdge) {
  15599. pllEdge.dirtyBoundingBoxCache();
  15600. });
  15601. });
  15602. };
  15603. styfn$8.checkTriggers = function (ele, name, fromValue, toValue) {
  15604. ele.dirtyStyleCache();
  15605. this.checkZOrderTrigger(ele, name, fromValue, toValue);
  15606. this.checkBoundsTrigger(ele, name, fromValue, toValue);
  15607. this.checkConnectedEdgesBoundsTrigger(ele, name, fromValue, toValue);
  15608. this.checkParallelEdgesBoundsTrigger(ele, name, fromValue, toValue);
  15609. };
  15610. var styfn$7 = {};
  15611. // bypasses are applied to an existing style on an element, and just tacked on temporarily
  15612. // returns true iff application was successful for at least 1 specified property
  15613. styfn$7.applyBypass = function (eles, name, value, updateTransitions) {
  15614. var self = this;
  15615. var props = [];
  15616. var isBypass = true;
  15617. // put all the properties (can specify one or many) in an array after parsing them
  15618. if (name === '*' || name === '**') {
  15619. // apply to all property names
  15620. if (value !== undefined) {
  15621. for (var i = 0; i < self.properties.length; i++) {
  15622. var prop = self.properties[i];
  15623. var _name = prop.name;
  15624. var parsedProp = this.parse(_name, value, true);
  15625. if (parsedProp) {
  15626. props.push(parsedProp);
  15627. }
  15628. }
  15629. }
  15630. } else if (string(name)) {
  15631. // then parse the single property
  15632. var _parsedProp = this.parse(name, value, true);
  15633. if (_parsedProp) {
  15634. props.push(_parsedProp);
  15635. }
  15636. } else if (plainObject(name)) {
  15637. // then parse each property
  15638. var specifiedProps = name;
  15639. updateTransitions = value;
  15640. var names = Object.keys(specifiedProps);
  15641. for (var _i = 0; _i < names.length; _i++) {
  15642. var _name2 = names[_i];
  15643. var _value = specifiedProps[_name2];
  15644. if (_value === undefined) {
  15645. // try camel case name too
  15646. _value = specifiedProps[dash2camel(_name2)];
  15647. }
  15648. if (_value !== undefined) {
  15649. var _parsedProp2 = this.parse(_name2, _value, true);
  15650. if (_parsedProp2) {
  15651. props.push(_parsedProp2);
  15652. }
  15653. }
  15654. }
  15655. } else {
  15656. // can't do anything without well defined properties
  15657. return false;
  15658. }
  15659. // we've failed if there are no valid properties
  15660. if (props.length === 0) {
  15661. return false;
  15662. }
  15663. // now, apply the bypass properties on the elements
  15664. var ret = false; // return true if at least one succesful bypass applied
  15665. for (var _i2 = 0; _i2 < eles.length; _i2++) {
  15666. // for each ele
  15667. var ele = eles[_i2];
  15668. var diffProps = {};
  15669. var diffProp = undefined;
  15670. for (var j = 0; j < props.length; j++) {
  15671. // for each prop
  15672. var _prop = props[j];
  15673. if (updateTransitions) {
  15674. var prevProp = ele.pstyle(_prop.name);
  15675. diffProp = diffProps[_prop.name] = {
  15676. prev: prevProp
  15677. };
  15678. }
  15679. ret = this.applyParsedProperty(ele, copy(_prop)) || ret;
  15680. if (updateTransitions) {
  15681. diffProp.next = ele.pstyle(_prop.name);
  15682. }
  15683. } // for props
  15684. if (ret) {
  15685. this.updateStyleHints(ele);
  15686. }
  15687. if (updateTransitions) {
  15688. this.updateTransitions(ele, diffProps, isBypass);
  15689. }
  15690. } // for eles
  15691. return ret;
  15692. };
  15693. // only useful in specific cases like animation
  15694. styfn$7.overrideBypass = function (eles, name, value) {
  15695. name = camel2dash(name);
  15696. for (var i = 0; i < eles.length; i++) {
  15697. var ele = eles[i];
  15698. var prop = ele._private.style[name];
  15699. var type = this.properties[name].type;
  15700. var isColor = type.color;
  15701. var isMulti = type.mutiple;
  15702. var oldValue = !prop ? null : prop.pfValue != null ? prop.pfValue : prop.value;
  15703. if (!prop || !prop.bypass) {
  15704. // need a bypass if one doesn't exist
  15705. this.applyBypass(ele, name, value);
  15706. } else {
  15707. prop.value = value;
  15708. if (prop.pfValue != null) {
  15709. prop.pfValue = value;
  15710. }
  15711. if (isColor) {
  15712. prop.strValue = 'rgb(' + value.join(',') + ')';
  15713. } else if (isMulti) {
  15714. prop.strValue = value.join(' ');
  15715. } else {
  15716. prop.strValue = '' + value;
  15717. }
  15718. this.updateStyleHints(ele);
  15719. }
  15720. this.checkTriggers(ele, name, oldValue, value);
  15721. }
  15722. };
  15723. styfn$7.removeAllBypasses = function (eles, updateTransitions) {
  15724. return this.removeBypasses(eles, this.propertyNames, updateTransitions);
  15725. };
  15726. styfn$7.removeBypasses = function (eles, props, updateTransitions) {
  15727. var isBypass = true;
  15728. for (var j = 0; j < eles.length; j++) {
  15729. var ele = eles[j];
  15730. var diffProps = {};
  15731. for (var i = 0; i < props.length; i++) {
  15732. var name = props[i];
  15733. var prop = this.properties[name];
  15734. var prevProp = ele.pstyle(prop.name);
  15735. if (!prevProp || !prevProp.bypass) {
  15736. // if a bypass doesn't exist for the prop, nothing needs to be removed
  15737. continue;
  15738. }
  15739. var value = ''; // empty => remove bypass
  15740. var parsedProp = this.parse(name, value, true);
  15741. var diffProp = diffProps[prop.name] = {
  15742. prev: prevProp
  15743. };
  15744. this.applyParsedProperty(ele, parsedProp);
  15745. diffProp.next = ele.pstyle(prop.name);
  15746. } // for props
  15747. this.updateStyleHints(ele);
  15748. if (updateTransitions) {
  15749. this.updateTransitions(ele, diffProps, isBypass);
  15750. }
  15751. } // for eles
  15752. };
  15753. var styfn$6 = {};
  15754. // gets what an em size corresponds to in pixels relative to a dom element
  15755. styfn$6.getEmSizeInPixels = function () {
  15756. var px = this.containerCss('font-size');
  15757. if (px != null) {
  15758. return parseFloat(px);
  15759. } else {
  15760. return 1; // for headless
  15761. }
  15762. };
  15763. // gets css property from the core container
  15764. styfn$6.containerCss = function (propName) {
  15765. var cy = this._private.cy;
  15766. var domElement = cy.container();
  15767. var containerWindow = cy.window();
  15768. if (containerWindow && domElement && containerWindow.getComputedStyle) {
  15769. return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);
  15770. }
  15771. };
  15772. var styfn$5 = {};
  15773. // gets the rendered style for an element
  15774. styfn$5.getRenderedStyle = function (ele, prop) {
  15775. if (prop) {
  15776. return this.getStylePropertyValue(ele, prop, true);
  15777. } else {
  15778. return this.getRawStyle(ele, true);
  15779. }
  15780. };
  15781. // gets the raw style for an element
  15782. styfn$5.getRawStyle = function (ele, isRenderedVal) {
  15783. var self = this;
  15784. ele = ele[0]; // insure it's an element
  15785. if (ele) {
  15786. var rstyle = {};
  15787. for (var i = 0; i < self.properties.length; i++) {
  15788. var prop = self.properties[i];
  15789. var val = self.getStylePropertyValue(ele, prop.name, isRenderedVal);
  15790. if (val != null) {
  15791. rstyle[prop.name] = val;
  15792. rstyle[dash2camel(prop.name)] = val;
  15793. }
  15794. }
  15795. return rstyle;
  15796. }
  15797. };
  15798. styfn$5.getIndexedStyle = function (ele, property, subproperty, index) {
  15799. var pstyle = ele.pstyle(property)[subproperty][index];
  15800. return pstyle != null ? pstyle : ele.cy().style().getDefaultProperty(property)[subproperty][0];
  15801. };
  15802. styfn$5.getStylePropertyValue = function (ele, propName, isRenderedVal) {
  15803. var self = this;
  15804. ele = ele[0]; // insure it's an element
  15805. if (ele) {
  15806. var prop = self.properties[propName];
  15807. if (prop.alias) {
  15808. prop = prop.pointsTo;
  15809. }
  15810. var type = prop.type;
  15811. var styleProp = ele.pstyle(prop.name);
  15812. if (styleProp) {
  15813. var value = styleProp.value,
  15814. units = styleProp.units,
  15815. strValue = styleProp.strValue;
  15816. if (isRenderedVal && type.number && value != null && number$1(value)) {
  15817. var zoom = ele.cy().zoom();
  15818. var getRenderedValue = function getRenderedValue(val) {
  15819. return val * zoom;
  15820. };
  15821. var getValueStringWithUnits = function getValueStringWithUnits(val, units) {
  15822. return getRenderedValue(val) + units;
  15823. };
  15824. var isArrayValue = array(value);
  15825. var haveUnits = isArrayValue ? units.every(function (u) {
  15826. return u != null;
  15827. }) : units != null;
  15828. if (haveUnits) {
  15829. if (isArrayValue) {
  15830. return value.map(function (v, i) {
  15831. return getValueStringWithUnits(v, units[i]);
  15832. }).join(' ');
  15833. } else {
  15834. return getValueStringWithUnits(value, units);
  15835. }
  15836. } else {
  15837. if (isArrayValue) {
  15838. return value.map(function (v) {
  15839. return string(v) ? v : '' + getRenderedValue(v);
  15840. }).join(' ');
  15841. } else {
  15842. return '' + getRenderedValue(value);
  15843. }
  15844. }
  15845. } else if (strValue != null) {
  15846. return strValue;
  15847. }
  15848. }
  15849. return null;
  15850. }
  15851. };
  15852. styfn$5.getAnimationStartStyle = function (ele, aniProps) {
  15853. var rstyle = {};
  15854. for (var i = 0; i < aniProps.length; i++) {
  15855. var aniProp = aniProps[i];
  15856. var name = aniProp.name;
  15857. var styleProp = ele.pstyle(name);
  15858. if (styleProp !== undefined) {
  15859. // then make a prop of it
  15860. if (plainObject(styleProp)) {
  15861. styleProp = this.parse(name, styleProp.strValue);
  15862. } else {
  15863. styleProp = this.parse(name, styleProp);
  15864. }
  15865. }
  15866. if (styleProp) {
  15867. rstyle[name] = styleProp;
  15868. }
  15869. }
  15870. return rstyle;
  15871. };
  15872. styfn$5.getPropsList = function (propsObj) {
  15873. var self = this;
  15874. var rstyle = [];
  15875. var style = propsObj;
  15876. var props = self.properties;
  15877. if (style) {
  15878. var names = Object.keys(style);
  15879. for (var i = 0; i < names.length; i++) {
  15880. var name = names[i];
  15881. var val = style[name];
  15882. var prop = props[name] || props[camel2dash(name)];
  15883. var styleProp = this.parse(prop.name, val);
  15884. if (styleProp) {
  15885. rstyle.push(styleProp);
  15886. }
  15887. }
  15888. }
  15889. return rstyle;
  15890. };
  15891. styfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {
  15892. var hash = seed.slice();
  15893. var name, val, strVal, chVal;
  15894. var i, j;
  15895. for (i = 0; i < propNames.length; i++) {
  15896. name = propNames[i];
  15897. val = ele.pstyle(name, false);
  15898. if (val == null) {
  15899. continue;
  15900. } else if (val.pfValue != null) {
  15901. hash[0] = hashInt(chVal, hash[0]);
  15902. hash[1] = hashIntAlt(chVal, hash[1]);
  15903. } else {
  15904. strVal = val.strValue;
  15905. for (j = 0; j < strVal.length; j++) {
  15906. chVal = strVal.charCodeAt(j);
  15907. hash[0] = hashInt(chVal, hash[0]);
  15908. hash[1] = hashIntAlt(chVal, hash[1]);
  15909. }
  15910. }
  15911. }
  15912. return hash;
  15913. };
  15914. styfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;
  15915. var styfn$4 = {};
  15916. styfn$4.appendFromJson = function (json) {
  15917. var style = this;
  15918. for (var i = 0; i < json.length; i++) {
  15919. var context = json[i];
  15920. var selector = context.selector;
  15921. var props = context.style || context.css;
  15922. var names = Object.keys(props);
  15923. style.selector(selector); // apply selector
  15924. for (var j = 0; j < names.length; j++) {
  15925. var name = names[j];
  15926. var value = props[name];
  15927. style.css(name, value); // apply property
  15928. }
  15929. }
  15930. return style;
  15931. };
  15932. // accessible cy.style() function
  15933. styfn$4.fromJson = function (json) {
  15934. var style = this;
  15935. style.resetToDefault();
  15936. style.appendFromJson(json);
  15937. return style;
  15938. };
  15939. // get json from cy.style() api
  15940. styfn$4.json = function () {
  15941. var json = [];
  15942. for (var i = this.defaultLength; i < this.length; i++) {
  15943. var cxt = this[i];
  15944. var selector = cxt.selector;
  15945. var props = cxt.properties;
  15946. var css = {};
  15947. for (var j = 0; j < props.length; j++) {
  15948. var prop = props[j];
  15949. css[prop.name] = prop.strValue;
  15950. }
  15951. json.push({
  15952. selector: !selector ? 'core' : selector.toString(),
  15953. style: css
  15954. });
  15955. }
  15956. return json;
  15957. };
  15958. var styfn$3 = {};
  15959. styfn$3.appendFromString = function (string) {
  15960. var self = this;
  15961. var style = this;
  15962. var remaining = '' + string;
  15963. var selAndBlockStr;
  15964. var blockRem;
  15965. var propAndValStr;
  15966. // remove comments from the style string
  15967. remaining = remaining.replace(/[/][*](\s|.)+?[*][/]/g, '');
  15968. function removeSelAndBlockFromRemaining() {
  15969. // remove the parsed selector and block from the remaining text to parse
  15970. if (remaining.length > selAndBlockStr.length) {
  15971. remaining = remaining.substr(selAndBlockStr.length);
  15972. } else {
  15973. remaining = '';
  15974. }
  15975. }
  15976. function removePropAndValFromRem() {
  15977. // remove the parsed property and value from the remaining block text to parse
  15978. if (blockRem.length > propAndValStr.length) {
  15979. blockRem = blockRem.substr(propAndValStr.length);
  15980. } else {
  15981. blockRem = '';
  15982. }
  15983. }
  15984. for (;;) {
  15985. var nothingLeftToParse = remaining.match(/^\s*$/);
  15986. if (nothingLeftToParse) {
  15987. break;
  15988. }
  15989. var selAndBlock = remaining.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);
  15990. if (!selAndBlock) {
  15991. warn('Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: ' + remaining);
  15992. break;
  15993. }
  15994. selAndBlockStr = selAndBlock[0];
  15995. // parse the selector
  15996. var selectorStr = selAndBlock[1];
  15997. if (selectorStr !== 'core') {
  15998. var selector = new Selector(selectorStr);
  15999. if (selector.invalid) {
  16000. warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr);
  16001. // skip this selector and block
  16002. removeSelAndBlockFromRemaining();
  16003. continue;
  16004. }
  16005. }
  16006. // parse the block of properties and values
  16007. var blockStr = selAndBlock[2];
  16008. var invalidBlock = false;
  16009. blockRem = blockStr;
  16010. var props = [];
  16011. for (;;) {
  16012. var _nothingLeftToParse = blockRem.match(/^\s*$/);
  16013. if (_nothingLeftToParse) {
  16014. break;
  16015. }
  16016. var propAndVal = blockRem.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);
  16017. if (!propAndVal) {
  16018. warn('Skipping parsing of block: Invalid formatting of style property and value definitions found in:' + blockStr);
  16019. invalidBlock = true;
  16020. break;
  16021. }
  16022. propAndValStr = propAndVal[0];
  16023. var propStr = propAndVal[1];
  16024. var valStr = propAndVal[2];
  16025. var prop = self.properties[propStr];
  16026. if (!prop) {
  16027. warn('Skipping property: Invalid property name in: ' + propAndValStr);
  16028. // skip this property in the block
  16029. removePropAndValFromRem();
  16030. continue;
  16031. }
  16032. var parsedProp = style.parse(propStr, valStr);
  16033. if (!parsedProp) {
  16034. warn('Skipping property: Invalid property definition in: ' + propAndValStr);
  16035. // skip this property in the block
  16036. removePropAndValFromRem();
  16037. continue;
  16038. }
  16039. props.push({
  16040. name: propStr,
  16041. val: valStr
  16042. });
  16043. removePropAndValFromRem();
  16044. }
  16045. if (invalidBlock) {
  16046. removeSelAndBlockFromRemaining();
  16047. break;
  16048. }
  16049. // put the parsed block in the style
  16050. style.selector(selectorStr);
  16051. for (var i = 0; i < props.length; i++) {
  16052. var _prop = props[i];
  16053. style.css(_prop.name, _prop.val);
  16054. }
  16055. removeSelAndBlockFromRemaining();
  16056. }
  16057. return style;
  16058. };
  16059. styfn$3.fromString = function (string) {
  16060. var style = this;
  16061. style.resetToDefault();
  16062. style.appendFromString(string);
  16063. return style;
  16064. };
  16065. var styfn$2 = {};
  16066. (function () {
  16067. var number$1 = number;
  16068. var rgba = rgbaNoBackRefs;
  16069. var hsla = hslaNoBackRefs;
  16070. var hex3$1 = hex3;
  16071. var hex6$1 = hex6;
  16072. var data = function data(prefix) {
  16073. return '^' + prefix + '\\s*\\(\\s*([\\w\\.]+)\\s*\\)$';
  16074. };
  16075. var mapData = function mapData(prefix) {
  16076. var mapArg = number$1 + '|\\w+|' + rgba + '|' + hsla + '|' + hex3$1 + '|' + hex6$1;
  16077. return '^' + prefix + '\\s*\\(([\\w\\.]+)\\s*\\,\\s*(' + number$1 + ')\\s*\\,\\s*(' + number$1 + ')\\s*,\\s*(' + mapArg + ')\\s*\\,\\s*(' + mapArg + ')\\)$';
  16078. };
  16079. var urlRegexes = ['^url\\s*\\(\\s*[\'"]?(.+?)[\'"]?\\s*\\)$', '^(none)$', '^(.+)$'];
  16080. // each visual style property has a type and needs to be validated according to it
  16081. styfn$2.types = {
  16082. time: {
  16083. number: true,
  16084. min: 0,
  16085. units: 's|ms',
  16086. implicitUnits: 'ms'
  16087. },
  16088. percent: {
  16089. number: true,
  16090. min: 0,
  16091. max: 100,
  16092. units: '%',
  16093. implicitUnits: '%'
  16094. },
  16095. percentages: {
  16096. number: true,
  16097. min: 0,
  16098. max: 100,
  16099. units: '%',
  16100. implicitUnits: '%',
  16101. multiple: true
  16102. },
  16103. zeroOneNumber: {
  16104. number: true,
  16105. min: 0,
  16106. max: 1,
  16107. unitless: true
  16108. },
  16109. zeroOneNumbers: {
  16110. number: true,
  16111. min: 0,
  16112. max: 1,
  16113. unitless: true,
  16114. multiple: true
  16115. },
  16116. nOneOneNumber: {
  16117. number: true,
  16118. min: -1,
  16119. max: 1,
  16120. unitless: true
  16121. },
  16122. nonNegativeInt: {
  16123. number: true,
  16124. min: 0,
  16125. integer: true,
  16126. unitless: true
  16127. },
  16128. nonNegativeNumber: {
  16129. number: true,
  16130. min: 0,
  16131. unitless: true
  16132. },
  16133. position: {
  16134. enums: ['parent', 'origin']
  16135. },
  16136. nodeSize: {
  16137. number: true,
  16138. min: 0,
  16139. enums: ['label']
  16140. },
  16141. number: {
  16142. number: true,
  16143. unitless: true
  16144. },
  16145. numbers: {
  16146. number: true,
  16147. unitless: true,
  16148. multiple: true
  16149. },
  16150. positiveNumber: {
  16151. number: true,
  16152. unitless: true,
  16153. min: 0,
  16154. strictMin: true
  16155. },
  16156. size: {
  16157. number: true,
  16158. min: 0
  16159. },
  16160. bidirectionalSize: {
  16161. number: true
  16162. },
  16163. // allows negative
  16164. bidirectionalSizeMaybePercent: {
  16165. number: true,
  16166. allowPercent: true
  16167. },
  16168. // allows negative
  16169. bidirectionalSizes: {
  16170. number: true,
  16171. multiple: true
  16172. },
  16173. // allows negative
  16174. sizeMaybePercent: {
  16175. number: true,
  16176. min: 0,
  16177. allowPercent: true
  16178. },
  16179. axisDirection: {
  16180. enums: ['horizontal', 'leftward', 'rightward', 'vertical', 'upward', 'downward', 'auto']
  16181. },
  16182. axisDirectionExplicit: {
  16183. enums: ['leftward', 'rightward', 'upward', 'downward']
  16184. },
  16185. axisDirectionPrimary: {
  16186. enums: ['horizontal', 'vertical']
  16187. },
  16188. paddingRelativeTo: {
  16189. enums: ['width', 'height', 'average', 'min', 'max']
  16190. },
  16191. bgWH: {
  16192. number: true,
  16193. min: 0,
  16194. allowPercent: true,
  16195. enums: ['auto'],
  16196. multiple: true
  16197. },
  16198. bgPos: {
  16199. number: true,
  16200. allowPercent: true,
  16201. multiple: true
  16202. },
  16203. bgRelativeTo: {
  16204. enums: ['inner', 'include-padding'],
  16205. multiple: true
  16206. },
  16207. bgRepeat: {
  16208. enums: ['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],
  16209. multiple: true
  16210. },
  16211. bgFit: {
  16212. enums: ['none', 'contain', 'cover'],
  16213. multiple: true
  16214. },
  16215. bgCrossOrigin: {
  16216. enums: ['anonymous', 'use-credentials', 'null'],
  16217. multiple: true
  16218. },
  16219. bgClip: {
  16220. enums: ['none', 'node'],
  16221. multiple: true
  16222. },
  16223. bgContainment: {
  16224. enums: ['inside', 'over'],
  16225. multiple: true
  16226. },
  16227. boxSelection: {
  16228. enums: ['contain', 'overlap', 'none']
  16229. },
  16230. color: {
  16231. color: true
  16232. },
  16233. colors: {
  16234. color: true,
  16235. multiple: true
  16236. },
  16237. fill: {
  16238. enums: ['solid', 'linear-gradient', 'radial-gradient']
  16239. },
  16240. bool: {
  16241. enums: ['yes', 'no']
  16242. },
  16243. bools: {
  16244. enums: ['yes', 'no'],
  16245. multiple: true
  16246. },
  16247. lineStyle: {
  16248. enums: ['solid', 'dotted', 'dashed']
  16249. },
  16250. lineCap: {
  16251. enums: ['butt', 'round', 'square']
  16252. },
  16253. linePosition: {
  16254. enums: ['center', 'inside', 'outside']
  16255. },
  16256. lineJoin: {
  16257. enums: ['round', 'bevel', 'miter']
  16258. },
  16259. borderStyle: {
  16260. enums: ['solid', 'dotted', 'dashed', 'double']
  16261. },
  16262. curveStyle: {
  16263. enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi', 'round-segments', 'round-taxi']
  16264. },
  16265. radiusType: {
  16266. enums: ['arc-radius', 'influence-radius'],
  16267. multiple: true
  16268. },
  16269. fontFamily: {
  16270. regex: '^([\\w- \\"]+(?:\\s*,\\s*[\\w- \\"]+)*)$'
  16271. },
  16272. fontStyle: {
  16273. enums: ['italic', 'normal', 'oblique']
  16274. },
  16275. fontWeight: {
  16276. enums: ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '800', '900', 100, 200, 300, 400, 500, 600, 700, 800, 900]
  16277. },
  16278. textDecoration: {
  16279. enums: ['none', 'underline', 'overline', 'line-through']
  16280. },
  16281. textTransform: {
  16282. enums: ['none', 'uppercase', 'lowercase']
  16283. },
  16284. textWrap: {
  16285. enums: ['none', 'wrap', 'ellipsis']
  16286. },
  16287. textOverflowWrap: {
  16288. enums: ['whitespace', 'anywhere']
  16289. },
  16290. textBackgroundShape: {
  16291. enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'circle']
  16292. },
  16293. nodeShape: {
  16294. 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']
  16295. },
  16296. overlayShape: {
  16297. enums: ['roundrectangle', 'round-rectangle', 'ellipse']
  16298. },
  16299. cornerRadius: {
  16300. number: true,
  16301. min: 0,
  16302. units: 'px|em',
  16303. implicitUnits: 'px',
  16304. enums: ['auto']
  16305. },
  16306. compoundIncludeLabels: {
  16307. enums: ['include', 'exclude']
  16308. },
  16309. arrowShape: {
  16310. enums: ['tee', 'triangle', 'triangle-tee', 'circle-triangle', 'triangle-cross', 'triangle-backcurve', 'vee', 'square', 'circle', 'diamond', 'chevron', 'none']
  16311. },
  16312. arrowFill: {
  16313. enums: ['filled', 'hollow']
  16314. },
  16315. arrowWidth: {
  16316. number: true,
  16317. units: '%|px|em',
  16318. implicitUnits: 'px',
  16319. enums: ['match-line']
  16320. },
  16321. display: {
  16322. enums: ['element', 'none']
  16323. },
  16324. visibility: {
  16325. enums: ['hidden', 'visible']
  16326. },
  16327. zCompoundDepth: {
  16328. enums: ['bottom', 'orphan', 'auto', 'top']
  16329. },
  16330. zIndexCompare: {
  16331. enums: ['auto', 'manual']
  16332. },
  16333. valign: {
  16334. enums: ['top', 'center', 'bottom']
  16335. },
  16336. halign: {
  16337. enums: ['left', 'center', 'right']
  16338. },
  16339. justification: {
  16340. enums: ['left', 'center', 'right', 'auto']
  16341. },
  16342. text: {
  16343. string: true
  16344. },
  16345. data: {
  16346. mapping: true,
  16347. regex: data('data')
  16348. },
  16349. layoutData: {
  16350. mapping: true,
  16351. regex: data('layoutData')
  16352. },
  16353. scratch: {
  16354. mapping: true,
  16355. regex: data('scratch')
  16356. },
  16357. mapData: {
  16358. mapping: true,
  16359. regex: mapData('mapData')
  16360. },
  16361. mapLayoutData: {
  16362. mapping: true,
  16363. regex: mapData('mapLayoutData')
  16364. },
  16365. mapScratch: {
  16366. mapping: true,
  16367. regex: mapData('mapScratch')
  16368. },
  16369. fn: {
  16370. mapping: true,
  16371. fn: true
  16372. },
  16373. url: {
  16374. regexes: urlRegexes,
  16375. singleRegexMatchValue: true
  16376. },
  16377. urls: {
  16378. regexes: urlRegexes,
  16379. singleRegexMatchValue: true,
  16380. multiple: true
  16381. },
  16382. propList: {
  16383. propList: true
  16384. },
  16385. angle: {
  16386. number: true,
  16387. units: 'deg|rad',
  16388. implicitUnits: 'rad'
  16389. },
  16390. textRotation: {
  16391. number: true,
  16392. units: 'deg|rad',
  16393. implicitUnits: 'rad',
  16394. enums: ['none', 'autorotate']
  16395. },
  16396. polygonPointList: {
  16397. number: true,
  16398. multiple: true,
  16399. evenMultiple: true,
  16400. min: -1,
  16401. max: 1,
  16402. unitless: true
  16403. },
  16404. edgeDistances: {
  16405. enums: ['intersection', 'node-position', 'endpoints']
  16406. },
  16407. edgeEndpoint: {
  16408. number: true,
  16409. multiple: true,
  16410. units: '%|px|em|deg|rad',
  16411. implicitUnits: 'px',
  16412. enums: ['inside-to-node', 'outside-to-node', 'outside-to-node-or-label', 'outside-to-line', 'outside-to-line-or-label'],
  16413. singleEnum: true,
  16414. validate: function validate(valArr, unitsArr) {
  16415. switch (valArr.length) {
  16416. case 2:
  16417. // can be % or px only
  16418. return unitsArr[0] !== 'deg' && unitsArr[0] !== 'rad' && unitsArr[1] !== 'deg' && unitsArr[1] !== 'rad';
  16419. case 1:
  16420. // can be enum, deg, or rad only
  16421. return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';
  16422. default:
  16423. return false;
  16424. }
  16425. }
  16426. },
  16427. easing: {
  16428. 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*\\)$'],
  16429. 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']
  16430. },
  16431. gradientDirection: {
  16432. 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
  16433. ]
  16434. },
  16435. boundsExpansion: {
  16436. number: true,
  16437. multiple: true,
  16438. min: 0,
  16439. validate: function validate(valArr) {
  16440. var length = valArr.length;
  16441. return length === 1 || length === 2 || length === 4;
  16442. }
  16443. }
  16444. };
  16445. var diff = {
  16446. zeroNonZero: function zeroNonZero(val1, val2) {
  16447. if ((val1 == null || val2 == null) && val1 !== val2) {
  16448. return true; // null cases could represent any value
  16449. }
  16450. if (val1 == 0 && val2 != 0) {
  16451. return true;
  16452. } else if (val1 != 0 && val2 == 0) {
  16453. return true;
  16454. } else {
  16455. return false;
  16456. }
  16457. },
  16458. any: function any(val1, val2) {
  16459. return val1 != val2;
  16460. },
  16461. emptyNonEmpty: function emptyNonEmpty(str1, str2) {
  16462. var empty1 = emptyString(str1);
  16463. var empty2 = emptyString(str2);
  16464. return empty1 && !empty2 || !empty1 && empty2;
  16465. }
  16466. };
  16467. // define visual style properties
  16468. //
  16469. // - n.b. adding a new group of props may require updates to updateStyleHints()
  16470. // - adding new props to an existing group gets handled automatically
  16471. var t = styfn$2.types;
  16472. var mainLabel = [{
  16473. name: 'label',
  16474. type: t.text,
  16475. triggersBounds: diff.any,
  16476. triggersZOrder: diff.emptyNonEmpty
  16477. }, {
  16478. name: 'text-rotation',
  16479. type: t.textRotation,
  16480. triggersBounds: diff.any
  16481. }, {
  16482. name: 'text-margin-x',
  16483. type: t.bidirectionalSize,
  16484. triggersBounds: diff.any
  16485. }, {
  16486. name: 'text-margin-y',
  16487. type: t.bidirectionalSize,
  16488. triggersBounds: diff.any
  16489. }];
  16490. var sourceLabel = [{
  16491. name: 'source-label',
  16492. type: t.text,
  16493. triggersBounds: diff.any
  16494. }, {
  16495. name: 'source-text-rotation',
  16496. type: t.textRotation,
  16497. triggersBounds: diff.any
  16498. }, {
  16499. name: 'source-text-margin-x',
  16500. type: t.bidirectionalSize,
  16501. triggersBounds: diff.any
  16502. }, {
  16503. name: 'source-text-margin-y',
  16504. type: t.bidirectionalSize,
  16505. triggersBounds: diff.any
  16506. }, {
  16507. name: 'source-text-offset',
  16508. type: t.size,
  16509. triggersBounds: diff.any
  16510. }];
  16511. var targetLabel = [{
  16512. name: 'target-label',
  16513. type: t.text,
  16514. triggersBounds: diff.any
  16515. }, {
  16516. name: 'target-text-rotation',
  16517. type: t.textRotation,
  16518. triggersBounds: diff.any
  16519. }, {
  16520. name: 'target-text-margin-x',
  16521. type: t.bidirectionalSize,
  16522. triggersBounds: diff.any
  16523. }, {
  16524. name: 'target-text-margin-y',
  16525. type: t.bidirectionalSize,
  16526. triggersBounds: diff.any
  16527. }, {
  16528. name: 'target-text-offset',
  16529. type: t.size,
  16530. triggersBounds: diff.any
  16531. }];
  16532. var labelDimensions = [{
  16533. name: 'font-family',
  16534. type: t.fontFamily,
  16535. triggersBounds: diff.any
  16536. }, {
  16537. name: 'font-style',
  16538. type: t.fontStyle,
  16539. triggersBounds: diff.any
  16540. }, {
  16541. name: 'font-weight',
  16542. type: t.fontWeight,
  16543. triggersBounds: diff.any
  16544. }, {
  16545. name: 'font-size',
  16546. type: t.size,
  16547. triggersBounds: diff.any
  16548. }, {
  16549. name: 'text-transform',
  16550. type: t.textTransform,
  16551. triggersBounds: diff.any
  16552. }, {
  16553. name: 'text-wrap',
  16554. type: t.textWrap,
  16555. triggersBounds: diff.any
  16556. }, {
  16557. name: 'text-overflow-wrap',
  16558. type: t.textOverflowWrap,
  16559. triggersBounds: diff.any
  16560. }, {
  16561. name: 'text-max-width',
  16562. type: t.size,
  16563. triggersBounds: diff.any
  16564. }, {
  16565. name: 'text-outline-width',
  16566. type: t.size,
  16567. triggersBounds: diff.any
  16568. }, {
  16569. name: 'line-height',
  16570. type: t.positiveNumber,
  16571. triggersBounds: diff.any
  16572. }];
  16573. var commonLabel = [{
  16574. name: 'text-valign',
  16575. type: t.valign,
  16576. triggersBounds: diff.any
  16577. }, {
  16578. name: 'text-halign',
  16579. type: t.halign,
  16580. triggersBounds: diff.any
  16581. }, {
  16582. name: 'color',
  16583. type: t.color
  16584. }, {
  16585. name: 'text-outline-color',
  16586. type: t.color
  16587. }, {
  16588. name: 'text-outline-opacity',
  16589. type: t.zeroOneNumber
  16590. }, {
  16591. name: 'text-background-color',
  16592. type: t.color
  16593. }, {
  16594. name: 'text-background-opacity',
  16595. type: t.zeroOneNumber
  16596. }, {
  16597. name: 'text-background-padding',
  16598. type: t.size,
  16599. triggersBounds: diff.any
  16600. }, {
  16601. name: 'text-border-opacity',
  16602. type: t.zeroOneNumber
  16603. }, {
  16604. name: 'text-border-color',
  16605. type: t.color
  16606. }, {
  16607. name: 'text-border-width',
  16608. type: t.size,
  16609. triggersBounds: diff.any
  16610. }, {
  16611. name: 'text-border-style',
  16612. type: t.borderStyle,
  16613. triggersBounds: diff.any
  16614. }, {
  16615. name: 'text-background-shape',
  16616. type: t.textBackgroundShape,
  16617. triggersBounds: diff.any
  16618. }, {
  16619. name: 'text-justification',
  16620. type: t.justification
  16621. }, {
  16622. name: 'box-select-labels',
  16623. type: t.bool,
  16624. triggersBounds: diff.any
  16625. }];
  16626. var behavior = [{
  16627. name: 'events',
  16628. type: t.bool,
  16629. triggersZOrder: diff.any
  16630. }, {
  16631. name: 'text-events',
  16632. type: t.bool,
  16633. triggersZOrder: diff.any
  16634. }, {
  16635. name: 'box-selection',
  16636. type: t.boxSelection,
  16637. triggersZOrder: diff.any
  16638. }];
  16639. var visibility = [{
  16640. name: 'display',
  16641. type: t.display,
  16642. triggersZOrder: diff.any,
  16643. triggersBounds: diff.any,
  16644. triggersBoundsOfConnectedEdges: diff.any,
  16645. triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue, ele) {
  16646. if (fromValue === toValue) {
  16647. return false;
  16648. }
  16649. // only if edge is bundled bezier (so as not to affect performance of other edges)
  16650. return ele.pstyle('curve-style').value === 'bezier';
  16651. }
  16652. }, {
  16653. name: 'visibility',
  16654. type: t.visibility,
  16655. triggersZOrder: diff.any
  16656. }, {
  16657. name: 'opacity',
  16658. type: t.zeroOneNumber,
  16659. triggersZOrder: diff.zeroNonZero
  16660. }, {
  16661. name: 'text-opacity',
  16662. type: t.zeroOneNumber
  16663. }, {
  16664. name: 'min-zoomed-font-size',
  16665. type: t.size
  16666. }, {
  16667. name: 'z-compound-depth',
  16668. type: t.zCompoundDepth,
  16669. triggersZOrder: diff.any
  16670. }, {
  16671. name: 'z-index-compare',
  16672. type: t.zIndexCompare,
  16673. triggersZOrder: diff.any
  16674. }, {
  16675. name: 'z-index',
  16676. type: t.number,
  16677. triggersZOrder: diff.any
  16678. }];
  16679. var overlay = [{
  16680. name: 'overlay-padding',
  16681. type: t.size,
  16682. triggersBounds: diff.any
  16683. }, {
  16684. name: 'overlay-color',
  16685. type: t.color
  16686. }, {
  16687. name: 'overlay-opacity',
  16688. type: t.zeroOneNumber,
  16689. triggersBounds: diff.zeroNonZero
  16690. }, {
  16691. name: 'overlay-shape',
  16692. type: t.overlayShape,
  16693. triggersBounds: diff.any
  16694. }, {
  16695. name: 'overlay-corner-radius',
  16696. type: t.cornerRadius
  16697. }];
  16698. var underlay = [{
  16699. name: 'underlay-padding',
  16700. type: t.size,
  16701. triggersBounds: diff.any
  16702. }, {
  16703. name: 'underlay-color',
  16704. type: t.color
  16705. }, {
  16706. name: 'underlay-opacity',
  16707. type: t.zeroOneNumber,
  16708. triggersBounds: diff.zeroNonZero
  16709. }, {
  16710. name: 'underlay-shape',
  16711. type: t.overlayShape,
  16712. triggersBounds: diff.any
  16713. }, {
  16714. name: 'underlay-corner-radius',
  16715. type: t.cornerRadius
  16716. }];
  16717. var transition = [{
  16718. name: 'transition-property',
  16719. type: t.propList
  16720. }, {
  16721. name: 'transition-duration',
  16722. type: t.time
  16723. }, {
  16724. name: 'transition-delay',
  16725. type: t.time
  16726. }, {
  16727. name: 'transition-timing-function',
  16728. type: t.easing
  16729. }];
  16730. var nodeSizeHashOverride = function nodeSizeHashOverride(ele, parsedProp) {
  16731. if (parsedProp.value === 'label') {
  16732. return -ele.poolIndex(); // no hash key hits is using label size (hitrate for perf probably low anyway)
  16733. } else {
  16734. return parsedProp.pfValue;
  16735. }
  16736. };
  16737. var nodeBody = [{
  16738. name: 'height',
  16739. type: t.nodeSize,
  16740. triggersBounds: diff.any,
  16741. hashOverride: nodeSizeHashOverride
  16742. }, {
  16743. name: 'width',
  16744. type: t.nodeSize,
  16745. triggersBounds: diff.any,
  16746. hashOverride: nodeSizeHashOverride
  16747. }, {
  16748. name: 'shape',
  16749. type: t.nodeShape,
  16750. triggersBounds: diff.any
  16751. }, {
  16752. name: 'shape-polygon-points',
  16753. type: t.polygonPointList,
  16754. triggersBounds: diff.any
  16755. }, {
  16756. name: 'corner-radius',
  16757. type: t.cornerRadius
  16758. }, {
  16759. name: 'background-color',
  16760. type: t.color
  16761. }, {
  16762. name: 'background-fill',
  16763. type: t.fill
  16764. }, {
  16765. name: 'background-opacity',
  16766. type: t.zeroOneNumber
  16767. }, {
  16768. name: 'background-blacken',
  16769. type: t.nOneOneNumber
  16770. }, {
  16771. name: 'background-gradient-stop-colors',
  16772. type: t.colors
  16773. }, {
  16774. name: 'background-gradient-stop-positions',
  16775. type: t.percentages
  16776. }, {
  16777. name: 'background-gradient-direction',
  16778. type: t.gradientDirection
  16779. }, {
  16780. name: 'padding',
  16781. type: t.sizeMaybePercent,
  16782. triggersBounds: diff.any
  16783. }, {
  16784. name: 'padding-relative-to',
  16785. type: t.paddingRelativeTo,
  16786. triggersBounds: diff.any
  16787. }, {
  16788. name: 'bounds-expansion',
  16789. type: t.boundsExpansion,
  16790. triggersBounds: diff.any
  16791. }];
  16792. var nodeBorder = [{
  16793. name: 'border-color',
  16794. type: t.color
  16795. }, {
  16796. name: 'border-opacity',
  16797. type: t.zeroOneNumber
  16798. }, {
  16799. name: 'border-width',
  16800. type: t.size,
  16801. triggersBounds: diff.any
  16802. }, {
  16803. name: 'border-style',
  16804. type: t.borderStyle
  16805. }, {
  16806. name: 'border-cap',
  16807. type: t.lineCap
  16808. }, {
  16809. name: 'border-join',
  16810. type: t.lineJoin
  16811. }, {
  16812. name: 'border-dash-pattern',
  16813. type: t.numbers
  16814. }, {
  16815. name: 'border-dash-offset',
  16816. type: t.number
  16817. }, {
  16818. name: 'border-position',
  16819. type: t.linePosition
  16820. }];
  16821. var nodeOutline = [{
  16822. name: 'outline-color',
  16823. type: t.color
  16824. }, {
  16825. name: 'outline-opacity',
  16826. type: t.zeroOneNumber
  16827. }, {
  16828. name: 'outline-width',
  16829. type: t.size,
  16830. triggersBounds: diff.any
  16831. }, {
  16832. name: 'outline-style',
  16833. type: t.borderStyle
  16834. }, {
  16835. name: 'outline-offset',
  16836. type: t.size,
  16837. triggersBounds: diff.any
  16838. }];
  16839. var backgroundImage = [{
  16840. name: 'background-image',
  16841. type: t.urls
  16842. }, {
  16843. name: 'background-image-crossorigin',
  16844. type: t.bgCrossOrigin
  16845. }, {
  16846. name: 'background-image-opacity',
  16847. type: t.zeroOneNumbers
  16848. }, {
  16849. name: 'background-image-containment',
  16850. type: t.bgContainment
  16851. }, {
  16852. name: 'background-image-smoothing',
  16853. type: t.bools
  16854. }, {
  16855. name: 'background-position-x',
  16856. type: t.bgPos
  16857. }, {
  16858. name: 'background-position-y',
  16859. type: t.bgPos
  16860. }, {
  16861. name: 'background-width-relative-to',
  16862. type: t.bgRelativeTo
  16863. }, {
  16864. name: 'background-height-relative-to',
  16865. type: t.bgRelativeTo
  16866. }, {
  16867. name: 'background-repeat',
  16868. type: t.bgRepeat
  16869. }, {
  16870. name: 'background-fit',
  16871. type: t.bgFit
  16872. }, {
  16873. name: 'background-clip',
  16874. type: t.bgClip
  16875. }, {
  16876. name: 'background-width',
  16877. type: t.bgWH
  16878. }, {
  16879. name: 'background-height',
  16880. type: t.bgWH
  16881. }, {
  16882. name: 'background-offset-x',
  16883. type: t.bgPos
  16884. }, {
  16885. name: 'background-offset-y',
  16886. type: t.bgPos
  16887. }];
  16888. var compound = [{
  16889. name: 'position',
  16890. type: t.position,
  16891. triggersBounds: diff.any
  16892. }, {
  16893. name: 'compound-sizing-wrt-labels',
  16894. type: t.compoundIncludeLabels,
  16895. triggersBounds: diff.any
  16896. }, {
  16897. name: 'min-width',
  16898. type: t.size,
  16899. triggersBounds: diff.any
  16900. }, {
  16901. name: 'min-width-bias-left',
  16902. type: t.sizeMaybePercent,
  16903. triggersBounds: diff.any
  16904. }, {
  16905. name: 'min-width-bias-right',
  16906. type: t.sizeMaybePercent,
  16907. triggersBounds: diff.any
  16908. }, {
  16909. name: 'min-height',
  16910. type: t.size,
  16911. triggersBounds: diff.any
  16912. }, {
  16913. name: 'min-height-bias-top',
  16914. type: t.sizeMaybePercent,
  16915. triggersBounds: diff.any
  16916. }, {
  16917. name: 'min-height-bias-bottom',
  16918. type: t.sizeMaybePercent,
  16919. triggersBounds: diff.any
  16920. }];
  16921. var edgeLine = [{
  16922. name: 'line-style',
  16923. type: t.lineStyle
  16924. }, {
  16925. name: 'line-color',
  16926. type: t.color
  16927. }, {
  16928. name: 'line-fill',
  16929. type: t.fill
  16930. }, {
  16931. name: 'line-cap',
  16932. type: t.lineCap
  16933. }, {
  16934. name: 'line-opacity',
  16935. type: t.zeroOneNumber
  16936. }, {
  16937. name: 'line-dash-pattern',
  16938. type: t.numbers
  16939. }, {
  16940. name: 'line-dash-offset',
  16941. type: t.number
  16942. }, {
  16943. name: 'line-outline-width',
  16944. type: t.size
  16945. }, {
  16946. name: 'line-outline-color',
  16947. type: t.color
  16948. }, {
  16949. name: 'line-gradient-stop-colors',
  16950. type: t.colors
  16951. }, {
  16952. name: 'line-gradient-stop-positions',
  16953. type: t.percentages
  16954. }, {
  16955. name: 'curve-style',
  16956. type: t.curveStyle,
  16957. triggersBounds: diff.any,
  16958. triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue) {
  16959. if (fromValue === toValue) {
  16960. return false;
  16961. } // must have diff
  16962. return fromValue === 'bezier' ||
  16963. // remove from bundle
  16964. toValue === 'bezier'; // add to bundle
  16965. }
  16966. }, {
  16967. name: 'haystack-radius',
  16968. type: t.zeroOneNumber,
  16969. triggersBounds: diff.any
  16970. }, {
  16971. name: 'source-endpoint',
  16972. type: t.edgeEndpoint,
  16973. triggersBounds: diff.any
  16974. }, {
  16975. name: 'target-endpoint',
  16976. type: t.edgeEndpoint,
  16977. triggersBounds: diff.any
  16978. }, {
  16979. name: 'control-point-step-size',
  16980. type: t.size,
  16981. triggersBounds: diff.any
  16982. }, {
  16983. name: 'control-point-distances',
  16984. type: t.bidirectionalSizes,
  16985. triggersBounds: diff.any
  16986. }, {
  16987. name: 'control-point-weights',
  16988. type: t.numbers,
  16989. triggersBounds: diff.any
  16990. }, {
  16991. name: 'segment-distances',
  16992. type: t.bidirectionalSizes,
  16993. triggersBounds: diff.any
  16994. }, {
  16995. name: 'segment-weights',
  16996. type: t.numbers,
  16997. triggersBounds: diff.any
  16998. }, {
  16999. name: 'segment-radii',
  17000. type: t.numbers,
  17001. triggersBounds: diff.any
  17002. }, {
  17003. name: 'radius-type',
  17004. type: t.radiusType,
  17005. triggersBounds: diff.any
  17006. }, {
  17007. name: 'taxi-turn',
  17008. type: t.bidirectionalSizeMaybePercent,
  17009. triggersBounds: diff.any
  17010. }, {
  17011. name: 'taxi-turn-min-distance',
  17012. type: t.size,
  17013. triggersBounds: diff.any
  17014. }, {
  17015. name: 'taxi-direction',
  17016. type: t.axisDirection,
  17017. triggersBounds: diff.any
  17018. }, {
  17019. name: 'taxi-radius',
  17020. type: t.number,
  17021. triggersBounds: diff.any
  17022. }, {
  17023. name: 'edge-distances',
  17024. type: t.edgeDistances,
  17025. triggersBounds: diff.any
  17026. }, {
  17027. name: 'arrow-scale',
  17028. type: t.positiveNumber,
  17029. triggersBounds: diff.any
  17030. }, {
  17031. name: 'loop-direction',
  17032. type: t.angle,
  17033. triggersBounds: diff.any
  17034. }, {
  17035. name: 'loop-sweep',
  17036. type: t.angle,
  17037. triggersBounds: diff.any
  17038. }, {
  17039. name: 'source-distance-from-node',
  17040. type: t.size,
  17041. triggersBounds: diff.any
  17042. }, {
  17043. name: 'target-distance-from-node',
  17044. type: t.size,
  17045. triggersBounds: diff.any
  17046. }];
  17047. var ghost = [{
  17048. name: 'ghost',
  17049. type: t.bool,
  17050. triggersBounds: diff.any
  17051. }, {
  17052. name: 'ghost-offset-x',
  17053. type: t.bidirectionalSize,
  17054. triggersBounds: diff.any
  17055. }, {
  17056. name: 'ghost-offset-y',
  17057. type: t.bidirectionalSize,
  17058. triggersBounds: diff.any
  17059. }, {
  17060. name: 'ghost-opacity',
  17061. type: t.zeroOneNumber
  17062. }];
  17063. var core = [{
  17064. name: 'selection-box-color',
  17065. type: t.color
  17066. }, {
  17067. name: 'selection-box-opacity',
  17068. type: t.zeroOneNumber
  17069. }, {
  17070. name: 'selection-box-border-color',
  17071. type: t.color
  17072. }, {
  17073. name: 'selection-box-border-width',
  17074. type: t.size
  17075. }, {
  17076. name: 'active-bg-color',
  17077. type: t.color
  17078. }, {
  17079. name: 'active-bg-opacity',
  17080. type: t.zeroOneNumber
  17081. }, {
  17082. name: 'active-bg-size',
  17083. type: t.size
  17084. }, {
  17085. name: 'outside-texture-bg-color',
  17086. type: t.color
  17087. }, {
  17088. name: 'outside-texture-bg-opacity',
  17089. type: t.zeroOneNumber
  17090. }];
  17091. // pie backgrounds for nodes
  17092. var pie = [];
  17093. styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)
  17094. pie.push({
  17095. name: 'pie-size',
  17096. type: t.sizeMaybePercent
  17097. });
  17098. pie.push({
  17099. name: 'pie-hole',
  17100. type: t.sizeMaybePercent
  17101. });
  17102. pie.push({
  17103. name: 'pie-start-angle',
  17104. type: t.angle
  17105. });
  17106. for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
  17107. pie.push({
  17108. name: 'pie-' + i + '-background-color',
  17109. type: t.color
  17110. });
  17111. pie.push({
  17112. name: 'pie-' + i + '-background-size',
  17113. type: t.percent
  17114. });
  17115. pie.push({
  17116. name: 'pie-' + i + '-background-opacity',
  17117. type: t.zeroOneNumber
  17118. });
  17119. }
  17120. // stripe backgrounds for nodes
  17121. var stripe = [];
  17122. styfn$2.stripeBackgroundN = 16; // because the stripe properties are numbered, give access to a constant N (for renderer use)
  17123. stripe.push({
  17124. name: 'stripe-size',
  17125. type: t.sizeMaybePercent
  17126. });
  17127. stripe.push({
  17128. name: 'stripe-direction',
  17129. type: t.axisDirectionPrimary
  17130. });
  17131. for (var _i = 1; _i <= styfn$2.stripeBackgroundN; _i++) {
  17132. stripe.push({
  17133. name: 'stripe-' + _i + '-background-color',
  17134. type: t.color
  17135. });
  17136. stripe.push({
  17137. name: 'stripe-' + _i + '-background-size',
  17138. type: t.percent
  17139. });
  17140. stripe.push({
  17141. name: 'stripe-' + _i + '-background-opacity',
  17142. type: t.zeroOneNumber
  17143. });
  17144. }
  17145. // edge arrows
  17146. var edgeArrow = [];
  17147. var arrowPrefixes = styfn$2.arrowPrefixes = ['source', 'mid-source', 'target', 'mid-target'];
  17148. [{
  17149. name: 'arrow-shape',
  17150. type: t.arrowShape,
  17151. triggersBounds: diff.any
  17152. }, {
  17153. name: 'arrow-color',
  17154. type: t.color
  17155. }, {
  17156. name: 'arrow-fill',
  17157. type: t.arrowFill
  17158. }, {
  17159. name: 'arrow-width',
  17160. type: t.arrowWidth
  17161. }].forEach(function (prop) {
  17162. arrowPrefixes.forEach(function (prefix) {
  17163. var name = prefix + '-' + prop.name;
  17164. var type = prop.type,
  17165. triggersBounds = prop.triggersBounds;
  17166. edgeArrow.push({
  17167. name: name,
  17168. type: type,
  17169. triggersBounds: triggersBounds
  17170. });
  17171. });
  17172. }, {});
  17173. 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);
  17174. var propGroups = styfn$2.propertyGroups = {
  17175. // common to all eles
  17176. behavior: behavior,
  17177. transition: transition,
  17178. visibility: visibility,
  17179. overlay: overlay,
  17180. underlay: underlay,
  17181. ghost: ghost,
  17182. // labels
  17183. commonLabel: commonLabel,
  17184. labelDimensions: labelDimensions,
  17185. mainLabel: mainLabel,
  17186. sourceLabel: sourceLabel,
  17187. targetLabel: targetLabel,
  17188. // node props
  17189. nodeBody: nodeBody,
  17190. nodeBorder: nodeBorder,
  17191. nodeOutline: nodeOutline,
  17192. backgroundImage: backgroundImage,
  17193. pie: pie,
  17194. stripe: stripe,
  17195. compound: compound,
  17196. // edge props
  17197. edgeLine: edgeLine,
  17198. edgeArrow: edgeArrow,
  17199. core: core
  17200. };
  17201. var propGroupNames = styfn$2.propertyGroupNames = {};
  17202. var propGroupKeys = styfn$2.propertyGroupKeys = Object.keys(propGroups);
  17203. propGroupKeys.forEach(function (key) {
  17204. propGroupNames[key] = propGroups[key].map(function (prop) {
  17205. return prop.name;
  17206. });
  17207. propGroups[key].forEach(function (prop) {
  17208. return prop.groupKey = key;
  17209. });
  17210. });
  17211. // define aliases
  17212. var aliases = styfn$2.aliases = [{
  17213. name: 'content',
  17214. pointsTo: 'label'
  17215. }, {
  17216. name: 'control-point-distance',
  17217. pointsTo: 'control-point-distances'
  17218. }, {
  17219. name: 'control-point-weight',
  17220. pointsTo: 'control-point-weights'
  17221. }, {
  17222. name: 'segment-distance',
  17223. pointsTo: 'segment-distances'
  17224. }, {
  17225. name: 'segment-weight',
  17226. pointsTo: 'segment-weights'
  17227. }, {
  17228. name: 'segment-radius',
  17229. pointsTo: 'segment-radii'
  17230. }, {
  17231. name: 'edge-text-rotation',
  17232. pointsTo: 'text-rotation'
  17233. }, {
  17234. name: 'padding-left',
  17235. pointsTo: 'padding'
  17236. }, {
  17237. name: 'padding-right',
  17238. pointsTo: 'padding'
  17239. }, {
  17240. name: 'padding-top',
  17241. pointsTo: 'padding'
  17242. }, {
  17243. name: 'padding-bottom',
  17244. pointsTo: 'padding'
  17245. }];
  17246. // list of property names
  17247. styfn$2.propertyNames = props.map(function (p) {
  17248. return p.name;
  17249. });
  17250. // allow access of properties by name ( e.g. style.properties.height )
  17251. for (var _i2 = 0; _i2 < props.length; _i2++) {
  17252. var prop = props[_i2];
  17253. props[prop.name] = prop; // allow lookup by name
  17254. }
  17255. // map aliases
  17256. for (var _i3 = 0; _i3 < aliases.length; _i3++) {
  17257. var alias = aliases[_i3];
  17258. var pointsToProp = props[alias.pointsTo];
  17259. var aliasProp = {
  17260. name: alias.name,
  17261. alias: true,
  17262. pointsTo: pointsToProp
  17263. };
  17264. // add alias prop for parsing
  17265. props.push(aliasProp);
  17266. props[alias.name] = aliasProp; // allow lookup by name
  17267. }
  17268. })();
  17269. styfn$2.getDefaultProperty = function (name) {
  17270. return this.getDefaultProperties()[name];
  17271. };
  17272. styfn$2.getDefaultProperties = function () {
  17273. var _p = this._private;
  17274. if (_p.defaultProperties != null) {
  17275. return _p.defaultProperties;
  17276. }
  17277. var rawProps = extend({
  17278. // core props
  17279. 'selection-box-color': '#ddd',
  17280. 'selection-box-opacity': 0.65,
  17281. 'selection-box-border-color': '#aaa',
  17282. 'selection-box-border-width': 1,
  17283. 'active-bg-color': 'black',
  17284. 'active-bg-opacity': 0.15,
  17285. 'active-bg-size': 30,
  17286. 'outside-texture-bg-color': '#000',
  17287. 'outside-texture-bg-opacity': 0.125,
  17288. // common node/edge props
  17289. 'events': 'yes',
  17290. 'text-events': 'no',
  17291. 'text-valign': 'top',
  17292. 'text-halign': 'center',
  17293. 'text-justification': 'auto',
  17294. 'line-height': 1,
  17295. 'color': '#000',
  17296. 'box-selection': 'contain',
  17297. 'text-outline-color': '#000',
  17298. 'text-outline-width': 0,
  17299. 'text-outline-opacity': 1,
  17300. 'text-opacity': 1,
  17301. 'text-decoration': 'none',
  17302. 'text-transform': 'none',
  17303. 'text-wrap': 'none',
  17304. 'text-overflow-wrap': 'whitespace',
  17305. 'text-max-width': 9999,
  17306. 'text-background-color': '#000',
  17307. 'text-background-opacity': 0,
  17308. 'text-background-shape': 'rectangle',
  17309. 'text-background-padding': 0,
  17310. 'text-border-opacity': 0,
  17311. 'text-border-width': 0,
  17312. 'text-border-style': 'solid',
  17313. 'text-border-color': '#000',
  17314. 'font-family': 'Helvetica Neue, Helvetica, sans-serif',
  17315. 'font-style': 'normal',
  17316. 'font-weight': 'normal',
  17317. 'font-size': 16,
  17318. 'min-zoomed-font-size': 0,
  17319. 'text-rotation': 'none',
  17320. 'source-text-rotation': 'none',
  17321. 'target-text-rotation': 'none',
  17322. 'visibility': 'visible',
  17323. 'display': 'element',
  17324. 'opacity': 1,
  17325. 'z-compound-depth': 'auto',
  17326. 'z-index-compare': 'auto',
  17327. 'z-index': 0,
  17328. 'label': '',
  17329. 'text-margin-x': 0,
  17330. 'text-margin-y': 0,
  17331. 'source-label': '',
  17332. 'source-text-offset': 0,
  17333. 'source-text-margin-x': 0,
  17334. 'source-text-margin-y': 0,
  17335. 'target-label': '',
  17336. 'target-text-offset': 0,
  17337. 'target-text-margin-x': 0,
  17338. 'target-text-margin-y': 0,
  17339. 'overlay-opacity': 0,
  17340. 'overlay-color': '#000',
  17341. 'overlay-padding': 10,
  17342. 'overlay-shape': 'round-rectangle',
  17343. 'overlay-corner-radius': 'auto',
  17344. 'underlay-opacity': 0,
  17345. 'underlay-color': '#000',
  17346. 'underlay-padding': 10,
  17347. 'underlay-shape': 'round-rectangle',
  17348. 'underlay-corner-radius': 'auto',
  17349. 'transition-property': 'none',
  17350. 'transition-duration': 0,
  17351. 'transition-delay': 0,
  17352. 'transition-timing-function': 'linear',
  17353. 'box-select-labels': 'no',
  17354. // node props
  17355. 'background-blacken': 0,
  17356. 'background-color': '#999',
  17357. 'background-fill': 'solid',
  17358. 'background-opacity': 1,
  17359. 'background-image': 'none',
  17360. 'background-image-crossorigin': 'anonymous',
  17361. 'background-image-opacity': 1,
  17362. 'background-image-containment': 'inside',
  17363. 'background-image-smoothing': 'yes',
  17364. 'background-position-x': '50%',
  17365. 'background-position-y': '50%',
  17366. 'background-offset-x': 0,
  17367. 'background-offset-y': 0,
  17368. 'background-width-relative-to': 'include-padding',
  17369. 'background-height-relative-to': 'include-padding',
  17370. 'background-repeat': 'no-repeat',
  17371. 'background-fit': 'none',
  17372. 'background-clip': 'node',
  17373. 'background-width': 'auto',
  17374. 'background-height': 'auto',
  17375. 'border-color': '#000',
  17376. 'border-opacity': 1,
  17377. 'border-width': 0,
  17378. 'border-style': 'solid',
  17379. 'border-dash-pattern': [4, 2],
  17380. 'border-dash-offset': 0,
  17381. 'border-cap': 'butt',
  17382. 'border-join': 'miter',
  17383. 'border-position': 'center',
  17384. 'outline-color': '#999',
  17385. 'outline-opacity': 1,
  17386. 'outline-width': 0,
  17387. 'outline-offset': 0,
  17388. 'outline-style': 'solid',
  17389. 'height': 30,
  17390. 'width': 30,
  17391. 'shape': 'ellipse',
  17392. 'shape-polygon-points': '-1, -1, 1, -1, 1, 1, -1, 1',
  17393. 'corner-radius': 'auto',
  17394. 'bounds-expansion': 0,
  17395. // node gradient
  17396. 'background-gradient-direction': 'to-bottom',
  17397. 'background-gradient-stop-colors': '#999',
  17398. 'background-gradient-stop-positions': '0%',
  17399. // ghost props
  17400. 'ghost': 'no',
  17401. 'ghost-offset-y': 0,
  17402. 'ghost-offset-x': 0,
  17403. 'ghost-opacity': 0,
  17404. // compound props
  17405. 'padding': 0,
  17406. 'padding-relative-to': 'width',
  17407. 'position': 'origin',
  17408. 'compound-sizing-wrt-labels': 'include',
  17409. 'min-width': 0,
  17410. 'min-width-bias-left': 0,
  17411. 'min-width-bias-right': 0,
  17412. 'min-height': 0,
  17413. 'min-height-bias-top': 0,
  17414. 'min-height-bias-bottom': 0
  17415. }, {
  17416. // node pie bg
  17417. 'pie-size': '100%',
  17418. 'pie-hole': 0,
  17419. 'pie-start-angle': '0deg'
  17420. }, [{
  17421. name: 'pie-{{i}}-background-color',
  17422. value: 'black'
  17423. }, {
  17424. name: 'pie-{{i}}-background-size',
  17425. value: '0%'
  17426. }, {
  17427. name: 'pie-{{i}}-background-opacity',
  17428. value: 1
  17429. }].reduce(function (css, prop) {
  17430. for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
  17431. var name = prop.name.replace('{{i}}', i);
  17432. var val = prop.value;
  17433. css[name] = val;
  17434. }
  17435. return css;
  17436. }, {}), {
  17437. // node stripes bg
  17438. 'stripe-size': '100%',
  17439. 'stripe-direction': 'horizontal'
  17440. }, [{
  17441. name: 'stripe-{{i}}-background-color',
  17442. value: 'black'
  17443. }, {
  17444. name: 'stripe-{{i}}-background-size',
  17445. value: '0%'
  17446. }, {
  17447. name: 'stripe-{{i}}-background-opacity',
  17448. value: 1
  17449. }].reduce(function (css, prop) {
  17450. for (var i = 1; i <= styfn$2.stripeBackgroundN; i++) {
  17451. var name = prop.name.replace('{{i}}', i);
  17452. var val = prop.value;
  17453. css[name] = val;
  17454. }
  17455. return css;
  17456. }, {}), {
  17457. // edge props
  17458. 'line-style': 'solid',
  17459. 'line-color': '#999',
  17460. 'line-fill': 'solid',
  17461. 'line-cap': 'butt',
  17462. 'line-opacity': 1,
  17463. 'line-outline-width': 0,
  17464. 'line-outline-color': '#000',
  17465. 'line-gradient-stop-colors': '#999',
  17466. 'line-gradient-stop-positions': '0%',
  17467. 'control-point-step-size': 40,
  17468. 'control-point-weights': 0.5,
  17469. 'segment-weights': 0.5,
  17470. 'segment-distances': 20,
  17471. 'segment-radii': 15,
  17472. 'radius-type': 'arc-radius',
  17473. 'taxi-turn': '50%',
  17474. 'taxi-radius': 15,
  17475. 'taxi-turn-min-distance': 10,
  17476. 'taxi-direction': 'auto',
  17477. 'edge-distances': 'intersection',
  17478. 'curve-style': 'haystack',
  17479. 'haystack-radius': 0,
  17480. 'arrow-scale': 1,
  17481. 'loop-direction': '-45deg',
  17482. 'loop-sweep': '-90deg',
  17483. 'source-distance-from-node': 0,
  17484. 'target-distance-from-node': 0,
  17485. 'source-endpoint': 'outside-to-node',
  17486. 'target-endpoint': 'outside-to-node',
  17487. 'line-dash-pattern': [6, 3],
  17488. 'line-dash-offset': 0
  17489. }, [{
  17490. name: 'arrow-shape',
  17491. value: 'none'
  17492. }, {
  17493. name: 'arrow-color',
  17494. value: '#999'
  17495. }, {
  17496. name: 'arrow-fill',
  17497. value: 'filled'
  17498. }, {
  17499. name: 'arrow-width',
  17500. value: 1
  17501. }].reduce(function (css, prop) {
  17502. styfn$2.arrowPrefixes.forEach(function (prefix) {
  17503. var name = prefix + '-' + prop.name;
  17504. var val = prop.value;
  17505. css[name] = val;
  17506. });
  17507. return css;
  17508. }, {}));
  17509. var parsedProps = {};
  17510. for (var i = 0; i < this.properties.length; i++) {
  17511. var prop = this.properties[i];
  17512. if (prop.pointsTo) {
  17513. continue;
  17514. }
  17515. var name = prop.name;
  17516. var val = rawProps[name];
  17517. var parsedProp = this.parse(name, val);
  17518. parsedProps[name] = parsedProp;
  17519. }
  17520. _p.defaultProperties = parsedProps;
  17521. return _p.defaultProperties;
  17522. };
  17523. styfn$2.addDefaultStylesheet = function () {
  17524. this.selector(':parent').css({
  17525. 'shape': 'rectangle',
  17526. 'padding': 10,
  17527. 'background-color': '#eee',
  17528. 'border-color': '#ccc',
  17529. 'border-width': 1
  17530. }).selector('edge').css({
  17531. 'width': 3
  17532. }).selector(':loop').css({
  17533. 'curve-style': 'bezier'
  17534. }).selector('edge:compound').css({
  17535. 'curve-style': 'bezier',
  17536. 'source-endpoint': 'outside-to-line',
  17537. 'target-endpoint': 'outside-to-line'
  17538. }).selector(':selected').css({
  17539. 'background-color': '#0169D9',
  17540. 'line-color': '#0169D9',
  17541. 'source-arrow-color': '#0169D9',
  17542. 'target-arrow-color': '#0169D9',
  17543. 'mid-source-arrow-color': '#0169D9',
  17544. 'mid-target-arrow-color': '#0169D9'
  17545. }).selector(':parent:selected').css({
  17546. 'background-color': '#CCE1F9',
  17547. 'border-color': '#aec8e5'
  17548. }).selector(':active').css({
  17549. 'overlay-color': 'black',
  17550. 'overlay-padding': 10,
  17551. 'overlay-opacity': 0.25
  17552. });
  17553. this.defaultLength = this.length;
  17554. };
  17555. var styfn$1 = {};
  17556. // a caching layer for property parsing
  17557. styfn$1.parse = function (name, value, propIsBypass, propIsFlat) {
  17558. var self = this;
  17559. // function values can't be cached in all cases, and there isn't much benefit of caching them anyway
  17560. if (fn$6(value)) {
  17561. return self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  17562. }
  17563. var flatKey = propIsFlat === 'mapping' || propIsFlat === true || propIsFlat === false || propIsFlat == null ? 'dontcare' : propIsFlat;
  17564. var bypassKey = propIsBypass ? 't' : 'f';
  17565. var valueKey = '' + value;
  17566. var argHash = hashStrings(name, valueKey, bypassKey, flatKey);
  17567. var propCache = self.propCache = self.propCache || [];
  17568. var ret;
  17569. if (!(ret = propCache[argHash])) {
  17570. ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  17571. }
  17572. // - bypasses can't be shared b/c the value can be changed by animations or otherwise overridden
  17573. // - mappings can't be shared b/c mappings are per-element
  17574. if (propIsBypass || propIsFlat === 'mapping') {
  17575. // need a copy since props are mutated later in their lifecycles
  17576. ret = copy(ret);
  17577. if (ret) {
  17578. ret.value = copy(ret.value); // because it could be an array, e.g. colour
  17579. }
  17580. }
  17581. return ret;
  17582. };
  17583. styfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {
  17584. var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);
  17585. if (!prop && value != null) {
  17586. warn("The style property `".concat(name, ": ").concat(value, "` is invalid"));
  17587. }
  17588. if (prop && (prop.name === 'width' || prop.name === 'height') && value === 'label') {
  17589. warn('The style value of `label` is deprecated for `' + prop.name + '`');
  17590. }
  17591. return prop;
  17592. };
  17593. // parse a property; return null on invalid; return parsed property otherwise
  17594. // fields :
  17595. // - name : the name of the property
  17596. // - value : the parsed, native-typed value of the property
  17597. // - strValue : a string value that represents the property value in valid css
  17598. // - bypass : true iff the property is a bypass property
  17599. styfn$1.parseImpl = function (name, value, propIsBypass, propIsFlat) {
  17600. var self = this;
  17601. name = camel2dash(name); // make sure the property name is in dash form (e.g. 'property-name' not 'propertyName')
  17602. var property = self.properties[name];
  17603. var passedValue = value;
  17604. var types = self.types;
  17605. if (!property) {
  17606. return null;
  17607. } // return null on property of unknown name
  17608. if (value === undefined) {
  17609. return null;
  17610. } // can't assign undefined
  17611. // the property may be an alias
  17612. if (property.alias) {
  17613. property = property.pointsTo;
  17614. name = property.name;
  17615. }
  17616. var valueIsString = string(value);
  17617. if (valueIsString) {
  17618. // trim the value to make parsing easier
  17619. value = value.trim();
  17620. }
  17621. var type = property.type;
  17622. if (!type) {
  17623. return null;
  17624. } // no type, no luck
  17625. // check if bypass is null or empty string (i.e. indication to delete bypass property)
  17626. if (propIsBypass && (value === '' || value === null)) {
  17627. return {
  17628. name: name,
  17629. value: value,
  17630. bypass: true,
  17631. deleteBypass: true
  17632. };
  17633. }
  17634. // check if value is a function used as a mapper
  17635. if (fn$6(value)) {
  17636. return {
  17637. name: name,
  17638. value: value,
  17639. strValue: 'fn',
  17640. mapped: types.fn,
  17641. bypass: propIsBypass
  17642. };
  17643. }
  17644. // check if value is mapped
  17645. var data, mapData;
  17646. 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))) {
  17647. if (propIsBypass) {
  17648. return false;
  17649. } // mappers not allowed in bypass
  17650. var mapped = types.data;
  17651. return {
  17652. name: name,
  17653. value: data,
  17654. strValue: '' + value,
  17655. mapped: mapped,
  17656. field: data[1],
  17657. bypass: propIsBypass
  17658. };
  17659. } else if (value.length >= 10 && value[0] === 'm' && (mapData = new RegExp(types.mapData.regex).exec(value))) {
  17660. if (propIsBypass) {
  17661. return false;
  17662. } // mappers not allowed in bypass
  17663. if (type.multiple) {
  17664. return false;
  17665. } // impossible to map to num
  17666. var _mapped = types.mapData;
  17667. // we can map only if the type is a colour or a number
  17668. if (!(type.color || type.number)) {
  17669. return false;
  17670. }
  17671. var valueMin = this.parse(name, mapData[4]); // parse to validate
  17672. if (!valueMin || valueMin.mapped) {
  17673. return false;
  17674. } // can't be invalid or mapped
  17675. var valueMax = this.parse(name, mapData[5]); // parse to validate
  17676. if (!valueMax || valueMax.mapped) {
  17677. return false;
  17678. } // can't be invalid or mapped
  17679. // check if valueMin and valueMax are the same
  17680. if (valueMin.pfValue === valueMax.pfValue || valueMin.strValue === valueMax.strValue) {
  17681. warn('`' + name + ': ' + value + '` is not a valid mapper because the output range is zero; converting to `' + name + ': ' + valueMin.strValue + '`');
  17682. return this.parse(name, valueMin.strValue); // can't make much of a mapper without a range
  17683. } else if (type.color) {
  17684. var c1 = valueMin.value;
  17685. var c2 = valueMax.value;
  17686. var same = c1[0] === c2[0] // red
  17687. && c1[1] === c2[1] // green
  17688. && c1[2] === c2[2] // blue
  17689. && (
  17690. // optional alpha
  17691. c1[3] === c2[3] // same alpha outright
  17692. || (c1[3] == null || c1[3] === 1 // full opacity for colour 1?
  17693. ) && (c2[3] == null || c2[3] === 1) // full opacity for colour 2?
  17694. );
  17695. if (same) {
  17696. return false;
  17697. } // can't make a mapper without a range
  17698. }
  17699. return {
  17700. name: name,
  17701. value: mapData,
  17702. strValue: '' + value,
  17703. mapped: _mapped,
  17704. field: mapData[1],
  17705. fieldMin: parseFloat(mapData[2]),
  17706. // min & max are numeric
  17707. fieldMax: parseFloat(mapData[3]),
  17708. valueMin: valueMin.value,
  17709. valueMax: valueMax.value,
  17710. bypass: propIsBypass
  17711. };
  17712. }
  17713. if (type.multiple && propIsFlat !== 'multiple') {
  17714. var vals;
  17715. if (valueIsString) {
  17716. vals = value.split(/\s+/);
  17717. } else if (array(value)) {
  17718. vals = value;
  17719. } else {
  17720. vals = [value];
  17721. }
  17722. if (type.evenMultiple && vals.length % 2 !== 0) {
  17723. return null;
  17724. }
  17725. var valArr = [];
  17726. var unitsArr = [];
  17727. var pfValArr = [];
  17728. var strVal = '';
  17729. var hasEnum = false;
  17730. for (var i = 0; i < vals.length; i++) {
  17731. var p = self.parse(name, vals[i], propIsBypass, 'multiple');
  17732. hasEnum = hasEnum || string(p.value);
  17733. valArr.push(p.value);
  17734. pfValArr.push(p.pfValue != null ? p.pfValue : p.value);
  17735. unitsArr.push(p.units);
  17736. strVal += (i > 0 ? ' ' : '') + p.strValue;
  17737. }
  17738. if (type.validate && !type.validate(valArr, unitsArr)) {
  17739. return null;
  17740. }
  17741. if (type.singleEnum && hasEnum) {
  17742. if (valArr.length === 1 && string(valArr[0])) {
  17743. return {
  17744. name: name,
  17745. value: valArr[0],
  17746. strValue: valArr[0],
  17747. bypass: propIsBypass
  17748. };
  17749. } else {
  17750. return null;
  17751. }
  17752. }
  17753. return {
  17754. name: name,
  17755. value: valArr,
  17756. pfValue: pfValArr,
  17757. strValue: strVal,
  17758. bypass: propIsBypass,
  17759. units: unitsArr
  17760. };
  17761. }
  17762. // several types also allow enums
  17763. var checkEnums = function checkEnums() {
  17764. for (var _i = 0; _i < type.enums.length; _i++) {
  17765. var en = type.enums[_i];
  17766. if (en === value) {
  17767. return {
  17768. name: name,
  17769. value: value,
  17770. strValue: '' + value,
  17771. bypass: propIsBypass
  17772. };
  17773. }
  17774. }
  17775. return null;
  17776. };
  17777. // check the type and return the appropriate object
  17778. if (type.number) {
  17779. var units;
  17780. var implicitUnits = 'px'; // not set => px
  17781. if (type.units) {
  17782. // use specified units if set
  17783. units = type.units;
  17784. }
  17785. if (type.implicitUnits) {
  17786. implicitUnits = type.implicitUnits;
  17787. }
  17788. if (!type.unitless) {
  17789. if (valueIsString) {
  17790. var unitsRegex = 'px|em' + (type.allowPercent ? '|\\%' : '');
  17791. if (units) {
  17792. unitsRegex = units;
  17793. } // only allow explicit units if so set
  17794. var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');
  17795. if (match) {
  17796. value = match[1];
  17797. units = match[2] || implicitUnits;
  17798. }
  17799. } else if (!units || type.implicitUnits) {
  17800. units = implicitUnits; // implicitly px if unspecified
  17801. }
  17802. }
  17803. value = parseFloat(value);
  17804. // if not a number and enums not allowed, then the value is invalid
  17805. if (isNaN(value) && type.enums === undefined) {
  17806. return null;
  17807. }
  17808. // check if this number type also accepts special keywords in place of numbers
  17809. // (i.e. `left`, `auto`, etc)
  17810. if (isNaN(value) && type.enums !== undefined) {
  17811. value = passedValue;
  17812. return checkEnums();
  17813. }
  17814. // check if value must be an integer
  17815. if (type.integer && !integer(value)) {
  17816. return null;
  17817. }
  17818. // check value is within range
  17819. if (type.min !== undefined && (value < type.min || type.strictMin && value === type.min) || type.max !== undefined && (value > type.max || type.strictMax && value === type.max)) {
  17820. return null;
  17821. }
  17822. var ret = {
  17823. name: name,
  17824. value: value,
  17825. strValue: '' + value + (units ? units : ''),
  17826. units: units,
  17827. bypass: propIsBypass
  17828. };
  17829. // normalise value in pixels
  17830. if (type.unitless || units !== 'px' && units !== 'em') {
  17831. ret.pfValue = value;
  17832. } else {
  17833. ret.pfValue = units === 'px' || !units ? value : this.getEmSizeInPixels() * value;
  17834. }
  17835. // normalise value in ms
  17836. if (units === 'ms' || units === 's') {
  17837. ret.pfValue = units === 'ms' ? value : 1000 * value;
  17838. }
  17839. // normalise value in rad
  17840. if (units === 'deg' || units === 'rad') {
  17841. ret.pfValue = units === 'rad' ? value : deg2rad(value);
  17842. }
  17843. // normalize value in %
  17844. if (units === '%') {
  17845. ret.pfValue = value / 100;
  17846. }
  17847. return ret;
  17848. } else if (type.propList) {
  17849. var props = [];
  17850. var propsStr = '' + value;
  17851. if (propsStr === 'none') ; else {
  17852. // go over each prop
  17853. var propsSplit = propsStr.split(/\s*,\s*|\s+/);
  17854. for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {
  17855. var propName = propsSplit[_i2].trim();
  17856. if (self.properties[propName]) {
  17857. props.push(propName);
  17858. } else {
  17859. warn('`' + propName + '` is not a valid property name');
  17860. }
  17861. }
  17862. if (props.length === 0) {
  17863. return null;
  17864. }
  17865. }
  17866. return {
  17867. name: name,
  17868. value: props,
  17869. strValue: props.length === 0 ? 'none' : props.join(' '),
  17870. bypass: propIsBypass
  17871. };
  17872. } else if (type.color) {
  17873. var tuple = color2tuple(value);
  17874. if (!tuple) {
  17875. return null;
  17876. }
  17877. return {
  17878. name: name,
  17879. value: tuple,
  17880. pfValue: tuple,
  17881. strValue: 'rgb(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')',
  17882. // n.b. no spaces b/c of multiple support
  17883. bypass: propIsBypass
  17884. };
  17885. } else if (type.regex || type.regexes) {
  17886. // first check enums
  17887. if (type.enums) {
  17888. var enumProp = checkEnums();
  17889. if (enumProp) {
  17890. return enumProp;
  17891. }
  17892. }
  17893. var regexes = type.regexes ? type.regexes : [type.regex];
  17894. for (var _i3 = 0; _i3 < regexes.length; _i3++) {
  17895. var regex = new RegExp(regexes[_i3]); // make a regex from the type string
  17896. var m = regex.exec(value);
  17897. if (m) {
  17898. // regex matches
  17899. return {
  17900. name: name,
  17901. value: type.singleRegexMatchValue ? m[1] : m,
  17902. strValue: '' + value,
  17903. bypass: propIsBypass
  17904. };
  17905. }
  17906. }
  17907. return null; // didn't match any
  17908. } else if (type.string) {
  17909. // just return
  17910. return {
  17911. name: name,
  17912. value: '' + value,
  17913. strValue: '' + value,
  17914. bypass: propIsBypass
  17915. };
  17916. } else if (type.enums) {
  17917. // check enums last because it's a combo type in others
  17918. return checkEnums();
  17919. } else {
  17920. return null; // not a type we can handle
  17921. }
  17922. };
  17923. var _Style = function Style(cy) {
  17924. if (!(this instanceof _Style)) {
  17925. return new _Style(cy);
  17926. }
  17927. if (!core(cy)) {
  17928. error('A style must have a core reference');
  17929. return;
  17930. }
  17931. this._private = {
  17932. cy: cy,
  17933. coreStyle: {}
  17934. };
  17935. this.length = 0;
  17936. this.resetToDefault();
  17937. };
  17938. var styfn = _Style.prototype;
  17939. styfn.instanceString = function () {
  17940. return 'style';
  17941. };
  17942. // remove all contexts
  17943. styfn.clear = function () {
  17944. var _p = this._private;
  17945. var cy = _p.cy;
  17946. var eles = cy.elements();
  17947. for (var i = 0; i < this.length; i++) {
  17948. this[i] = undefined;
  17949. }
  17950. this.length = 0;
  17951. _p.contextStyles = {};
  17952. _p.propDiffs = {};
  17953. this.cleanElements(eles, true);
  17954. eles.forEach(function (ele) {
  17955. var ele_p = ele[0]._private;
  17956. ele_p.styleDirty = true;
  17957. ele_p.appliedInitStyle = false;
  17958. });
  17959. return this; // chaining
  17960. };
  17961. styfn.resetToDefault = function () {
  17962. this.clear();
  17963. this.addDefaultStylesheet();
  17964. return this;
  17965. };
  17966. // builds a style object for the 'core' selector
  17967. styfn.core = function (propName) {
  17968. return this._private.coreStyle[propName] || this.getDefaultProperty(propName);
  17969. };
  17970. // create a new context from the specified selector string and switch to that context
  17971. styfn.selector = function (selectorStr) {
  17972. // 'core' is a special case and does not need a selector
  17973. var selector = selectorStr === 'core' ? null : new Selector(selectorStr);
  17974. var i = this.length++; // new context means new index
  17975. this[i] = {
  17976. selector: selector,
  17977. properties: [],
  17978. mappedProperties: [],
  17979. index: i
  17980. };
  17981. return this; // chaining
  17982. };
  17983. // add one or many css rules to the current context
  17984. styfn.css = function () {
  17985. var self = this;
  17986. var args = arguments;
  17987. if (args.length === 1) {
  17988. var map = args[0];
  17989. for (var i = 0; i < self.properties.length; i++) {
  17990. var prop = self.properties[i];
  17991. var mapVal = map[prop.name];
  17992. if (mapVal === undefined) {
  17993. mapVal = map[dash2camel(prop.name)];
  17994. }
  17995. if (mapVal !== undefined) {
  17996. this.cssRule(prop.name, mapVal);
  17997. }
  17998. }
  17999. } else if (args.length === 2) {
  18000. this.cssRule(args[0], args[1]);
  18001. }
  18002. // do nothing if args are invalid
  18003. return this; // chaining
  18004. };
  18005. styfn.style = styfn.css;
  18006. // add a single css rule to the current context
  18007. styfn.cssRule = function (name, value) {
  18008. // name-value pair
  18009. var property = this.parse(name, value);
  18010. // add property to current context if valid
  18011. if (property) {
  18012. var i = this.length - 1;
  18013. this[i].properties.push(property);
  18014. this[i].properties[property.name] = property; // allow access by name as well
  18015. if (property.name.match(/pie-(\d+)-background-size/) && property.value) {
  18016. this._private.hasPie = true;
  18017. }
  18018. if (property.name.match(/stripe-(\d+)-background-size/) && property.value) {
  18019. this._private.hasStripe = true;
  18020. }
  18021. if (property.mapped) {
  18022. this[i].mappedProperties.push(property);
  18023. }
  18024. // add to core style if necessary
  18025. var currentSelectorIsCore = !this[i].selector;
  18026. if (currentSelectorIsCore) {
  18027. this._private.coreStyle[property.name] = property;
  18028. }
  18029. }
  18030. return this; // chaining
  18031. };
  18032. styfn.append = function (style) {
  18033. if (stylesheet(style)) {
  18034. style.appendToStyle(this);
  18035. } else if (array(style)) {
  18036. this.appendFromJson(style);
  18037. } else if (string(style)) {
  18038. this.appendFromString(style);
  18039. } // you probably wouldn't want to append a Style, since you'd duplicate the default parts
  18040. return this;
  18041. };
  18042. // static function
  18043. _Style.fromJson = function (cy, json) {
  18044. var style = new _Style(cy);
  18045. style.fromJson(json);
  18046. return style;
  18047. };
  18048. _Style.fromString = function (cy, string) {
  18049. return new _Style(cy).fromString(string);
  18050. };
  18051. [styfn$8, styfn$7, styfn$6, styfn$5, styfn$4, styfn$3, styfn$2, styfn$1].forEach(function (props) {
  18052. extend(styfn, props);
  18053. });
  18054. _Style.types = styfn.types;
  18055. _Style.properties = styfn.properties;
  18056. _Style.propertyGroups = styfn.propertyGroups;
  18057. _Style.propertyGroupNames = styfn.propertyGroupNames;
  18058. _Style.propertyGroupKeys = styfn.propertyGroupKeys;
  18059. var corefn$2 = {
  18060. style: function style(newStyle) {
  18061. if (newStyle) {
  18062. var s = this.setStyle(newStyle);
  18063. s.update();
  18064. }
  18065. return this._private.style;
  18066. },
  18067. setStyle: function setStyle(style) {
  18068. var _p = this._private;
  18069. if (stylesheet(style)) {
  18070. _p.style = style.generateStyle(this);
  18071. } else if (array(style)) {
  18072. _p.style = _Style.fromJson(this, style);
  18073. } else if (string(style)) {
  18074. _p.style = _Style.fromString(this, style);
  18075. } else {
  18076. _p.style = _Style(this);
  18077. }
  18078. return _p.style;
  18079. },
  18080. // e.g. cy.data() changed => recalc ele mappers
  18081. updateStyle: function updateStyle() {
  18082. this.mutableElements().updateStyle(); // just send to all eles
  18083. }
  18084. };
  18085. var defaultSelectionType = 'single';
  18086. var corefn$1 = {
  18087. autolock: function autolock(bool) {
  18088. if (bool !== undefined) {
  18089. this._private.autolock = bool ? true : false;
  18090. } else {
  18091. return this._private.autolock;
  18092. }
  18093. return this; // chaining
  18094. },
  18095. autoungrabify: function autoungrabify(bool) {
  18096. if (bool !== undefined) {
  18097. this._private.autoungrabify = bool ? true : false;
  18098. } else {
  18099. return this._private.autoungrabify;
  18100. }
  18101. return this; // chaining
  18102. },
  18103. autounselectify: function autounselectify(bool) {
  18104. if (bool !== undefined) {
  18105. this._private.autounselectify = bool ? true : false;
  18106. } else {
  18107. return this._private.autounselectify;
  18108. }
  18109. return this; // chaining
  18110. },
  18111. selectionType: function selectionType(selType) {
  18112. var _p = this._private;
  18113. if (_p.selectionType == null) {
  18114. _p.selectionType = defaultSelectionType;
  18115. }
  18116. if (selType !== undefined) {
  18117. if (selType === 'additive' || selType === 'single') {
  18118. _p.selectionType = selType;
  18119. }
  18120. } else {
  18121. return _p.selectionType;
  18122. }
  18123. return this;
  18124. },
  18125. panningEnabled: function panningEnabled(bool) {
  18126. if (bool !== undefined) {
  18127. this._private.panningEnabled = bool ? true : false;
  18128. } else {
  18129. return this._private.panningEnabled;
  18130. }
  18131. return this; // chaining
  18132. },
  18133. userPanningEnabled: function userPanningEnabled(bool) {
  18134. if (bool !== undefined) {
  18135. this._private.userPanningEnabled = bool ? true : false;
  18136. } else {
  18137. return this._private.userPanningEnabled;
  18138. }
  18139. return this; // chaining
  18140. },
  18141. zoomingEnabled: function zoomingEnabled(bool) {
  18142. if (bool !== undefined) {
  18143. this._private.zoomingEnabled = bool ? true : false;
  18144. } else {
  18145. return this._private.zoomingEnabled;
  18146. }
  18147. return this; // chaining
  18148. },
  18149. userZoomingEnabled: function userZoomingEnabled(bool) {
  18150. if (bool !== undefined) {
  18151. this._private.userZoomingEnabled = bool ? true : false;
  18152. } else {
  18153. return this._private.userZoomingEnabled;
  18154. }
  18155. return this; // chaining
  18156. },
  18157. boxSelectionEnabled: function boxSelectionEnabled(bool) {
  18158. if (bool !== undefined) {
  18159. this._private.boxSelectionEnabled = bool ? true : false;
  18160. } else {
  18161. return this._private.boxSelectionEnabled;
  18162. }
  18163. return this; // chaining
  18164. },
  18165. pan: function pan() {
  18166. var args = arguments;
  18167. var pan = this._private.pan;
  18168. var dim, val, dims, x, y;
  18169. switch (args.length) {
  18170. case 0:
  18171. // .pan()
  18172. return pan;
  18173. case 1:
  18174. if (string(args[0])) {
  18175. // .pan('x')
  18176. dim = args[0];
  18177. return pan[dim];
  18178. } else if (plainObject(args[0])) {
  18179. // .pan({ x: 0, y: 100 })
  18180. if (!this._private.panningEnabled) {
  18181. return this;
  18182. }
  18183. dims = args[0];
  18184. x = dims.x;
  18185. y = dims.y;
  18186. if (number$1(x)) {
  18187. pan.x = x;
  18188. }
  18189. if (number$1(y)) {
  18190. pan.y = y;
  18191. }
  18192. this.emit('pan viewport');
  18193. }
  18194. break;
  18195. case 2:
  18196. // .pan('x', 100)
  18197. if (!this._private.panningEnabled) {
  18198. return this;
  18199. }
  18200. dim = args[0];
  18201. val = args[1];
  18202. if ((dim === 'x' || dim === 'y') && number$1(val)) {
  18203. pan[dim] = val;
  18204. }
  18205. this.emit('pan viewport');
  18206. break;
  18207. // invalid
  18208. }
  18209. this.notify('viewport');
  18210. return this; // chaining
  18211. },
  18212. panBy: function panBy(arg0, arg1) {
  18213. var args = arguments;
  18214. var pan = this._private.pan;
  18215. var dim, val, dims, x, y;
  18216. if (!this._private.panningEnabled) {
  18217. return this;
  18218. }
  18219. switch (args.length) {
  18220. case 1:
  18221. if (plainObject(arg0)) {
  18222. // .panBy({ x: 0, y: 100 })
  18223. dims = args[0];
  18224. x = dims.x;
  18225. y = dims.y;
  18226. if (number$1(x)) {
  18227. pan.x += x;
  18228. }
  18229. if (number$1(y)) {
  18230. pan.y += y;
  18231. }
  18232. this.emit('pan viewport');
  18233. }
  18234. break;
  18235. case 2:
  18236. // .panBy('x', 100)
  18237. dim = arg0;
  18238. val = arg1;
  18239. if ((dim === 'x' || dim === 'y') && number$1(val)) {
  18240. pan[dim] += val;
  18241. }
  18242. this.emit('pan viewport');
  18243. break;
  18244. // invalid
  18245. }
  18246. this.notify('viewport');
  18247. return this; // chaining
  18248. },
  18249. gc: function gc() {
  18250. this.notify('gc');
  18251. },
  18252. fit: function fit(elements, padding) {
  18253. var viewportState = this.getFitViewport(elements, padding);
  18254. if (viewportState) {
  18255. var _p = this._private;
  18256. _p.zoom = viewportState.zoom;
  18257. _p.pan = viewportState.pan;
  18258. this.emit('pan zoom viewport');
  18259. this.notify('viewport');
  18260. }
  18261. return this; // chaining
  18262. },
  18263. getFitViewport: function getFitViewport(elements, padding) {
  18264. if (number$1(elements) && padding === undefined) {
  18265. // elements is optional
  18266. padding = elements;
  18267. elements = undefined;
  18268. }
  18269. if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
  18270. return;
  18271. }
  18272. var bb;
  18273. if (string(elements)) {
  18274. var sel = elements;
  18275. elements = this.$(sel);
  18276. } else if (boundingBox(elements)) {
  18277. // assume bb
  18278. var bbe = elements;
  18279. bb = {
  18280. x1: bbe.x1,
  18281. y1: bbe.y1,
  18282. x2: bbe.x2,
  18283. y2: bbe.y2
  18284. };
  18285. bb.w = bb.x2 - bb.x1;
  18286. bb.h = bb.y2 - bb.y1;
  18287. } else if (!elementOrCollection(elements)) {
  18288. elements = this.mutableElements();
  18289. }
  18290. if (elementOrCollection(elements) && elements.empty()) {
  18291. return;
  18292. } // can't fit to nothing
  18293. bb = bb || elements.boundingBox();
  18294. var w = this.width();
  18295. var h = this.height();
  18296. var zoom;
  18297. padding = number$1(padding) ? padding : 0;
  18298. if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0 && !isNaN(bb.w) && !isNaN(bb.h) && bb.w > 0 && bb.h > 0) {
  18299. zoom = Math.min((w - 2 * padding) / bb.w, (h - 2 * padding) / bb.h);
  18300. // crop zoom
  18301. zoom = zoom > this._private.maxZoom ? this._private.maxZoom : zoom;
  18302. zoom = zoom < this._private.minZoom ? this._private.minZoom : zoom;
  18303. var pan = {
  18304. // now pan to middle
  18305. x: (w - zoom * (bb.x1 + bb.x2)) / 2,
  18306. y: (h - zoom * (bb.y1 + bb.y2)) / 2
  18307. };
  18308. return {
  18309. zoom: zoom,
  18310. pan: pan
  18311. };
  18312. }
  18313. return;
  18314. },
  18315. zoomRange: function zoomRange(min, max) {
  18316. var _p = this._private;
  18317. if (max == null) {
  18318. var opts = min;
  18319. min = opts.min;
  18320. max = opts.max;
  18321. }
  18322. if (number$1(min) && number$1(max) && min <= max) {
  18323. _p.minZoom = min;
  18324. _p.maxZoom = max;
  18325. } else if (number$1(min) && max === undefined && min <= _p.maxZoom) {
  18326. _p.minZoom = min;
  18327. } else if (number$1(max) && min === undefined && max >= _p.minZoom) {
  18328. _p.maxZoom = max;
  18329. }
  18330. return this;
  18331. },
  18332. minZoom: function minZoom(zoom) {
  18333. if (zoom === undefined) {
  18334. return this._private.minZoom;
  18335. } else {
  18336. return this.zoomRange({
  18337. min: zoom
  18338. });
  18339. }
  18340. },
  18341. maxZoom: function maxZoom(zoom) {
  18342. if (zoom === undefined) {
  18343. return this._private.maxZoom;
  18344. } else {
  18345. return this.zoomRange({
  18346. max: zoom
  18347. });
  18348. }
  18349. },
  18350. getZoomedViewport: function getZoomedViewport(params) {
  18351. var _p = this._private;
  18352. var currentPan = _p.pan;
  18353. var currentZoom = _p.zoom;
  18354. var pos; // in rendered px
  18355. var zoom;
  18356. var bail = false;
  18357. if (!_p.zoomingEnabled) {
  18358. // zooming disabled
  18359. bail = true;
  18360. }
  18361. if (number$1(params)) {
  18362. // then set the zoom
  18363. zoom = params;
  18364. } else if (plainObject(params)) {
  18365. // then zoom about a point
  18366. zoom = params.level;
  18367. if (params.position != null) {
  18368. pos = modelToRenderedPosition$1(params.position, currentZoom, currentPan);
  18369. } else if (params.renderedPosition != null) {
  18370. pos = params.renderedPosition;
  18371. }
  18372. if (pos != null && !_p.panningEnabled) {
  18373. // panning disabled
  18374. bail = true;
  18375. }
  18376. }
  18377. // crop zoom
  18378. zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;
  18379. zoom = zoom < _p.minZoom ? _p.minZoom : zoom;
  18380. // can't zoom with invalid params
  18381. if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {
  18382. return null;
  18383. }
  18384. if (pos != null) {
  18385. // set zoom about position
  18386. var pan1 = currentPan;
  18387. var zoom1 = currentZoom;
  18388. var zoom2 = zoom;
  18389. var pan2 = {
  18390. x: -zoom2 / zoom1 * (pos.x - pan1.x) + pos.x,
  18391. y: -zoom2 / zoom1 * (pos.y - pan1.y) + pos.y
  18392. };
  18393. return {
  18394. zoomed: true,
  18395. panned: true,
  18396. zoom: zoom2,
  18397. pan: pan2
  18398. };
  18399. } else {
  18400. // just set the zoom
  18401. return {
  18402. zoomed: true,
  18403. panned: false,
  18404. zoom: zoom,
  18405. pan: currentPan
  18406. };
  18407. }
  18408. },
  18409. zoom: function zoom(params) {
  18410. if (params === undefined) {
  18411. // get
  18412. return this._private.zoom;
  18413. } else {
  18414. // set
  18415. var vp = this.getZoomedViewport(params);
  18416. var _p = this._private;
  18417. if (vp == null || !vp.zoomed) {
  18418. return this;
  18419. }
  18420. _p.zoom = vp.zoom;
  18421. if (vp.panned) {
  18422. _p.pan.x = vp.pan.x;
  18423. _p.pan.y = vp.pan.y;
  18424. }
  18425. this.emit('zoom' + (vp.panned ? ' pan' : '') + ' viewport');
  18426. this.notify('viewport');
  18427. return this; // chaining
  18428. }
  18429. },
  18430. viewport: function viewport(opts) {
  18431. var _p = this._private;
  18432. var zoomDefd = true;
  18433. var panDefd = true;
  18434. var events = []; // to trigger
  18435. var zoomFailed = false;
  18436. var panFailed = false;
  18437. if (!opts) {
  18438. return this;
  18439. }
  18440. if (!number$1(opts.zoom)) {
  18441. zoomDefd = false;
  18442. }
  18443. if (!plainObject(opts.pan)) {
  18444. panDefd = false;
  18445. }
  18446. if (!zoomDefd && !panDefd) {
  18447. return this;
  18448. }
  18449. if (zoomDefd) {
  18450. var z = opts.zoom;
  18451. if (z < _p.minZoom || z > _p.maxZoom || !_p.zoomingEnabled) {
  18452. zoomFailed = true;
  18453. } else {
  18454. _p.zoom = z;
  18455. events.push('zoom');
  18456. }
  18457. }
  18458. if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {
  18459. var p = opts.pan;
  18460. if (number$1(p.x)) {
  18461. _p.pan.x = p.x;
  18462. panFailed = false;
  18463. }
  18464. if (number$1(p.y)) {
  18465. _p.pan.y = p.y;
  18466. panFailed = false;
  18467. }
  18468. if (!panFailed) {
  18469. events.push('pan');
  18470. }
  18471. }
  18472. if (events.length > 0) {
  18473. events.push('viewport');
  18474. this.emit(events.join(' '));
  18475. this.notify('viewport');
  18476. }
  18477. return this; // chaining
  18478. },
  18479. center: function center(elements) {
  18480. var pan = this.getCenterPan(elements);
  18481. if (pan) {
  18482. this._private.pan = pan;
  18483. this.emit('pan viewport');
  18484. this.notify('viewport');
  18485. }
  18486. return this; // chaining
  18487. },
  18488. getCenterPan: function getCenterPan(elements, zoom) {
  18489. if (!this._private.panningEnabled) {
  18490. return;
  18491. }
  18492. if (string(elements)) {
  18493. var selector = elements;
  18494. elements = this.mutableElements().filter(selector);
  18495. } else if (!elementOrCollection(elements)) {
  18496. elements = this.mutableElements();
  18497. }
  18498. if (elements.length === 0) {
  18499. return;
  18500. } // can't centre pan to nothing
  18501. var bb = elements.boundingBox();
  18502. var w = this.width();
  18503. var h = this.height();
  18504. zoom = zoom === undefined ? this._private.zoom : zoom;
  18505. var pan = {
  18506. // middle
  18507. x: (w - zoom * (bb.x1 + bb.x2)) / 2,
  18508. y: (h - zoom * (bb.y1 + bb.y2)) / 2
  18509. };
  18510. return pan;
  18511. },
  18512. reset: function reset() {
  18513. if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
  18514. return this;
  18515. }
  18516. this.viewport({
  18517. pan: {
  18518. x: 0,
  18519. y: 0
  18520. },
  18521. zoom: 1
  18522. });
  18523. return this; // chaining
  18524. },
  18525. invalidateSize: function invalidateSize() {
  18526. this._private.sizeCache = null;
  18527. },
  18528. size: function size() {
  18529. var _p = this._private;
  18530. var container = _p.container;
  18531. var cy = this;
  18532. return _p.sizeCache = _p.sizeCache || (container ? function () {
  18533. var style = cy.window().getComputedStyle(container);
  18534. var val = function val(name) {
  18535. return parseFloat(style.getPropertyValue(name));
  18536. };
  18537. return {
  18538. width: container.clientWidth - val('padding-left') - val('padding-right'),
  18539. height: container.clientHeight - val('padding-top') - val('padding-bottom')
  18540. };
  18541. }() : {
  18542. // fallback if no container (not 0 b/c can be used for dividing etc)
  18543. width: 1,
  18544. height: 1
  18545. });
  18546. },
  18547. width: function width() {
  18548. return this.size().width;
  18549. },
  18550. height: function height() {
  18551. return this.size().height;
  18552. },
  18553. extent: function extent() {
  18554. var pan = this._private.pan;
  18555. var zoom = this._private.zoom;
  18556. var rb = this.renderedExtent();
  18557. var b = {
  18558. x1: (rb.x1 - pan.x) / zoom,
  18559. x2: (rb.x2 - pan.x) / zoom,
  18560. y1: (rb.y1 - pan.y) / zoom,
  18561. y2: (rb.y2 - pan.y) / zoom
  18562. };
  18563. b.w = b.x2 - b.x1;
  18564. b.h = b.y2 - b.y1;
  18565. return b;
  18566. },
  18567. renderedExtent: function renderedExtent() {
  18568. var width = this.width();
  18569. var height = this.height();
  18570. return {
  18571. x1: 0,
  18572. y1: 0,
  18573. x2: width,
  18574. y2: height,
  18575. w: width,
  18576. h: height
  18577. };
  18578. },
  18579. multiClickDebounceTime: function multiClickDebounceTime(_int) {
  18580. if (_int) this._private.multiClickDebounceTime = _int;else return this._private.multiClickDebounceTime;
  18581. return this; // chaining
  18582. }
  18583. };
  18584. // aliases
  18585. corefn$1.centre = corefn$1.center;
  18586. // backwards compatibility
  18587. corefn$1.autolockNodes = corefn$1.autolock;
  18588. corefn$1.autoungrabifyNodes = corefn$1.autoungrabify;
  18589. var fn = {
  18590. data: define.data({
  18591. field: 'data',
  18592. bindingEvent: 'data',
  18593. allowBinding: true,
  18594. allowSetting: true,
  18595. settingEvent: 'data',
  18596. settingTriggersEvent: true,
  18597. triggerFnName: 'trigger',
  18598. allowGetting: true,
  18599. updateStyle: true
  18600. }),
  18601. removeData: define.removeData({
  18602. field: 'data',
  18603. event: 'data',
  18604. triggerFnName: 'trigger',
  18605. triggerEvent: true,
  18606. updateStyle: true
  18607. }),
  18608. scratch: define.data({
  18609. field: 'scratch',
  18610. bindingEvent: 'scratch',
  18611. allowBinding: true,
  18612. allowSetting: true,
  18613. settingEvent: 'scratch',
  18614. settingTriggersEvent: true,
  18615. triggerFnName: 'trigger',
  18616. allowGetting: true,
  18617. updateStyle: true
  18618. }),
  18619. removeScratch: define.removeData({
  18620. field: 'scratch',
  18621. event: 'scratch',
  18622. triggerFnName: 'trigger',
  18623. triggerEvent: true,
  18624. updateStyle: true
  18625. })
  18626. };
  18627. // aliases
  18628. fn.attr = fn.data;
  18629. fn.removeAttr = fn.removeData;
  18630. var Core = function Core(opts) {
  18631. var cy = this;
  18632. opts = extend({}, opts);
  18633. var container = opts.container;
  18634. // allow for passing a wrapped jquery object
  18635. // e.g. cytoscape({ container: $('#cy') })
  18636. if (container && !htmlElement(container) && htmlElement(container[0])) {
  18637. container = container[0];
  18638. }
  18639. var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery
  18640. reg = reg || {};
  18641. if (reg && reg.cy) {
  18642. reg.cy.destroy();
  18643. reg = {}; // old instance => replace reg completely
  18644. }
  18645. var readies = reg.readies = reg.readies || [];
  18646. if (container) {
  18647. container._cyreg = reg;
  18648. } // make sure container assoc'd reg points to this cy
  18649. reg.cy = cy;
  18650. var head = _window !== undefined && container !== undefined && !opts.headless;
  18651. var options = opts;
  18652. options.layout = extend({
  18653. name: head ? 'grid' : 'null'
  18654. }, options.layout);
  18655. options.renderer = extend({
  18656. name: head ? 'canvas' : 'null'
  18657. }, options.renderer);
  18658. var defVal = function defVal(def, val, altVal) {
  18659. if (val !== undefined) {
  18660. return val;
  18661. } else if (altVal !== undefined) {
  18662. return altVal;
  18663. } else {
  18664. return def;
  18665. }
  18666. };
  18667. var _p = this._private = {
  18668. container: container,
  18669. // html dom ele container
  18670. ready: false,
  18671. // whether ready has been triggered
  18672. options: options,
  18673. // cached options
  18674. elements: new Collection(this),
  18675. // elements in the graph
  18676. listeners: [],
  18677. // list of listeners
  18678. aniEles: new Collection(this),
  18679. // elements being animated
  18680. data: options.data || {},
  18681. // data for the core
  18682. scratch: {},
  18683. // scratch object for core
  18684. layout: null,
  18685. renderer: null,
  18686. destroyed: false,
  18687. // whether destroy was called
  18688. notificationsEnabled: true,
  18689. // whether notifications are sent to the renderer
  18690. minZoom: 1e-50,
  18691. maxZoom: 1e50,
  18692. zoomingEnabled: defVal(true, options.zoomingEnabled),
  18693. userZoomingEnabled: defVal(true, options.userZoomingEnabled),
  18694. panningEnabled: defVal(true, options.panningEnabled),
  18695. userPanningEnabled: defVal(true, options.userPanningEnabled),
  18696. boxSelectionEnabled: defVal(true, options.boxSelectionEnabled),
  18697. autolock: defVal(false, options.autolock, options.autolockNodes),
  18698. autoungrabify: defVal(false, options.autoungrabify, options.autoungrabifyNodes),
  18699. autounselectify: defVal(false, options.autounselectify),
  18700. styleEnabled: options.styleEnabled === undefined ? head : options.styleEnabled,
  18701. zoom: number$1(options.zoom) ? options.zoom : 1,
  18702. pan: {
  18703. x: plainObject(options.pan) && number$1(options.pan.x) ? options.pan.x : 0,
  18704. y: plainObject(options.pan) && number$1(options.pan.y) ? options.pan.y : 0
  18705. },
  18706. animation: {
  18707. // object for currently-running animations
  18708. current: [],
  18709. queue: []
  18710. },
  18711. hasCompoundNodes: false,
  18712. multiClickDebounceTime: defVal(250, options.multiClickDebounceTime)
  18713. };
  18714. this.createEmitter();
  18715. // set selection type
  18716. this.selectionType(options.selectionType);
  18717. // init zoom bounds
  18718. this.zoomRange({
  18719. min: options.minZoom,
  18720. max: options.maxZoom
  18721. });
  18722. var loadExtData = function loadExtData(extData, next) {
  18723. var anyIsPromise = extData.some(promise);
  18724. if (anyIsPromise) {
  18725. return Promise$1.all(extData).then(next); // load all data asynchronously, then exec rest of init
  18726. } else {
  18727. next(extData); // exec synchronously for convenience
  18728. }
  18729. };
  18730. // start with the default stylesheet so we have something before loading an external stylesheet
  18731. if (_p.styleEnabled) {
  18732. cy.setStyle([]);
  18733. }
  18734. // create the renderer
  18735. var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options
  18736. cy.initRenderer(rendererOptions);
  18737. var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {
  18738. cy.notifications(false);
  18739. // remove old elements
  18740. var oldEles = cy.mutableElements();
  18741. if (oldEles.length > 0) {
  18742. oldEles.remove();
  18743. }
  18744. if (elements != null) {
  18745. if (plainObject(elements) || array(elements)) {
  18746. cy.add(elements);
  18747. }
  18748. }
  18749. cy.one('layoutready', function (e) {
  18750. cy.notifications(true);
  18751. cy.emit(e); // we missed this event by turning notifications off, so pass it on
  18752. cy.one('load', onload);
  18753. cy.emitAndNotify('load');
  18754. }).one('layoutstop', function () {
  18755. cy.one('done', ondone);
  18756. cy.emit('done');
  18757. });
  18758. var layoutOpts = extend({}, cy._private.options.layout);
  18759. layoutOpts.eles = cy.elements();
  18760. cy.layout(layoutOpts).run();
  18761. };
  18762. loadExtData([options.style, options.elements], function (thens) {
  18763. var initStyle = thens[0];
  18764. var initEles = thens[1];
  18765. // init style
  18766. if (_p.styleEnabled) {
  18767. cy.style().append(initStyle);
  18768. }
  18769. // initial load
  18770. setElesAndLayout(initEles, function () {
  18771. // onready
  18772. cy.startAnimationLoop();
  18773. _p.ready = true;
  18774. // if a ready callback is specified as an option, the bind it
  18775. if (fn$6(options.ready)) {
  18776. cy.on('ready', options.ready);
  18777. }
  18778. // bind all the ready handlers registered before creating this instance
  18779. for (var i = 0; i < readies.length; i++) {
  18780. var fn = readies[i];
  18781. cy.on('ready', fn);
  18782. }
  18783. if (reg) {
  18784. reg.readies = [];
  18785. } // 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
  18786. cy.emit('ready');
  18787. }, options.done);
  18788. });
  18789. };
  18790. var corefn = Core.prototype; // short alias
  18791. extend(corefn, {
  18792. instanceString: function instanceString() {
  18793. return 'core';
  18794. },
  18795. isReady: function isReady() {
  18796. return this._private.ready;
  18797. },
  18798. destroyed: function destroyed() {
  18799. return this._private.destroyed;
  18800. },
  18801. ready: function ready(fn) {
  18802. if (this.isReady()) {
  18803. this.emitter().emit('ready', [], fn); // just calls fn as though triggered via ready event
  18804. } else {
  18805. this.on('ready', fn);
  18806. }
  18807. return this;
  18808. },
  18809. destroy: function destroy() {
  18810. var cy = this;
  18811. if (cy.destroyed()) return;
  18812. cy.stopAnimationLoop();
  18813. cy.destroyRenderer();
  18814. this.emit('destroy');
  18815. cy._private.destroyed = true;
  18816. return cy;
  18817. },
  18818. hasElementWithId: function hasElementWithId(id) {
  18819. return this._private.elements.hasElementWithId(id);
  18820. },
  18821. getElementById: function getElementById(id) {
  18822. return this._private.elements.getElementById(id);
  18823. },
  18824. hasCompoundNodes: function hasCompoundNodes() {
  18825. return this._private.hasCompoundNodes;
  18826. },
  18827. headless: function headless() {
  18828. return this._private.renderer.isHeadless();
  18829. },
  18830. styleEnabled: function styleEnabled() {
  18831. return this._private.styleEnabled;
  18832. },
  18833. addToPool: function addToPool(eles) {
  18834. this._private.elements.merge(eles);
  18835. return this; // chaining
  18836. },
  18837. removeFromPool: function removeFromPool(eles) {
  18838. this._private.elements.unmerge(eles);
  18839. return this;
  18840. },
  18841. container: function container() {
  18842. return this._private.container || null;
  18843. },
  18844. window: function window() {
  18845. var container = this._private.container;
  18846. if (container == null) return _window;
  18847. var ownerDocument = this._private.container.ownerDocument;
  18848. if (ownerDocument === undefined || ownerDocument == null) {
  18849. return _window;
  18850. }
  18851. return ownerDocument.defaultView || _window;
  18852. },
  18853. mount: function mount(container) {
  18854. if (container == null) {
  18855. return;
  18856. }
  18857. var cy = this;
  18858. var _p = cy._private;
  18859. var options = _p.options;
  18860. if (!htmlElement(container) && htmlElement(container[0])) {
  18861. container = container[0];
  18862. }
  18863. cy.stopAnimationLoop();
  18864. cy.destroyRenderer();
  18865. _p.container = container;
  18866. _p.styleEnabled = true;
  18867. cy.invalidateSize();
  18868. cy.initRenderer(extend({}, options, options.renderer, {
  18869. // allow custom renderer name to be re-used, otherwise use canvas
  18870. name: options.renderer.name === 'null' ? 'canvas' : options.renderer.name
  18871. }));
  18872. cy.startAnimationLoop();
  18873. cy.style(options.style);
  18874. cy.emit('mount');
  18875. return cy;
  18876. },
  18877. unmount: function unmount() {
  18878. var cy = this;
  18879. cy.stopAnimationLoop();
  18880. cy.destroyRenderer();
  18881. cy.initRenderer({
  18882. name: 'null'
  18883. });
  18884. cy.emit('unmount');
  18885. return cy;
  18886. },
  18887. options: function options() {
  18888. return copy(this._private.options);
  18889. },
  18890. json: function json(obj) {
  18891. var cy = this;
  18892. var _p = cy._private;
  18893. var eles = cy.mutableElements();
  18894. var getFreshRef = function getFreshRef(ele) {
  18895. return cy.getElementById(ele.id());
  18896. };
  18897. if (plainObject(obj)) {
  18898. // set
  18899. cy.startBatch();
  18900. if (obj.elements) {
  18901. var idInJson = {};
  18902. var updateEles = function updateEles(jsons, gr) {
  18903. var toAdd = [];
  18904. var toMod = [];
  18905. for (var i = 0; i < jsons.length; i++) {
  18906. var json = jsons[i];
  18907. if (!json.data.id) {
  18908. warn('cy.json() cannot handle elements without an ID attribute');
  18909. continue;
  18910. }
  18911. var id = '' + json.data.id; // id must be string
  18912. var ele = cy.getElementById(id);
  18913. idInJson[id] = true;
  18914. if (ele.length !== 0) {
  18915. // existing element should be updated
  18916. toMod.push({
  18917. ele: ele,
  18918. json: json
  18919. });
  18920. } else {
  18921. // otherwise should be added
  18922. if (gr) {
  18923. json.group = gr;
  18924. toAdd.push(json);
  18925. } else {
  18926. toAdd.push(json);
  18927. }
  18928. }
  18929. }
  18930. cy.add(toAdd);
  18931. for (var _i = 0; _i < toMod.length; _i++) {
  18932. var _toMod$_i = toMod[_i],
  18933. _ele = _toMod$_i.ele,
  18934. _json = _toMod$_i.json;
  18935. _ele.json(_json);
  18936. }
  18937. };
  18938. if (array(obj.elements)) {
  18939. // elements: []
  18940. updateEles(obj.elements);
  18941. } else {
  18942. // elements: { nodes: [], edges: [] }
  18943. var grs = ['nodes', 'edges'];
  18944. for (var i = 0; i < grs.length; i++) {
  18945. var gr = grs[i];
  18946. var elements = obj.elements[gr];
  18947. if (array(elements)) {
  18948. updateEles(elements, gr);
  18949. }
  18950. }
  18951. }
  18952. var parentsToRemove = cy.collection();
  18953. eles.filter(function (ele) {
  18954. return !idInJson[ele.id()];
  18955. }).forEach(function (ele) {
  18956. if (ele.isParent()) {
  18957. parentsToRemove.merge(ele);
  18958. } else {
  18959. ele.remove();
  18960. }
  18961. });
  18962. // so that children are not removed w/parent
  18963. parentsToRemove.forEach(function (ele) {
  18964. return ele.children().move({
  18965. parent: null
  18966. });
  18967. });
  18968. // intermediate parents may be moved by prior line, so make sure we remove by fresh refs
  18969. parentsToRemove.forEach(function (ele) {
  18970. return getFreshRef(ele).remove();
  18971. });
  18972. }
  18973. if (obj.style) {
  18974. cy.style(obj.style);
  18975. }
  18976. if (obj.zoom != null && obj.zoom !== _p.zoom) {
  18977. cy.zoom(obj.zoom);
  18978. }
  18979. if (obj.pan) {
  18980. if (obj.pan.x !== _p.pan.x || obj.pan.y !== _p.pan.y) {
  18981. cy.pan(obj.pan);
  18982. }
  18983. }
  18984. if (obj.data) {
  18985. cy.data(obj.data);
  18986. }
  18987. var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];
  18988. for (var _i2 = 0; _i2 < fields.length; _i2++) {
  18989. var f = fields[_i2];
  18990. if (obj[f] != null) {
  18991. cy[f](obj[f]);
  18992. }
  18993. }
  18994. cy.endBatch();
  18995. return this; // chaining
  18996. } else {
  18997. // get
  18998. var flat = !!obj;
  18999. var json = {};
  19000. if (flat) {
  19001. json.elements = this.elements().map(function (ele) {
  19002. return ele.json();
  19003. });
  19004. } else {
  19005. json.elements = {};
  19006. eles.forEach(function (ele) {
  19007. var group = ele.group();
  19008. if (!json.elements[group]) {
  19009. json.elements[group] = [];
  19010. }
  19011. json.elements[group].push(ele.json());
  19012. });
  19013. }
  19014. if (this._private.styleEnabled) {
  19015. json.style = cy.style().json();
  19016. }
  19017. json.data = copy(cy.data());
  19018. var options = _p.options;
  19019. json.zoomingEnabled = _p.zoomingEnabled;
  19020. json.userZoomingEnabled = _p.userZoomingEnabled;
  19021. json.zoom = _p.zoom;
  19022. json.minZoom = _p.minZoom;
  19023. json.maxZoom = _p.maxZoom;
  19024. json.panningEnabled = _p.panningEnabled;
  19025. json.userPanningEnabled = _p.userPanningEnabled;
  19026. json.pan = copy(_p.pan);
  19027. json.boxSelectionEnabled = _p.boxSelectionEnabled;
  19028. json.renderer = copy(options.renderer);
  19029. json.hideEdgesOnViewport = options.hideEdgesOnViewport;
  19030. json.textureOnViewport = options.textureOnViewport;
  19031. json.wheelSensitivity = options.wheelSensitivity;
  19032. json.motionBlur = options.motionBlur;
  19033. json.multiClickDebounceTime = options.multiClickDebounceTime;
  19034. return json;
  19035. }
  19036. }
  19037. });
  19038. corefn.$id = corefn.getElementById;
  19039. [corefn$9, corefn$8, elesfn, corefn$7, corefn$6, corefn$5, corefn$4, corefn$3, corefn$2, corefn$1, fn].forEach(function (props) {
  19040. extend(corefn, props);
  19041. });
  19042. /* eslint-disable no-unused-vars */
  19043. var defaults$7 = {
  19044. fit: true,
  19045. // whether to fit the viewport to the graph
  19046. directed: false,
  19047. // whether the tree is directed downwards (or edges can point in any direction if false)
  19048. direction: 'downward',
  19049. // determines the direction in which the tree structure is drawn. The possible values are 'downward', 'upward', 'rightward', or 'leftward'.
  19050. padding: 30,
  19051. // padding on fit
  19052. circle: false,
  19053. // put depths in concentric circles if true, put depths top down if false
  19054. grid: false,
  19055. // whether to create an even grid into which the DAG is placed (circle:false only)
  19056. spacingFactor: 1.75,
  19057. // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)
  19058. boundingBox: undefined,
  19059. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19060. avoidOverlap: true,
  19061. // prevents node overlap, may overflow boundingBox if not enough space
  19062. nodeDimensionsIncludeLabels: false,
  19063. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19064. roots: undefined,
  19065. // the roots of the trees
  19066. depthSort: undefined,
  19067. // a sorting function to order nodes at equal depth. e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  19068. animate: false,
  19069. // whether to transition the node positions
  19070. animationDuration: 500,
  19071. // duration of animation in ms if enabled
  19072. animationEasing: undefined,
  19073. // easing of animation if enabled,
  19074. animateFilter: function animateFilter(node, i) {
  19075. return true;
  19076. },
  19077. // 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
  19078. ready: undefined,
  19079. // callback on layoutready
  19080. stop: undefined,
  19081. // callback on layoutstop
  19082. transform: function transform(node, position) {
  19083. return position;
  19084. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19085. };
  19086. var deprecatedOptionDefaults = {
  19087. maximal: false,
  19088. // 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
  19089. 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
  19090. };
  19091. /* eslint-enable */
  19092. var getInfo = function getInfo(ele) {
  19093. return ele.scratch('breadthfirst');
  19094. };
  19095. var setInfo = function setInfo(ele, obj) {
  19096. return ele.scratch('breadthfirst', obj);
  19097. };
  19098. function BreadthFirstLayout(options) {
  19099. this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);
  19100. }
  19101. BreadthFirstLayout.prototype.run = function () {
  19102. var options = this.options;
  19103. var cy = options.cy;
  19104. var eles = options.eles;
  19105. var nodes = eles.nodes().filter(function (n) {
  19106. return n.isChildless();
  19107. });
  19108. var graph = eles;
  19109. var directed = options.directed;
  19110. var maximal = options.acyclic || options.maximal || options.maximalAdjustments > 0; // maximalAdjustments for compat. w/ old code; also, setting acyclic to true sets maximal to true
  19111. var hasBoundingBox = !!options.boundingBox;
  19112. var bb = makeBoundingBox(hasBoundingBox ? options.boundingBox : structuredClone(cy.extent()));
  19113. var roots;
  19114. if (elementOrCollection(options.roots)) {
  19115. roots = options.roots;
  19116. } else if (array(options.roots)) {
  19117. var rootsArray = [];
  19118. for (var i = 0; i < options.roots.length; i++) {
  19119. var id = options.roots[i];
  19120. var ele = cy.getElementById(id);
  19121. rootsArray.push(ele);
  19122. }
  19123. roots = cy.collection(rootsArray);
  19124. } else if (string(options.roots)) {
  19125. roots = cy.$(options.roots);
  19126. } else {
  19127. if (directed) {
  19128. roots = nodes.roots();
  19129. } else {
  19130. var components = eles.components();
  19131. roots = cy.collection();
  19132. var _loop = function _loop() {
  19133. var comp = components[_i];
  19134. var maxDegree = comp.maxDegree(false);
  19135. var compRoots = comp.filter(function (ele) {
  19136. return ele.degree(false) === maxDegree;
  19137. });
  19138. roots = roots.add(compRoots);
  19139. };
  19140. for (var _i = 0; _i < components.length; _i++) {
  19141. _loop();
  19142. }
  19143. }
  19144. }
  19145. var depths = [];
  19146. var foundByBfs = {};
  19147. var addToDepth = function addToDepth(ele, d) {
  19148. if (depths[d] == null) {
  19149. depths[d] = [];
  19150. }
  19151. var i = depths[d].length;
  19152. depths[d].push(ele);
  19153. setInfo(ele, {
  19154. index: i,
  19155. depth: d
  19156. });
  19157. };
  19158. var changeDepth = function changeDepth(ele, newDepth) {
  19159. var _getInfo = getInfo(ele),
  19160. depth = _getInfo.depth,
  19161. index = _getInfo.index;
  19162. depths[depth][index] = null;
  19163. // add only childless nodes
  19164. if (ele.isChildless()) addToDepth(ele, newDepth);
  19165. };
  19166. // find the depths of the nodes
  19167. graph.bfs({
  19168. roots: roots,
  19169. directed: options.directed,
  19170. visit: function visit(node, edge, pNode, i, depth) {
  19171. var ele = node[0];
  19172. var id = ele.id();
  19173. // add only childless nodes
  19174. if (ele.isChildless()) addToDepth(ele, depth);
  19175. foundByBfs[id] = true;
  19176. }
  19177. });
  19178. // check for nodes not found by bfs
  19179. var orphanNodes = [];
  19180. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  19181. var _ele = nodes[_i2];
  19182. if (foundByBfs[_ele.id()]) {
  19183. continue;
  19184. } else {
  19185. orphanNodes.push(_ele);
  19186. }
  19187. }
  19188. // assign the nodes a depth and index
  19189. var assignDepthsAt = function assignDepthsAt(i) {
  19190. var eles = depths[i];
  19191. for (var j = 0; j < eles.length; j++) {
  19192. var _ele2 = eles[j];
  19193. if (_ele2 == null) {
  19194. eles.splice(j, 1);
  19195. j--;
  19196. continue;
  19197. }
  19198. setInfo(_ele2, {
  19199. depth: i,
  19200. index: j
  19201. });
  19202. }
  19203. };
  19204. var adjustMaximally = function adjustMaximally(ele, shifted) {
  19205. var eInfo = getInfo(ele);
  19206. var incomers = ele.incomers().filter(function (el) {
  19207. return el.isNode() && eles.has(el);
  19208. });
  19209. var maxDepth = -1;
  19210. var id = ele.id();
  19211. for (var k = 0; k < incomers.length; k++) {
  19212. var incmr = incomers[k];
  19213. var iInfo = getInfo(incmr);
  19214. maxDepth = Math.max(maxDepth, iInfo.depth);
  19215. }
  19216. if (eInfo.depth <= maxDepth) {
  19217. if (!options.acyclic && shifted[id]) {
  19218. return null;
  19219. }
  19220. var newDepth = maxDepth + 1;
  19221. changeDepth(ele, newDepth);
  19222. shifted[id] = newDepth;
  19223. return true;
  19224. }
  19225. return false;
  19226. };
  19227. // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)
  19228. if (directed && maximal) {
  19229. var Q = [];
  19230. var shifted = {};
  19231. var enqueue = function enqueue(n) {
  19232. return Q.push(n);
  19233. };
  19234. var dequeue = function dequeue() {
  19235. return Q.shift();
  19236. };
  19237. nodes.forEach(function (n) {
  19238. return Q.push(n);
  19239. });
  19240. while (Q.length > 0) {
  19241. var _ele3 = dequeue();
  19242. var didShift = adjustMaximally(_ele3, shifted);
  19243. if (didShift) {
  19244. _ele3.outgoers().filter(function (el) {
  19245. return el.isNode() && eles.has(el);
  19246. }).forEach(enqueue);
  19247. } else if (didShift === null) {
  19248. warn('Detected double maximal shift for node `' + _ele3.id() + '`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.');
  19249. break; // exit on failure
  19250. }
  19251. }
  19252. }
  19253. // find min distance we need to leave between nodes
  19254. var minDistance = 0;
  19255. if (options.avoidOverlap) {
  19256. for (var _i3 = 0; _i3 < nodes.length; _i3++) {
  19257. var n = nodes[_i3];
  19258. var nbb = n.layoutDimensions(options);
  19259. var w = nbb.w;
  19260. var h = nbb.h;
  19261. minDistance = Math.max(minDistance, w, h);
  19262. }
  19263. }
  19264. // get the weighted percent for an element based on its connectivity to other levels
  19265. var cachedWeightedPercent = {};
  19266. var getWeightedPercent = function getWeightedPercent(ele) {
  19267. if (cachedWeightedPercent[ele.id()]) {
  19268. return cachedWeightedPercent[ele.id()];
  19269. }
  19270. var eleDepth = getInfo(ele).depth;
  19271. var neighbors = ele.neighborhood();
  19272. var percent = 0;
  19273. var samples = 0;
  19274. for (var _i4 = 0; _i4 < neighbors.length; _i4++) {
  19275. var neighbor = neighbors[_i4];
  19276. if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {
  19277. continue;
  19278. }
  19279. var bf = getInfo(neighbor);
  19280. if (bf == null) {
  19281. continue;
  19282. }
  19283. var index = bf.index;
  19284. var depth = bf.depth;
  19285. // unassigned neighbours shouldn't affect the ordering
  19286. if (index == null || depth == null) {
  19287. continue;
  19288. }
  19289. var nDepth = depths[depth].length;
  19290. if (depth < eleDepth) {
  19291. // only get influenced by elements above
  19292. percent += index / nDepth;
  19293. samples++;
  19294. }
  19295. }
  19296. samples = Math.max(1, samples);
  19297. percent = percent / samples;
  19298. if (samples === 0) {
  19299. // put lone nodes at the start
  19300. percent = 0;
  19301. }
  19302. cachedWeightedPercent[ele.id()] = percent;
  19303. return percent;
  19304. };
  19305. // rearrange the indices in each depth level based on connectivity
  19306. var sortFn = function sortFn(a, b) {
  19307. var apct = getWeightedPercent(a);
  19308. var bpct = getWeightedPercent(b);
  19309. var diff = apct - bpct;
  19310. if (diff === 0) {
  19311. return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons
  19312. } else {
  19313. return diff;
  19314. }
  19315. };
  19316. if (options.depthSort !== undefined) {
  19317. sortFn = options.depthSort;
  19318. }
  19319. var depthsLen = depths.length;
  19320. // sort each level to make connected nodes closer
  19321. for (var _i5 = 0; _i5 < depthsLen; _i5++) {
  19322. depths[_i5].sort(sortFn);
  19323. assignDepthsAt(_i5);
  19324. }
  19325. // assign orphan nodes to a new top-level depth
  19326. var orphanDepth = [];
  19327. for (var _i6 = 0; _i6 < orphanNodes.length; _i6++) {
  19328. orphanDepth.push(orphanNodes[_i6]);
  19329. }
  19330. var assignDepths = function assignDepths() {
  19331. for (var _i7 = 0; _i7 < depthsLen; _i7++) {
  19332. assignDepthsAt(_i7);
  19333. }
  19334. };
  19335. // add a new top-level depth only when there are orphan nodes
  19336. if (orphanDepth.length) {
  19337. depths.unshift(orphanDepth);
  19338. depthsLen = depths.length;
  19339. assignDepths();
  19340. }
  19341. var biggestDepthSize = 0;
  19342. for (var _i8 = 0; _i8 < depthsLen; _i8++) {
  19343. biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);
  19344. }
  19345. var center = {
  19346. x: bb.x1 + bb.w / 2,
  19347. y: bb.y1 + bb.h / 2
  19348. };
  19349. // average node size
  19350. var aveNodeSize = nodes.reduce(function (acc, node) {
  19351. return function (box) {
  19352. return {
  19353. w: acc.w === -1 ? box.w : (acc.w + box.w) / 2,
  19354. h: acc.h === -1 ? box.h : (acc.h + box.h) / 2
  19355. };
  19356. }(node.boundingBox({
  19357. includeLabels: options.nodeDimensionsIncludeLabels
  19358. }));
  19359. }, {
  19360. w: -1,
  19361. h: -1
  19362. });
  19363. var distanceY = Math.max(
  19364. // only one depth
  19365. depthsLen === 1 ? 0 :
  19366. // inside a bounding box, no need for top & bottom padding
  19367. hasBoundingBox ? (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen - 1) : (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen + 1), minDistance);
  19368. var maxDepthSize = depths.reduce(function (max, eles) {
  19369. return Math.max(max, eles.length);
  19370. }, 0);
  19371. var getPositionTopBottom = function getPositionTopBottom(ele) {
  19372. var _getInfo2 = getInfo(ele),
  19373. depth = _getInfo2.depth,
  19374. index = _getInfo2.index;
  19375. if (options.circle) {
  19376. var radiusStepSize = Math.min(bb.w / 2 / depthsLen, bb.h / 2 / depthsLen);
  19377. radiusStepSize = Math.max(radiusStepSize, minDistance);
  19378. var radius = radiusStepSize * depth + radiusStepSize - (depthsLen > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);
  19379. var theta = 2 * Math.PI / depths[depth].length * index;
  19380. if (depth === 0 && depths[0].length === 1) {
  19381. radius = 1;
  19382. }
  19383. return {
  19384. x: center.x + radius * Math.cos(theta),
  19385. y: center.y + radius * Math.sin(theta)
  19386. };
  19387. } else {
  19388. var depthSize = depths[depth].length;
  19389. var distanceX = Math.max(
  19390. // only one depth
  19391. depthSize === 1 ? 0 :
  19392. // inside a bounding box, no need for left & right padding
  19393. 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);
  19394. var epos = {
  19395. x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,
  19396. y: center.y + (depth + 1 - (depthsLen + 1) / 2) * distanceY
  19397. };
  19398. return epos;
  19399. }
  19400. };
  19401. var rotateDegrees = {
  19402. 'downward': 0,
  19403. 'leftward': 90,
  19404. 'upward': 180,
  19405. 'rightward': -90
  19406. };
  19407. if (Object.keys(rotateDegrees).indexOf(options.direction) === -1) {
  19408. error("Invalid direction '".concat(options.direction, "' specified for breadthfirst layout. Valid values are: ").concat(Object.keys(rotateDegrees).join(', ')));
  19409. }
  19410. var getPosition = function getPosition(ele) {
  19411. return rotatePosAndSkewByBox(getPositionTopBottom(ele), bb, rotateDegrees[options.direction]);
  19412. };
  19413. eles.nodes().layoutPositions(this, options, getPosition);
  19414. return this; // chaining
  19415. };
  19416. var defaults$6 = {
  19417. fit: true,
  19418. // whether to fit the viewport to the graph
  19419. padding: 30,
  19420. // the padding on fit
  19421. boundingBox: undefined,
  19422. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19423. avoidOverlap: true,
  19424. // prevents node overlap, may overflow boundingBox and radius if not enough space
  19425. nodeDimensionsIncludeLabels: false,
  19426. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19427. spacingFactor: undefined,
  19428. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  19429. radius: undefined,
  19430. // the radius of the circle
  19431. startAngle: 3 / 2 * Math.PI,
  19432. // where nodes start in radians
  19433. sweep: undefined,
  19434. // how many radians should be between the first and last node (defaults to full circle)
  19435. clockwise: true,
  19436. // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  19437. sort: undefined,
  19438. // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  19439. animate: false,
  19440. // whether to transition the node positions
  19441. animationDuration: 500,
  19442. // duration of animation in ms if enabled
  19443. animationEasing: undefined,
  19444. // easing of animation if enabled
  19445. animateFilter: function animateFilter(node, i) {
  19446. return true;
  19447. },
  19448. // 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
  19449. ready: undefined,
  19450. // callback on layoutready
  19451. stop: undefined,
  19452. // callback on layoutstop
  19453. transform: function transform(node, position) {
  19454. return position;
  19455. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19456. };
  19457. function CircleLayout(options) {
  19458. this.options = extend({}, defaults$6, options);
  19459. }
  19460. CircleLayout.prototype.run = function () {
  19461. var params = this.options;
  19462. var options = params;
  19463. var cy = params.cy;
  19464. var eles = options.eles;
  19465. var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  19466. var nodes = eles.nodes().not(':parent');
  19467. if (options.sort) {
  19468. nodes = nodes.sort(options.sort);
  19469. }
  19470. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19471. x1: 0,
  19472. y1: 0,
  19473. w: cy.width(),
  19474. h: cy.height()
  19475. });
  19476. var center = {
  19477. x: bb.x1 + bb.w / 2,
  19478. y: bb.y1 + bb.h / 2
  19479. };
  19480. var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / nodes.length : options.sweep;
  19481. var dTheta = sweep / Math.max(1, nodes.length - 1);
  19482. var r;
  19483. var minDistance = 0;
  19484. for (var i = 0; i < nodes.length; i++) {
  19485. var n = nodes[i];
  19486. var nbb = n.layoutDimensions(options);
  19487. var w = nbb.w;
  19488. var h = nbb.h;
  19489. minDistance = Math.max(minDistance, w, h);
  19490. }
  19491. if (number$1(options.radius)) {
  19492. r = options.radius;
  19493. } else if (nodes.length <= 1) {
  19494. r = 0;
  19495. } else {
  19496. r = Math.min(bb.h, bb.w) / 2 - minDistance;
  19497. }
  19498. // calculate the radius
  19499. if (nodes.length > 1 && options.avoidOverlap) {
  19500. // but only if more than one node (can't overlap)
  19501. minDistance *= 1.75; // just to have some nice spacing
  19502. var dcos = Math.cos(dTheta) - Math.cos(0);
  19503. var dsin = Math.sin(dTheta) - Math.sin(0);
  19504. var rMin = Math.sqrt(minDistance * minDistance / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
  19505. r = Math.max(rMin, r);
  19506. }
  19507. var getPos = function getPos(ele, i) {
  19508. var theta = options.startAngle + i * dTheta * (clockwise ? 1 : -1);
  19509. var rx = r * Math.cos(theta);
  19510. var ry = r * Math.sin(theta);
  19511. var pos = {
  19512. x: center.x + rx,
  19513. y: center.y + ry
  19514. };
  19515. return pos;
  19516. };
  19517. eles.nodes().layoutPositions(this, options, getPos);
  19518. return this; // chaining
  19519. };
  19520. var defaults$5 = {
  19521. fit: true,
  19522. // whether to fit the viewport to the graph
  19523. padding: 30,
  19524. // the padding on fit
  19525. startAngle: 3 / 2 * Math.PI,
  19526. // where nodes start in radians
  19527. sweep: undefined,
  19528. // how many radians should be between the first and last node (defaults to full circle)
  19529. clockwise: true,
  19530. // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  19531. equidistant: false,
  19532. // whether levels have an equal radial distance betwen them, may cause bounding box overflow
  19533. minNodeSpacing: 10,
  19534. // min spacing between outside of nodes (used for radius adjustment)
  19535. boundingBox: undefined,
  19536. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19537. avoidOverlap: true,
  19538. // prevents node overlap, may overflow boundingBox if not enough space
  19539. nodeDimensionsIncludeLabels: false,
  19540. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19541. height: undefined,
  19542. // height of layout area (overrides container height)
  19543. width: undefined,
  19544. // width of layout area (overrides container width)
  19545. spacingFactor: undefined,
  19546. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  19547. concentric: function concentric(node) {
  19548. // returns numeric value for each node, placing higher nodes in levels towards the centre
  19549. return node.degree();
  19550. },
  19551. levelWidth: function levelWidth(nodes) {
  19552. // the variation of concentric values in each level
  19553. return nodes.maxDegree() / 4;
  19554. },
  19555. animate: false,
  19556. // whether to transition the node positions
  19557. animationDuration: 500,
  19558. // duration of animation in ms if enabled
  19559. animationEasing: undefined,
  19560. // easing of animation if enabled
  19561. animateFilter: function animateFilter(node, i) {
  19562. return true;
  19563. },
  19564. // 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
  19565. ready: undefined,
  19566. // callback on layoutready
  19567. stop: undefined,
  19568. // callback on layoutstop
  19569. transform: function transform(node, position) {
  19570. return position;
  19571. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19572. };
  19573. function ConcentricLayout(options) {
  19574. this.options = extend({}, defaults$5, options);
  19575. }
  19576. ConcentricLayout.prototype.run = function () {
  19577. var params = this.options;
  19578. var options = params;
  19579. var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  19580. var cy = params.cy;
  19581. var eles = options.eles;
  19582. var nodes = eles.nodes().not(':parent');
  19583. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19584. x1: 0,
  19585. y1: 0,
  19586. w: cy.width(),
  19587. h: cy.height()
  19588. });
  19589. var center = {
  19590. x: bb.x1 + bb.w / 2,
  19591. y: bb.y1 + bb.h / 2
  19592. };
  19593. var nodeValues = []; // { node, value }
  19594. var maxNodeSize = 0;
  19595. for (var i = 0; i < nodes.length; i++) {
  19596. var node = nodes[i];
  19597. var value = undefined;
  19598. // calculate the node value
  19599. value = options.concentric(node);
  19600. nodeValues.push({
  19601. value: value,
  19602. node: node
  19603. });
  19604. // for style mapping
  19605. node._private.scratch.concentric = value;
  19606. }
  19607. // in case we used the `concentric` in style
  19608. nodes.updateStyle();
  19609. // calculate max size now based on potentially updated mappers
  19610. for (var _i = 0; _i < nodes.length; _i++) {
  19611. var _node = nodes[_i];
  19612. var nbb = _node.layoutDimensions(options);
  19613. maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);
  19614. }
  19615. // sort node values in descreasing order
  19616. nodeValues.sort(function (a, b) {
  19617. return b.value - a.value;
  19618. });
  19619. var levelWidth = options.levelWidth(nodes);
  19620. // put the values into levels
  19621. var levels = [[]];
  19622. var currentLevel = levels[0];
  19623. for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {
  19624. var val = nodeValues[_i2];
  19625. if (currentLevel.length > 0) {
  19626. var diff = Math.abs(currentLevel[0].value - val.value);
  19627. if (diff >= levelWidth) {
  19628. currentLevel = [];
  19629. levels.push(currentLevel);
  19630. }
  19631. }
  19632. currentLevel.push(val);
  19633. }
  19634. // create positions from levels
  19635. var minDist = maxNodeSize + options.minNodeSpacing; // min dist between nodes
  19636. if (!options.avoidOverlap) {
  19637. // then strictly constrain to bb
  19638. var firstLvlHasMulti = levels.length > 0 && levels[0].length > 1;
  19639. var maxR = Math.min(bb.w, bb.h) / 2 - minDist;
  19640. var rStep = maxR / (levels.length + firstLvlHasMulti ? 1 : 0);
  19641. minDist = Math.min(minDist, rStep);
  19642. }
  19643. // find the metrics for each level
  19644. var r = 0;
  19645. for (var _i3 = 0; _i3 < levels.length; _i3++) {
  19646. var level = levels[_i3];
  19647. var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / level.length : options.sweep;
  19648. var dTheta = level.dTheta = sweep / Math.max(1, level.length - 1);
  19649. // calculate the radius
  19650. if (level.length > 1 && options.avoidOverlap) {
  19651. // but only if more than one node (can't overlap)
  19652. var dcos = Math.cos(dTheta) - Math.cos(0);
  19653. var dsin = Math.sin(dTheta) - Math.sin(0);
  19654. var rMin = Math.sqrt(minDist * minDist / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
  19655. r = Math.max(rMin, r);
  19656. }
  19657. level.r = r;
  19658. r += minDist;
  19659. }
  19660. if (options.equidistant) {
  19661. var rDeltaMax = 0;
  19662. var _r = 0;
  19663. for (var _i4 = 0; _i4 < levels.length; _i4++) {
  19664. var _level = levels[_i4];
  19665. var rDelta = _level.r - _r;
  19666. rDeltaMax = Math.max(rDeltaMax, rDelta);
  19667. }
  19668. _r = 0;
  19669. for (var _i5 = 0; _i5 < levels.length; _i5++) {
  19670. var _level2 = levels[_i5];
  19671. if (_i5 === 0) {
  19672. _r = _level2.r;
  19673. }
  19674. _level2.r = _r;
  19675. _r += rDeltaMax;
  19676. }
  19677. }
  19678. // calculate the node positions
  19679. var pos = {}; // id => position
  19680. for (var _i6 = 0; _i6 < levels.length; _i6++) {
  19681. var _level3 = levels[_i6];
  19682. var _dTheta = _level3.dTheta;
  19683. var _r2 = _level3.r;
  19684. for (var j = 0; j < _level3.length; j++) {
  19685. var _val = _level3[j];
  19686. var theta = options.startAngle + (clockwise ? 1 : -1) * _dTheta * j;
  19687. var p = {
  19688. x: center.x + _r2 * Math.cos(theta),
  19689. y: center.y + _r2 * Math.sin(theta)
  19690. };
  19691. pos[_val.node.id()] = p;
  19692. }
  19693. }
  19694. // position the nodes
  19695. eles.nodes().layoutPositions(this, options, function (ele) {
  19696. var id = ele.id();
  19697. return pos[id];
  19698. });
  19699. return this; // chaining
  19700. };
  19701. /*
  19702. The CoSE layout was written by Gerardo Huck.
  19703. https://www.linkedin.com/in/gerardohuck/
  19704. Based on the following article:
  19705. http://dl.acm.org/citation.cfm?id=1498047
  19706. Modifications tracked on Github.
  19707. */
  19708. var DEBUG;
  19709. /**
  19710. * @brief : default layout options
  19711. */
  19712. var defaults$4 = {
  19713. // Called on `layoutready`
  19714. ready: function ready() {},
  19715. // Called on `layoutstop`
  19716. stop: function stop() {},
  19717. // Whether to animate while running the layout
  19718. // true : Animate continuously as the layout is running
  19719. // false : Just show the end result
  19720. // 'end' : Animate with the end result, from the initial positions to the end positions
  19721. animate: true,
  19722. // Easing of the animation for animate:'end'
  19723. animationEasing: undefined,
  19724. // The duration of the animation for animate:'end'
  19725. animationDuration: undefined,
  19726. // A function that determines whether the node should be animated
  19727. // All nodes animated by default on animate enabled
  19728. // Non-animated nodes are positioned immediately when the layout starts
  19729. animateFilter: function animateFilter(node, i) {
  19730. return true;
  19731. },
  19732. // The layout animates only after this many milliseconds for animate:true
  19733. // (prevents flashing on fast runs)
  19734. animationThreshold: 250,
  19735. // Number of iterations between consecutive screen positions update
  19736. refresh: 20,
  19737. // Whether to fit the network view after when done
  19738. fit: true,
  19739. // Padding on fit
  19740. padding: 30,
  19741. // Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19742. boundingBox: undefined,
  19743. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19744. nodeDimensionsIncludeLabels: false,
  19745. // Randomize the initial positions of the nodes (true) or use existing positions (false)
  19746. randomize: false,
  19747. // Extra spacing between components in non-compound graphs
  19748. componentSpacing: 40,
  19749. // Node repulsion (non overlapping) multiplier
  19750. nodeRepulsion: function nodeRepulsion(node) {
  19751. return 2048;
  19752. },
  19753. // Node repulsion (overlapping) multiplier
  19754. nodeOverlap: 4,
  19755. // Ideal edge (non nested) length
  19756. idealEdgeLength: function idealEdgeLength(edge) {
  19757. return 32;
  19758. },
  19759. // Divisor to compute edge forces
  19760. edgeElasticity: function edgeElasticity(edge) {
  19761. return 32;
  19762. },
  19763. // Nesting factor (multiplier) to compute ideal edge length for nested edges
  19764. nestingFactor: 1.2,
  19765. // Gravity force (constant)
  19766. gravity: 1,
  19767. // Maximum number of iterations to perform
  19768. numIter: 1000,
  19769. // Initial temperature (maximum node displacement)
  19770. initialTemp: 1000,
  19771. // Cooling factor (how the temperature is reduced between consecutive iterations
  19772. coolingFactor: 0.99,
  19773. // Lower temperature threshold (below this point the layout will end)
  19774. minTemp: 1.0
  19775. };
  19776. /**
  19777. * @brief : constructor
  19778. * @arg options : object containing layout options
  19779. */
  19780. function CoseLayout(options) {
  19781. this.options = extend({}, defaults$4, options);
  19782. this.options.layout = this;
  19783. // Exclude any edge that has a source or target node that is not in the set of passed-in nodes
  19784. var nodes = this.options.eles.nodes();
  19785. var edges = this.options.eles.edges();
  19786. var notEdges = edges.filter(function (e) {
  19787. var sourceId = e.source().data('id');
  19788. var targetId = e.target().data('id');
  19789. var hasSource = nodes.some(function (n) {
  19790. return n.data('id') === sourceId;
  19791. });
  19792. var hasTarget = nodes.some(function (n) {
  19793. return n.data('id') === targetId;
  19794. });
  19795. return !hasSource || !hasTarget;
  19796. });
  19797. this.options.eles = this.options.eles.not(notEdges);
  19798. }
  19799. /**
  19800. * @brief : runs the layout
  19801. */
  19802. CoseLayout.prototype.run = function () {
  19803. var options = this.options;
  19804. var cy = options.cy;
  19805. var layout = this;
  19806. layout.stopped = false;
  19807. if (options.animate === true || options.animate === false) {
  19808. layout.emit({
  19809. type: 'layoutstart',
  19810. layout: layout
  19811. });
  19812. }
  19813. // Set DEBUG - Global variable
  19814. if (true === options.debug) {
  19815. DEBUG = true;
  19816. } else {
  19817. DEBUG = false;
  19818. }
  19819. // Initialize layout info
  19820. var layoutInfo = createLayoutInfo(cy, layout, options);
  19821. // Show LayoutInfo contents if debugging
  19822. if (DEBUG) {
  19823. printLayoutInfo(layoutInfo);
  19824. }
  19825. // If required, randomize node positions
  19826. if (options.randomize) {
  19827. randomizePositions(layoutInfo);
  19828. }
  19829. var startTime = performanceNow();
  19830. var refresh = function refresh() {
  19831. refreshPositions(layoutInfo, cy, options);
  19832. // Fit the graph if necessary
  19833. if (true === options.fit) {
  19834. cy.fit(options.padding);
  19835. }
  19836. };
  19837. var mainLoop = function mainLoop(i) {
  19838. if (layout.stopped || i >= options.numIter) {
  19839. // logDebug("Layout manually stopped. Stopping computation in step " + i);
  19840. return false;
  19841. }
  19842. // Do one step in the phisical simulation
  19843. step(layoutInfo, options);
  19844. // Update temperature
  19845. layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;
  19846. // logDebug("New temperature: " + layoutInfo.temperature);
  19847. if (layoutInfo.temperature < options.minTemp) {
  19848. // logDebug("Temperature drop below minimum threshold. Stopping computation in step " + i);
  19849. return false;
  19850. }
  19851. return true;
  19852. };
  19853. var done = function done() {
  19854. if (options.animate === true || options.animate === false) {
  19855. refresh();
  19856. // Layout has finished
  19857. layout.one('layoutstop', options.stop);
  19858. layout.emit({
  19859. type: 'layoutstop',
  19860. layout: layout
  19861. });
  19862. } else {
  19863. var nodes = options.eles.nodes();
  19864. var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  19865. nodes.layoutPositions(layout, options, getScaledPos);
  19866. }
  19867. };
  19868. var i = 0;
  19869. var loopRet = true;
  19870. if (options.animate === true) {
  19871. var _frame = function frame() {
  19872. var f = 0;
  19873. while (loopRet && f < options.refresh) {
  19874. loopRet = mainLoop(i);
  19875. i++;
  19876. f++;
  19877. }
  19878. if (!loopRet) {
  19879. // it's done
  19880. separateComponents(layoutInfo, options);
  19881. done();
  19882. } else {
  19883. var now = performanceNow();
  19884. if (now - startTime >= options.animationThreshold) {
  19885. refresh();
  19886. }
  19887. requestAnimationFrame(_frame);
  19888. }
  19889. };
  19890. _frame();
  19891. } else {
  19892. while (loopRet) {
  19893. loopRet = mainLoop(i);
  19894. i++;
  19895. }
  19896. separateComponents(layoutInfo, options);
  19897. done();
  19898. }
  19899. return this; // chaining
  19900. };
  19901. /**
  19902. * @brief : called on continuous layouts to stop them before they finish
  19903. */
  19904. CoseLayout.prototype.stop = function () {
  19905. this.stopped = true;
  19906. if (this.thread) {
  19907. this.thread.stop();
  19908. }
  19909. this.emit('layoutstop');
  19910. return this; // chaining
  19911. };
  19912. CoseLayout.prototype.destroy = function () {
  19913. if (this.thread) {
  19914. this.thread.stop();
  19915. }
  19916. return this; // chaining
  19917. };
  19918. /**
  19919. * @brief : Creates an object which is contains all the data
  19920. * used in the layout process
  19921. * @arg cy : cytoscape.js object
  19922. * @return : layoutInfo object initialized
  19923. */
  19924. var createLayoutInfo = function createLayoutInfo(cy, layout, options) {
  19925. // Shortcut
  19926. var edges = options.eles.edges();
  19927. var nodes = options.eles.nodes();
  19928. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19929. x1: 0,
  19930. y1: 0,
  19931. w: cy.width(),
  19932. h: cy.height()
  19933. });
  19934. var layoutInfo = {
  19935. isCompound: cy.hasCompoundNodes(),
  19936. layoutNodes: [],
  19937. idToIndex: {},
  19938. nodeSize: nodes.size(),
  19939. graphSet: [],
  19940. indexToGraph: [],
  19941. layoutEdges: [],
  19942. edgeSize: edges.size(),
  19943. temperature: options.initialTemp,
  19944. clientWidth: bb.w,
  19945. clientHeight: bb.h,
  19946. boundingBox: bb
  19947. };
  19948. var components = options.eles.components();
  19949. var id2cmptId = {};
  19950. for (var i = 0; i < components.length; i++) {
  19951. var component = components[i];
  19952. for (var j = 0; j < component.length; j++) {
  19953. var node = component[j];
  19954. id2cmptId[node.id()] = i;
  19955. }
  19956. }
  19957. // Iterate over all nodes, creating layout nodes
  19958. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  19959. var n = nodes[i];
  19960. var nbb = n.layoutDimensions(options);
  19961. var tempNode = {};
  19962. tempNode.isLocked = n.locked();
  19963. tempNode.id = n.data('id');
  19964. tempNode.parentId = n.data('parent');
  19965. tempNode.cmptId = id2cmptId[n.id()];
  19966. tempNode.children = [];
  19967. tempNode.positionX = n.position('x');
  19968. tempNode.positionY = n.position('y');
  19969. tempNode.offsetX = 0;
  19970. tempNode.offsetY = 0;
  19971. tempNode.height = nbb.w;
  19972. tempNode.width = nbb.h;
  19973. tempNode.maxX = tempNode.positionX + tempNode.width / 2;
  19974. tempNode.minX = tempNode.positionX - tempNode.width / 2;
  19975. tempNode.maxY = tempNode.positionY + tempNode.height / 2;
  19976. tempNode.minY = tempNode.positionY - tempNode.height / 2;
  19977. tempNode.padLeft = parseFloat(n.style('padding'));
  19978. tempNode.padRight = parseFloat(n.style('padding'));
  19979. tempNode.padTop = parseFloat(n.style('padding'));
  19980. tempNode.padBottom = parseFloat(n.style('padding'));
  19981. // forces
  19982. tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion;
  19983. // Add new node
  19984. layoutInfo.layoutNodes.push(tempNode);
  19985. // Add entry to id-index map
  19986. layoutInfo.idToIndex[tempNode.id] = i;
  19987. }
  19988. // Inline implementation of a queue, used for traversing the graph in BFS order
  19989. var queue = [];
  19990. var start = 0; // Points to the start the queue
  19991. var end = -1; // Points to the end of the queue
  19992. var tempGraph = [];
  19993. // Second pass to add child information and
  19994. // initialize queue for hierarchical traversal
  19995. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  19996. var n = layoutInfo.layoutNodes[i];
  19997. var p_id = n.parentId;
  19998. // Check if node n has a parent node
  19999. if (null != p_id) {
  20000. // Add node Id to parent's list of children
  20001. layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);
  20002. } else {
  20003. // If a node doesn't have a parent, then it's in the root graph
  20004. queue[++end] = n.id;
  20005. tempGraph.push(n.id);
  20006. }
  20007. }
  20008. // Add root graph to graphSet
  20009. layoutInfo.graphSet.push(tempGraph);
  20010. // Traverse the graph, level by level,
  20011. while (start <= end) {
  20012. // Get the node to visit and remove it from queue
  20013. var node_id = queue[start++];
  20014. var node_ix = layoutInfo.idToIndex[node_id];
  20015. var node = layoutInfo.layoutNodes[node_ix];
  20016. var children = node.children;
  20017. if (children.length > 0) {
  20018. // Add children nodes as a new graph to graph set
  20019. layoutInfo.graphSet.push(children);
  20020. // Add children to que queue to be visited
  20021. for (var i = 0; i < children.length; i++) {
  20022. queue[++end] = children[i];
  20023. }
  20024. }
  20025. }
  20026. // Create indexToGraph map
  20027. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20028. var graph = layoutInfo.graphSet[i];
  20029. for (var j = 0; j < graph.length; j++) {
  20030. var index = layoutInfo.idToIndex[graph[j]];
  20031. layoutInfo.indexToGraph[index] = i;
  20032. }
  20033. }
  20034. // Iterate over all edges, creating Layout Edges
  20035. for (var i = 0; i < layoutInfo.edgeSize; i++) {
  20036. var e = edges[i];
  20037. var tempEdge = {};
  20038. tempEdge.id = e.data('id');
  20039. tempEdge.sourceId = e.data('source');
  20040. tempEdge.targetId = e.data('target');
  20041. // Compute ideal length
  20042. var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;
  20043. var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity;
  20044. // Check if it's an inter graph edge
  20045. var sourceIx = layoutInfo.idToIndex[tempEdge.sourceId];
  20046. var targetIx = layoutInfo.idToIndex[tempEdge.targetId];
  20047. var sourceGraph = layoutInfo.indexToGraph[sourceIx];
  20048. var targetGraph = layoutInfo.indexToGraph[targetIx];
  20049. if (sourceGraph != targetGraph) {
  20050. // Find lowest common graph ancestor
  20051. var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo);
  20052. // Compute sum of node depths, relative to lca graph
  20053. var lcaGraph = layoutInfo.graphSet[lca];
  20054. var depth = 0;
  20055. // Source depth
  20056. var tempNode = layoutInfo.layoutNodes[sourceIx];
  20057. while (-1 === lcaGraph.indexOf(tempNode.id)) {
  20058. tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
  20059. depth++;
  20060. }
  20061. // Target depth
  20062. tempNode = layoutInfo.layoutNodes[targetIx];
  20063. while (-1 === lcaGraph.indexOf(tempNode.id)) {
  20064. tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
  20065. depth++;
  20066. }
  20067. // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +
  20068. // ". Index: " + lca + " Contents: " + lcaGraph.toString() +
  20069. // ". Depth: " + depth);
  20070. // Update idealLength
  20071. idealLength *= depth * options.nestingFactor;
  20072. }
  20073. tempEdge.idealLength = idealLength;
  20074. tempEdge.elasticity = elasticity;
  20075. layoutInfo.layoutEdges.push(tempEdge);
  20076. }
  20077. // Finally, return layoutInfo object
  20078. return layoutInfo;
  20079. };
  20080. /**
  20081. * @brief : This function finds the index of the lowest common
  20082. * graph ancestor between 2 nodes in the subtree
  20083. * (from the graph hierarchy induced tree) whose
  20084. * root is graphIx
  20085. *
  20086. * @arg node1: node1's ID
  20087. * @arg node2: node2's ID
  20088. * @arg layoutInfo: layoutInfo object
  20089. *
  20090. */
  20091. var findLCA = function findLCA(node1, node2, layoutInfo) {
  20092. // Find their common ancester, starting from the root graph
  20093. var res = _findLCA_aux(node1, node2, 0, layoutInfo);
  20094. if (2 > res.count) {
  20095. // If aux function couldn't find the common ancester,
  20096. // then it is the root graph
  20097. return 0;
  20098. } else {
  20099. return res.graph;
  20100. }
  20101. };
  20102. /**
  20103. * @brief : Auxiliary function used for LCA computation
  20104. *
  20105. * @arg node1 : node1's ID
  20106. * @arg node2 : node2's ID
  20107. * @arg graphIx : subgraph index
  20108. * @arg layoutInfo : layoutInfo object
  20109. *
  20110. * @return : object of the form {count: X, graph: Y}, where:
  20111. * X is the number of ancestors (max: 2) found in
  20112. * graphIx (and it's subgraphs),
  20113. * Y is the graph index of the lowest graph containing
  20114. * all X nodes
  20115. */
  20116. var _findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {
  20117. var graph = layoutInfo.graphSet[graphIx];
  20118. // If both nodes belongs to graphIx
  20119. if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {
  20120. return {
  20121. count: 2,
  20122. graph: graphIx
  20123. };
  20124. }
  20125. // Make recursive calls for all subgraphs
  20126. var c = 0;
  20127. for (var i = 0; i < graph.length; i++) {
  20128. var nodeId = graph[i];
  20129. var nodeIx = layoutInfo.idToIndex[nodeId];
  20130. var children = layoutInfo.layoutNodes[nodeIx].children;
  20131. // If the node has no child, skip it
  20132. if (0 === children.length) {
  20133. continue;
  20134. }
  20135. var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];
  20136. var result = _findLCA_aux(node1, node2, childGraphIx, layoutInfo);
  20137. if (0 === result.count) {
  20138. // Neither node1 nor node2 are present in this subgraph
  20139. continue;
  20140. } else if (1 === result.count) {
  20141. // One of (node1, node2) is present in this subgraph
  20142. c++;
  20143. if (2 === c) {
  20144. // We've already found both nodes, no need to keep searching
  20145. break;
  20146. }
  20147. } else {
  20148. // Both nodes are present in this subgraph
  20149. return result;
  20150. }
  20151. }
  20152. return {
  20153. count: c,
  20154. graph: graphIx
  20155. };
  20156. };
  20157. /**
  20158. * @brief: printsLayoutInfo into js console
  20159. * Only used for debbuging
  20160. */
  20161. var printLayoutInfo;
  20162. /**
  20163. * @brief : Randomizes the position of all nodes
  20164. */
  20165. var randomizePositions = function randomizePositions(layoutInfo, cy) {
  20166. var width = layoutInfo.clientWidth;
  20167. var height = layoutInfo.clientHeight;
  20168. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20169. var n = layoutInfo.layoutNodes[i];
  20170. // No need to randomize compound nodes or locked nodes
  20171. if (0 === n.children.length && !n.isLocked) {
  20172. n.positionX = Math.random() * width;
  20173. n.positionY = Math.random() * height;
  20174. }
  20175. }
  20176. };
  20177. var getScaleInBoundsFn = function getScaleInBoundsFn(layoutInfo, options, nodes) {
  20178. var bb = layoutInfo.boundingBox;
  20179. var coseBB = {
  20180. x1: Infinity,
  20181. x2: -Infinity,
  20182. y1: Infinity,
  20183. y2: -Infinity
  20184. };
  20185. if (options.boundingBox) {
  20186. nodes.forEach(function (node) {
  20187. var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[node.data('id')]];
  20188. coseBB.x1 = Math.min(coseBB.x1, lnode.positionX);
  20189. coseBB.x2 = Math.max(coseBB.x2, lnode.positionX);
  20190. coseBB.y1 = Math.min(coseBB.y1, lnode.positionY);
  20191. coseBB.y2 = Math.max(coseBB.y2, lnode.positionY);
  20192. });
  20193. coseBB.w = coseBB.x2 - coseBB.x1;
  20194. coseBB.h = coseBB.y2 - coseBB.y1;
  20195. }
  20196. return function (ele, i) {
  20197. var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];
  20198. if (options.boundingBox) {
  20199. // then add extra bounding box constraint
  20200. // Handle single node case where coseBB.w or coseBB.h is 0
  20201. var pctX = coseBB.w === 0 ? 0.5 : (lnode.positionX - coseBB.x1) / coseBB.w;
  20202. var pctY = coseBB.h === 0 ? 0.5 : (lnode.positionY - coseBB.y1) / coseBB.h;
  20203. return {
  20204. x: bb.x1 + pctX * bb.w,
  20205. y: bb.y1 + pctY * bb.h
  20206. };
  20207. } else {
  20208. return {
  20209. x: lnode.positionX,
  20210. y: lnode.positionY
  20211. };
  20212. }
  20213. };
  20214. };
  20215. /**
  20216. * @brief : Updates the positions of nodes in the network
  20217. * @arg layoutInfo : LayoutInfo object
  20218. * @arg cy : Cytoscape object
  20219. * @arg options : Layout options
  20220. */
  20221. var refreshPositions = function refreshPositions(layoutInfo, cy, options) {
  20222. // var s = 'Refreshing positions';
  20223. // logDebug(s);
  20224. var layout = options.layout;
  20225. var nodes = options.eles.nodes();
  20226. var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  20227. nodes.positions(getScaledPos);
  20228. // Trigger layoutReady only on first call
  20229. if (true !== layoutInfo.ready) {
  20230. // s = 'Triggering layoutready';
  20231. // logDebug(s);
  20232. layoutInfo.ready = true;
  20233. layout.one('layoutready', options.ready);
  20234. layout.emit({
  20235. type: 'layoutready',
  20236. layout: this
  20237. });
  20238. }
  20239. };
  20240. /**
  20241. * @brief : Logs a debug message in JS console, if DEBUG is ON
  20242. */
  20243. // var logDebug = function(text) {
  20244. // if (DEBUG) {
  20245. // console.debug(text);
  20246. // }
  20247. // };
  20248. /**
  20249. * @brief : Performs one iteration of the physical simulation
  20250. * @arg layoutInfo : LayoutInfo object already initialized
  20251. * @arg cy : Cytoscape object
  20252. * @arg options : Layout options
  20253. */
  20254. var step = function step(layoutInfo, options, _step) {
  20255. // var s = "\n\n###############################";
  20256. // s += "\nSTEP: " + step;
  20257. // s += "\n###############################\n";
  20258. // logDebug(s);
  20259. // Calculate node repulsions
  20260. calculateNodeForces(layoutInfo, options);
  20261. // Calculate edge forces
  20262. calculateEdgeForces(layoutInfo);
  20263. // Calculate gravity forces
  20264. calculateGravityForces(layoutInfo, options);
  20265. // Propagate forces from parent to child
  20266. propagateForces(layoutInfo);
  20267. // Update positions based on calculated forces
  20268. updatePositions(layoutInfo);
  20269. };
  20270. /**
  20271. * @brief : Computes the node repulsion forces
  20272. */
  20273. var calculateNodeForces = function calculateNodeForces(layoutInfo, options) {
  20274. // Go through each of the graphs in graphSet
  20275. // Nodes only repel each other if they belong to the same graph
  20276. // var s = 'calculateNodeForces';
  20277. // logDebug(s);
  20278. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20279. var graph = layoutInfo.graphSet[i];
  20280. var numNodes = graph.length;
  20281. // s = "Set: " + graph.toString();
  20282. // logDebug(s);
  20283. // Now get all the pairs of nodes
  20284. // Only get each pair once, (A, B) = (B, A)
  20285. for (var j = 0; j < numNodes; j++) {
  20286. var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
  20287. for (var k = j + 1; k < numNodes; k++) {
  20288. var node2 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[k]]];
  20289. nodeRepulsion(node1, node2, layoutInfo, options);
  20290. }
  20291. }
  20292. }
  20293. };
  20294. var randomDistance = function randomDistance(max) {
  20295. return -1 + 2 * max * Math.random();
  20296. };
  20297. /**
  20298. * @brief : Compute the node repulsion forces between a pair of nodes
  20299. */
  20300. var nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {
  20301. // var s = "Node repulsion. Node1: " + node1.id + " Node2: " + node2.id;
  20302. var cmptId1 = node1.cmptId;
  20303. var cmptId2 = node2.cmptId;
  20304. if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {
  20305. return;
  20306. }
  20307. // Get direction of line connecting both node centers
  20308. var directionX = node2.positionX - node1.positionX;
  20309. var directionY = node2.positionY - node1.positionY;
  20310. var maxRandDist = 1;
  20311. // s += "\ndirectionX: " + directionX + ", directionY: " + directionY;
  20312. // If both centers are the same, apply a random force
  20313. if (0 === directionX && 0 === directionY) {
  20314. directionX = randomDistance(maxRandDist);
  20315. directionY = randomDistance(maxRandDist);
  20316. }
  20317. var overlap = nodesOverlap(node1, node2, directionX, directionY);
  20318. if (overlap > 0) {
  20319. // s += "\nNodes DO overlap.";
  20320. // s += "\nOverlap: " + overlap;
  20321. // If nodes overlap, repulsion force is proportional
  20322. // to the overlap
  20323. var force = options.nodeOverlap * overlap;
  20324. // Compute the module and components of the force vector
  20325. var distance = Math.sqrt(directionX * directionX + directionY * directionY);
  20326. // s += "\nDistance: " + distance;
  20327. var forceX = force * directionX / distance;
  20328. var forceY = force * directionY / distance;
  20329. } else {
  20330. // s += "\nNodes do NOT overlap.";
  20331. // If there's no overlap, force is inversely proportional
  20332. // to squared distance
  20333. // Get clipping points for both nodes
  20334. var point1 = findClippingPoint(node1, directionX, directionY);
  20335. var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY);
  20336. // Use clipping points to compute distance
  20337. var distanceX = point2.x - point1.x;
  20338. var distanceY = point2.y - point1.y;
  20339. var distanceSqr = distanceX * distanceX + distanceY * distanceY;
  20340. var distance = Math.sqrt(distanceSqr);
  20341. // s += "\nDistance: " + distance;
  20342. // Compute the module and components of the force vector
  20343. var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;
  20344. var forceX = force * distanceX / distance;
  20345. var forceY = force * distanceY / distance;
  20346. }
  20347. // Apply force
  20348. if (!node1.isLocked) {
  20349. node1.offsetX -= forceX;
  20350. node1.offsetY -= forceY;
  20351. }
  20352. if (!node2.isLocked) {
  20353. node2.offsetX += forceX;
  20354. node2.offsetY += forceY;
  20355. }
  20356. // s += "\nForceX: " + forceX + " ForceY: " + forceY;
  20357. // logDebug(s);
  20358. return;
  20359. };
  20360. /**
  20361. * @brief : Determines whether two nodes overlap or not
  20362. * @return : Amount of overlapping (0 => no overlap)
  20363. */
  20364. var nodesOverlap = function nodesOverlap(node1, node2, dX, dY) {
  20365. if (dX > 0) {
  20366. var overlapX = node1.maxX - node2.minX;
  20367. } else {
  20368. var overlapX = node2.maxX - node1.minX;
  20369. }
  20370. if (dY > 0) {
  20371. var overlapY = node1.maxY - node2.minY;
  20372. } else {
  20373. var overlapY = node2.maxY - node1.minY;
  20374. }
  20375. if (overlapX >= 0 && overlapY >= 0) {
  20376. return Math.sqrt(overlapX * overlapX + overlapY * overlapY);
  20377. } else {
  20378. return 0;
  20379. }
  20380. };
  20381. /**
  20382. * @brief : Finds the point in which an edge (direction dX, dY) intersects
  20383. * the rectangular bounding box of it's source/target node
  20384. */
  20385. var findClippingPoint = function findClippingPoint(node, dX, dY) {
  20386. // Shorcuts
  20387. var X = node.positionX;
  20388. var Y = node.positionY;
  20389. var H = node.height || 1;
  20390. var W = node.width || 1;
  20391. var dirSlope = dY / dX;
  20392. var nodeSlope = H / W;
  20393. // var s = 'Computing clipping point of node ' + node.id +
  20394. // " . Height: " + H + ", Width: " + W +
  20395. // "\nDirection " + dX + ", " + dY;
  20396. //
  20397. // Compute intersection
  20398. var res = {};
  20399. // Case: Vertical direction (up)
  20400. if (0 === dX && 0 < dY) {
  20401. res.x = X;
  20402. // s += "\nUp direction";
  20403. res.y = Y + H / 2;
  20404. return res;
  20405. }
  20406. // Case: Vertical direction (down)
  20407. if (0 === dX && 0 > dY) {
  20408. res.x = X;
  20409. res.y = Y + H / 2;
  20410. // s += "\nDown direction";
  20411. return res;
  20412. }
  20413. // Case: Intersects the right border
  20414. if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
  20415. res.x = X + W / 2;
  20416. res.y = Y + W * dY / 2 / dX;
  20417. // s += "\nRightborder";
  20418. return res;
  20419. }
  20420. // Case: Intersects the left border
  20421. if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
  20422. res.x = X - W / 2;
  20423. res.y = Y - W * dY / 2 / dX;
  20424. // s += "\nLeftborder";
  20425. return res;
  20426. }
  20427. // Case: Intersects the top border
  20428. if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
  20429. res.x = X + H * dX / 2 / dY;
  20430. res.y = Y + H / 2;
  20431. // s += "\nTop border";
  20432. return res;
  20433. }
  20434. // Case: Intersects the bottom border
  20435. if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
  20436. res.x = X - H * dX / 2 / dY;
  20437. res.y = Y - H / 2;
  20438. // s += "\nBottom border";
  20439. return res;
  20440. }
  20441. // s += "\nClipping point found at " + res.x + ", " + res.y;
  20442. // logDebug(s);
  20443. return res;
  20444. };
  20445. /**
  20446. * @brief : Calculates all edge forces
  20447. */
  20448. var calculateEdgeForces = function calculateEdgeForces(layoutInfo, options) {
  20449. // Iterate over all edges
  20450. for (var i = 0; i < layoutInfo.edgeSize; i++) {
  20451. // Get edge, source & target nodes
  20452. var edge = layoutInfo.layoutEdges[i];
  20453. var sourceIx = layoutInfo.idToIndex[edge.sourceId];
  20454. var source = layoutInfo.layoutNodes[sourceIx];
  20455. var targetIx = layoutInfo.idToIndex[edge.targetId];
  20456. var target = layoutInfo.layoutNodes[targetIx];
  20457. // Get direction of line connecting both node centers
  20458. var directionX = target.positionX - source.positionX;
  20459. var directionY = target.positionY - source.positionY;
  20460. // If both centers are the same, do nothing.
  20461. // A random force has already been applied as node repulsion
  20462. if (0 === directionX && 0 === directionY) {
  20463. continue;
  20464. }
  20465. // Get clipping points for both nodes
  20466. var point1 = findClippingPoint(source, directionX, directionY);
  20467. var point2 = findClippingPoint(target, -1 * directionX, -1 * directionY);
  20468. var lx = point2.x - point1.x;
  20469. var ly = point2.y - point1.y;
  20470. var l = Math.sqrt(lx * lx + ly * ly);
  20471. var force = Math.pow(edge.idealLength - l, 2) / edge.elasticity;
  20472. if (0 !== l) {
  20473. var forceX = force * lx / l;
  20474. var forceY = force * ly / l;
  20475. } else {
  20476. var forceX = 0;
  20477. var forceY = 0;
  20478. }
  20479. // Add this force to target and source nodes
  20480. if (!source.isLocked) {
  20481. source.offsetX += forceX;
  20482. source.offsetY += forceY;
  20483. }
  20484. if (!target.isLocked) {
  20485. target.offsetX -= forceX;
  20486. target.offsetY -= forceY;
  20487. }
  20488. // var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;
  20489. // s += "\nDistance: " + l + " Force: (" + forceX + ", " + forceY + ")";
  20490. // logDebug(s);
  20491. }
  20492. };
  20493. /**
  20494. * @brief : Computes gravity forces for all nodes
  20495. */
  20496. var calculateGravityForces = function calculateGravityForces(layoutInfo, options) {
  20497. if (options.gravity === 0) {
  20498. return;
  20499. }
  20500. var distThreshold = 1;
  20501. // var s = 'calculateGravityForces';
  20502. // logDebug(s);
  20503. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20504. var graph = layoutInfo.graphSet[i];
  20505. var numNodes = graph.length;
  20506. // s = "Set: " + graph.toString();
  20507. // logDebug(s);
  20508. // Compute graph center
  20509. if (0 === i) {
  20510. var centerX = layoutInfo.clientHeight / 2;
  20511. var centerY = layoutInfo.clientWidth / 2;
  20512. } else {
  20513. // Get Parent node for this graph, and use its position as center
  20514. var temp = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[0]]];
  20515. var parent = layoutInfo.layoutNodes[layoutInfo.idToIndex[temp.parentId]];
  20516. var centerX = parent.positionX;
  20517. var centerY = parent.positionY;
  20518. }
  20519. // s = "Center found at: " + centerX + ", " + centerY;
  20520. // logDebug(s);
  20521. // Apply force to all nodes in graph
  20522. for (var j = 0; j < numNodes; j++) {
  20523. var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
  20524. // s = "Node: " + node.id;
  20525. if (node.isLocked) {
  20526. continue;
  20527. }
  20528. var dx = centerX - node.positionX;
  20529. var dy = centerY - node.positionY;
  20530. var d = Math.sqrt(dx * dx + dy * dy);
  20531. if (d > distThreshold) {
  20532. var fx = options.gravity * dx / d;
  20533. var fy = options.gravity * dy / d;
  20534. node.offsetX += fx;
  20535. node.offsetY += fy;
  20536. // s += ": Applied force: " + fx + ", " + fy;
  20537. }
  20538. // logDebug(s);
  20539. }
  20540. }
  20541. };
  20542. /**
  20543. * @brief : This function propagates the existing offsets from
  20544. * parent nodes to its descendents.
  20545. * @arg layoutInfo : layoutInfo Object
  20546. * @arg cy : cytoscape Object
  20547. * @arg options : Layout options
  20548. */
  20549. var propagateForces = function propagateForces(layoutInfo, options) {
  20550. // Inline implementation of a queue, used for traversing the graph in BFS order
  20551. var queue = [];
  20552. var start = 0; // Points to the start the queue
  20553. var end = -1; // Points to the end of the queue
  20554. // logDebug('propagateForces');
  20555. // Start by visiting the nodes in the root graph
  20556. queue.push.apply(queue, layoutInfo.graphSet[0]);
  20557. end += layoutInfo.graphSet[0].length;
  20558. // Traverse the graph, level by level,
  20559. while (start <= end) {
  20560. // Get the node to visit and remove it from queue
  20561. var nodeId = queue[start++];
  20562. var nodeIndex = layoutInfo.idToIndex[nodeId];
  20563. var node = layoutInfo.layoutNodes[nodeIndex];
  20564. var children = node.children;
  20565. // We only need to process the node if it's compound
  20566. if (0 < children.length && !node.isLocked) {
  20567. var offX = node.offsetX;
  20568. var offY = node.offsetY;
  20569. // var s = "Propagating offset from parent node : " + node.id +
  20570. // ". OffsetX: " + offX + ". OffsetY: " + offY;
  20571. // s += "\n Children: " + children.toString();
  20572. // logDebug(s);
  20573. for (var i = 0; i < children.length; i++) {
  20574. var childNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[children[i]]];
  20575. // Propagate offset
  20576. childNode.offsetX += offX;
  20577. childNode.offsetY += offY;
  20578. // Add children to queue to be visited
  20579. queue[++end] = children[i];
  20580. }
  20581. // Reset parent offsets
  20582. node.offsetX = 0;
  20583. node.offsetY = 0;
  20584. }
  20585. }
  20586. };
  20587. /**
  20588. * @brief : Updates the layout model positions, based on
  20589. * the accumulated forces
  20590. */
  20591. var updatePositions = function updatePositions(layoutInfo, options) {
  20592. // var s = 'Updating positions';
  20593. // logDebug(s);
  20594. // Reset boundaries for compound nodes
  20595. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20596. var n = layoutInfo.layoutNodes[i];
  20597. if (0 < n.children.length) {
  20598. // logDebug("Resetting boundaries of compound node: " + n.id);
  20599. n.maxX = undefined;
  20600. n.minX = undefined;
  20601. n.maxY = undefined;
  20602. n.minY = undefined;
  20603. }
  20604. }
  20605. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20606. var n = layoutInfo.layoutNodes[i];
  20607. if (0 < n.children.length || n.isLocked) {
  20608. // No need to set compound or locked node position
  20609. // logDebug("Skipping position update of node: " + n.id);
  20610. continue;
  20611. }
  20612. // s = "Node: " + n.id + " Previous position: (" +
  20613. // n.positionX + ", " + n.positionY + ").";
  20614. // Limit displacement in order to improve stability
  20615. var tempForce = limitForce(n.offsetX, n.offsetY, layoutInfo.temperature);
  20616. n.positionX += tempForce.x;
  20617. n.positionY += tempForce.y;
  20618. n.offsetX = 0;
  20619. n.offsetY = 0;
  20620. n.minX = n.positionX - n.width;
  20621. n.maxX = n.positionX + n.width;
  20622. n.minY = n.positionY - n.height;
  20623. n.maxY = n.positionY + n.height;
  20624. // s += " New Position: (" + n.positionX + ", " + n.positionY + ").";
  20625. // logDebug(s);
  20626. // Update ancestry boudaries
  20627. _updateAncestryBoundaries(n, layoutInfo);
  20628. }
  20629. // Update size, position of compund nodes
  20630. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20631. var n = layoutInfo.layoutNodes[i];
  20632. if (0 < n.children.length && !n.isLocked) {
  20633. n.positionX = (n.maxX + n.minX) / 2;
  20634. n.positionY = (n.maxY + n.minY) / 2;
  20635. n.width = n.maxX - n.minX;
  20636. n.height = n.maxY - n.minY;
  20637. // s = "Updating position, size of compound node " + n.id;
  20638. // s += "\nPositionX: " + n.positionX + ", PositionY: " + n.positionY;
  20639. // s += "\nWidth: " + n.width + ", Height: " + n.height;
  20640. // logDebug(s);
  20641. }
  20642. }
  20643. };
  20644. /**
  20645. * @brief : Limits a force (forceX, forceY) to be not
  20646. * greater (in modulo) than max.
  20647. 8 Preserves force direction.
  20648. */
  20649. var limitForce = function limitForce(forceX, forceY, max) {
  20650. // var s = "Limiting force: (" + forceX + ", " + forceY + "). Max: " + max;
  20651. var force = Math.sqrt(forceX * forceX + forceY * forceY);
  20652. if (force > max) {
  20653. var res = {
  20654. x: max * forceX / force,
  20655. y: max * forceY / force
  20656. };
  20657. } else {
  20658. var res = {
  20659. x: forceX,
  20660. y: forceY
  20661. };
  20662. }
  20663. // s += ".\nResult: (" + res.x + ", " + res.y + ")";
  20664. // logDebug(s);
  20665. return res;
  20666. };
  20667. /**
  20668. * @brief : Function used for keeping track of compound node
  20669. * sizes, since they should bound all their subnodes.
  20670. */
  20671. var _updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {
  20672. // var s = "Propagating new position/size of node " + node.id;
  20673. var parentId = node.parentId;
  20674. if (null == parentId) {
  20675. // If there's no parent, we are done
  20676. // s += ". No parent node.";
  20677. // logDebug(s);
  20678. return;
  20679. }
  20680. // Get Parent Node
  20681. var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];
  20682. var flag = false;
  20683. // MaxX
  20684. if (null == p.maxX || node.maxX + p.padRight > p.maxX) {
  20685. p.maxX = node.maxX + p.padRight;
  20686. flag = true;
  20687. // s += "\nNew maxX for parent node " + p.id + ": " + p.maxX;
  20688. }
  20689. // MinX
  20690. if (null == p.minX || node.minX - p.padLeft < p.minX) {
  20691. p.minX = node.minX - p.padLeft;
  20692. flag = true;
  20693. // s += "\nNew minX for parent node " + p.id + ": " + p.minX;
  20694. }
  20695. // MaxY
  20696. if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {
  20697. p.maxY = node.maxY + p.padBottom;
  20698. flag = true;
  20699. // s += "\nNew maxY for parent node " + p.id + ": " + p.maxY;
  20700. }
  20701. // MinY
  20702. if (null == p.minY || node.minY - p.padTop < p.minY) {
  20703. p.minY = node.minY - p.padTop;
  20704. flag = true;
  20705. // s += "\nNew minY for parent node " + p.id + ": " + p.minY;
  20706. }
  20707. // If updated boundaries, propagate changes upward
  20708. if (flag) {
  20709. // logDebug(s);
  20710. return _updateAncestryBoundaries(p, layoutInfo);
  20711. }
  20712. // s += ". No changes in boundaries/position of parent node " + p.id;
  20713. // logDebug(s);
  20714. return;
  20715. };
  20716. var separateComponents = function separateComponents(layoutInfo, options) {
  20717. var nodes = layoutInfo.layoutNodes;
  20718. var components = [];
  20719. for (var i = 0; i < nodes.length; i++) {
  20720. var node = nodes[i];
  20721. var cid = node.cmptId;
  20722. var component = components[cid] = components[cid] || [];
  20723. component.push(node);
  20724. }
  20725. var totalA = 0;
  20726. for (var i = 0; i < components.length; i++) {
  20727. var c = components[i];
  20728. if (!c) {
  20729. continue;
  20730. }
  20731. c.x1 = Infinity;
  20732. c.x2 = -Infinity;
  20733. c.y1 = Infinity;
  20734. c.y2 = -Infinity;
  20735. for (var j = 0; j < c.length; j++) {
  20736. var n = c[j];
  20737. c.x1 = Math.min(c.x1, n.positionX - n.width / 2);
  20738. c.x2 = Math.max(c.x2, n.positionX + n.width / 2);
  20739. c.y1 = Math.min(c.y1, n.positionY - n.height / 2);
  20740. c.y2 = Math.max(c.y2, n.positionY + n.height / 2);
  20741. }
  20742. c.w = c.x2 - c.x1;
  20743. c.h = c.y2 - c.y1;
  20744. totalA += c.w * c.h;
  20745. }
  20746. components.sort(function (c1, c2) {
  20747. return c2.w * c2.h - c1.w * c1.h;
  20748. });
  20749. var x = 0;
  20750. var y = 0;
  20751. var usedW = 0;
  20752. var rowH = 0;
  20753. var maxRowW = Math.sqrt(totalA) * layoutInfo.clientWidth / layoutInfo.clientHeight;
  20754. for (var i = 0; i < components.length; i++) {
  20755. var c = components[i];
  20756. if (!c) {
  20757. continue;
  20758. }
  20759. for (var j = 0; j < c.length; j++) {
  20760. var n = c[j];
  20761. if (!n.isLocked) {
  20762. n.positionX += x - c.x1;
  20763. n.positionY += y - c.y1;
  20764. }
  20765. }
  20766. x += c.w + options.componentSpacing;
  20767. usedW += c.w + options.componentSpacing;
  20768. rowH = Math.max(rowH, c.h);
  20769. if (usedW > maxRowW) {
  20770. y += rowH + options.componentSpacing;
  20771. x = 0;
  20772. usedW = 0;
  20773. rowH = 0;
  20774. }
  20775. }
  20776. };
  20777. var defaults$3 = {
  20778. fit: true,
  20779. // whether to fit the viewport to the graph
  20780. padding: 30,
  20781. // padding used on fit
  20782. boundingBox: undefined,
  20783. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  20784. avoidOverlap: true,
  20785. // prevents node overlap, may overflow boundingBox if not enough space
  20786. avoidOverlapPadding: 10,
  20787. // extra spacing around nodes when avoidOverlap: true
  20788. nodeDimensionsIncludeLabels: false,
  20789. // Excludes the label when calculating node bounding boxes for the layout algorithm
  20790. spacingFactor: undefined,
  20791. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  20792. condense: false,
  20793. // uses all available space on false, uses minimal space on true
  20794. rows: undefined,
  20795. // force num of rows in the grid
  20796. cols: undefined,
  20797. // force num of columns in the grid
  20798. position: function position(node) {},
  20799. // returns { row, col } for element
  20800. sort: undefined,
  20801. // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  20802. animate: false,
  20803. // whether to transition the node positions
  20804. animationDuration: 500,
  20805. // duration of animation in ms if enabled
  20806. animationEasing: undefined,
  20807. // easing of animation if enabled
  20808. animateFilter: function animateFilter(node, i) {
  20809. return true;
  20810. },
  20811. // 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
  20812. ready: undefined,
  20813. // callback on layoutready
  20814. stop: undefined,
  20815. // callback on layoutstop
  20816. transform: function transform(node, position) {
  20817. return position;
  20818. } // transform a given node position. Useful for changing flow direction in discrete layouts
  20819. };
  20820. function GridLayout(options) {
  20821. this.options = extend({}, defaults$3, options);
  20822. }
  20823. GridLayout.prototype.run = function () {
  20824. var params = this.options;
  20825. var options = params;
  20826. var cy = params.cy;
  20827. var eles = options.eles;
  20828. var nodes = eles.nodes().not(':parent');
  20829. if (options.sort) {
  20830. nodes = nodes.sort(options.sort);
  20831. }
  20832. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  20833. x1: 0,
  20834. y1: 0,
  20835. w: cy.width(),
  20836. h: cy.height()
  20837. });
  20838. if (bb.h === 0 || bb.w === 0) {
  20839. eles.nodes().layoutPositions(this, options, function (ele) {
  20840. return {
  20841. x: bb.x1,
  20842. y: bb.y1
  20843. };
  20844. });
  20845. } else {
  20846. // width/height * splits^2 = cells where splits is number of times to split width
  20847. var cells = nodes.size();
  20848. var splits = Math.sqrt(cells * bb.h / bb.w);
  20849. var rows = Math.round(splits);
  20850. var cols = Math.round(bb.w / bb.h * splits);
  20851. var small = function small(val) {
  20852. if (val == null) {
  20853. return Math.min(rows, cols);
  20854. } else {
  20855. var min = Math.min(rows, cols);
  20856. if (min == rows) {
  20857. rows = val;
  20858. } else {
  20859. cols = val;
  20860. }
  20861. }
  20862. };
  20863. var large = function large(val) {
  20864. if (val == null) {
  20865. return Math.max(rows, cols);
  20866. } else {
  20867. var max = Math.max(rows, cols);
  20868. if (max == rows) {
  20869. rows = val;
  20870. } else {
  20871. cols = val;
  20872. }
  20873. }
  20874. };
  20875. var oRows = options.rows;
  20876. var oCols = options.cols != null ? options.cols : options.columns;
  20877. // if rows or columns were set in options, use those values
  20878. if (oRows != null && oCols != null) {
  20879. rows = oRows;
  20880. cols = oCols;
  20881. } else if (oRows != null && oCols == null) {
  20882. rows = oRows;
  20883. cols = Math.ceil(cells / rows);
  20884. } else if (oRows == null && oCols != null) {
  20885. cols = oCols;
  20886. rows = Math.ceil(cells / cols);
  20887. }
  20888. // otherwise use the automatic values and adjust accordingly
  20889. // if rounding was up, see if we can reduce rows or columns
  20890. else if (cols * rows > cells) {
  20891. var sm = small();
  20892. var lg = large();
  20893. // reducing the small side takes away the most cells, so try it first
  20894. if ((sm - 1) * lg >= cells) {
  20895. small(sm - 1);
  20896. } else if ((lg - 1) * sm >= cells) {
  20897. large(lg - 1);
  20898. }
  20899. } else {
  20900. // if rounding was too low, add rows or columns
  20901. while (cols * rows < cells) {
  20902. var _sm = small();
  20903. var _lg = large();
  20904. // try to add to larger side first (adds less in multiplication)
  20905. if ((_lg + 1) * _sm >= cells) {
  20906. large(_lg + 1);
  20907. } else {
  20908. small(_sm + 1);
  20909. }
  20910. }
  20911. }
  20912. var cellWidth = bb.w / cols;
  20913. var cellHeight = bb.h / rows;
  20914. if (options.condense) {
  20915. cellWidth = 0;
  20916. cellHeight = 0;
  20917. }
  20918. if (options.avoidOverlap) {
  20919. for (var i = 0; i < nodes.length; i++) {
  20920. var node = nodes[i];
  20921. var pos = node._private.position;
  20922. if (pos.x == null || pos.y == null) {
  20923. // for bb
  20924. pos.x = 0;
  20925. pos.y = 0;
  20926. }
  20927. var nbb = node.layoutDimensions(options);
  20928. var p = options.avoidOverlapPadding;
  20929. var w = nbb.w + p;
  20930. var h = nbb.h + p;
  20931. cellWidth = Math.max(cellWidth, w);
  20932. cellHeight = Math.max(cellHeight, h);
  20933. }
  20934. }
  20935. var cellUsed = {}; // e.g. 'c-0-2' => true
  20936. var used = function used(row, col) {
  20937. return cellUsed['c-' + row + '-' + col] ? true : false;
  20938. };
  20939. var use = function use(row, col) {
  20940. cellUsed['c-' + row + '-' + col] = true;
  20941. };
  20942. // to keep track of current cell position
  20943. var row = 0;
  20944. var col = 0;
  20945. var moveToNextCell = function moveToNextCell() {
  20946. col++;
  20947. if (col >= cols) {
  20948. col = 0;
  20949. row++;
  20950. }
  20951. };
  20952. // get a cache of all the manual positions
  20953. var id2manPos = {};
  20954. for (var _i = 0; _i < nodes.length; _i++) {
  20955. var _node = nodes[_i];
  20956. var rcPos = options.position(_node);
  20957. if (rcPos && (rcPos.row !== undefined || rcPos.col !== undefined)) {
  20958. // must have at least row or col def'd
  20959. var _pos = {
  20960. row: rcPos.row,
  20961. col: rcPos.col
  20962. };
  20963. if (_pos.col === undefined) {
  20964. // find unused col
  20965. _pos.col = 0;
  20966. while (used(_pos.row, _pos.col)) {
  20967. _pos.col++;
  20968. }
  20969. } else if (_pos.row === undefined) {
  20970. // find unused row
  20971. _pos.row = 0;
  20972. while (used(_pos.row, _pos.col)) {
  20973. _pos.row++;
  20974. }
  20975. }
  20976. id2manPos[_node.id()] = _pos;
  20977. use(_pos.row, _pos.col);
  20978. }
  20979. }
  20980. var getPos = function getPos(element, i) {
  20981. var x, y;
  20982. if (element.locked() || element.isParent()) {
  20983. return false;
  20984. }
  20985. // see if we have a manual position set
  20986. var rcPos = id2manPos[element.id()];
  20987. if (rcPos) {
  20988. x = rcPos.col * cellWidth + cellWidth / 2 + bb.x1;
  20989. y = rcPos.row * cellHeight + cellHeight / 2 + bb.y1;
  20990. } else {
  20991. // otherwise set automatically
  20992. while (used(row, col)) {
  20993. moveToNextCell();
  20994. }
  20995. x = col * cellWidth + cellWidth / 2 + bb.x1;
  20996. y = row * cellHeight + cellHeight / 2 + bb.y1;
  20997. use(row, col);
  20998. moveToNextCell();
  20999. }
  21000. return {
  21001. x: x,
  21002. y: y
  21003. };
  21004. };
  21005. nodes.layoutPositions(this, options, getPos);
  21006. }
  21007. return this; // chaining
  21008. };
  21009. // default layout options
  21010. var defaults$2 = {
  21011. ready: function ready() {},
  21012. // on layoutready
  21013. stop: function stop() {} // on layoutstop
  21014. };
  21015. // constructor
  21016. // options : object containing layout options
  21017. function NullLayout(options) {
  21018. this.options = extend({}, defaults$2, options);
  21019. }
  21020. // runs the layout
  21021. NullLayout.prototype.run = function () {
  21022. var options = this.options;
  21023. var eles = options.eles; // elements to consider in the layout
  21024. var layout = this;
  21025. // cy is automatically populated for us in the constructor
  21026. // (disable eslint for next line as this serves as example layout code to external developers)
  21027. // eslint-disable-next-line no-unused-vars
  21028. options.cy;
  21029. layout.emit('layoutstart');
  21030. // puts all nodes at (0, 0)
  21031. // n.b. most layouts would use layoutPositions(), instead of positions() and manual events
  21032. eles.nodes().positions(function () {
  21033. return {
  21034. x: 0,
  21035. y: 0
  21036. };
  21037. });
  21038. // trigger layoutready when each node has had its position set at least once
  21039. layout.one('layoutready', options.ready);
  21040. layout.emit('layoutready');
  21041. // trigger layoutstop when the layout stops (e.g. finishes)
  21042. layout.one('layoutstop', options.stop);
  21043. layout.emit('layoutstop');
  21044. return this; // chaining
  21045. };
  21046. // called on continuous layouts to stop them before they finish
  21047. NullLayout.prototype.stop = function () {
  21048. return this; // chaining
  21049. };
  21050. var defaults$1 = {
  21051. positions: undefined,
  21052. // map of (node id) => (position obj); or function(node){ return somPos; }
  21053. zoom: undefined,
  21054. // the zoom level to set (prob want fit = false if set)
  21055. pan: undefined,
  21056. // the pan level to set (prob want fit = false if set)
  21057. fit: true,
  21058. // whether to fit to viewport
  21059. padding: 30,
  21060. // padding on fit
  21061. spacingFactor: undefined,
  21062. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  21063. animate: false,
  21064. // whether to transition the node positions
  21065. animationDuration: 500,
  21066. // duration of animation in ms if enabled
  21067. animationEasing: undefined,
  21068. // easing of animation if enabled
  21069. animateFilter: function animateFilter(node, i) {
  21070. return true;
  21071. },
  21072. // 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
  21073. ready: undefined,
  21074. // callback on layoutready
  21075. stop: undefined,
  21076. // callback on layoutstop
  21077. transform: function transform(node, position) {
  21078. return position;
  21079. } // transform a given node position. Useful for changing flow direction in discrete layouts
  21080. };
  21081. function PresetLayout(options) {
  21082. this.options = extend({}, defaults$1, options);
  21083. }
  21084. PresetLayout.prototype.run = function () {
  21085. var options = this.options;
  21086. var eles = options.eles;
  21087. var nodes = eles.nodes();
  21088. var posIsFn = fn$6(options.positions);
  21089. function getPosition(node) {
  21090. if (options.positions == null) {
  21091. return copyPosition(node.position());
  21092. }
  21093. if (posIsFn) {
  21094. return options.positions(node);
  21095. }
  21096. var pos = options.positions[node._private.data.id];
  21097. if (pos == null) {
  21098. return null;
  21099. }
  21100. return pos;
  21101. }
  21102. nodes.layoutPositions(this, options, function (node, i) {
  21103. var position = getPosition(node);
  21104. if (node.locked() || position == null) {
  21105. return false;
  21106. }
  21107. return position;
  21108. });
  21109. return this; // chaining
  21110. };
  21111. var defaults = {
  21112. fit: true,
  21113. // whether to fit to viewport
  21114. padding: 30,
  21115. // fit padding
  21116. boundingBox: undefined,
  21117. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  21118. animate: false,
  21119. // whether to transition the node positions
  21120. animationDuration: 500,
  21121. // duration of animation in ms if enabled
  21122. animationEasing: undefined,
  21123. // easing of animation if enabled
  21124. animateFilter: function animateFilter(node, i) {
  21125. return true;
  21126. },
  21127. // 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
  21128. ready: undefined,
  21129. // callback on layoutready
  21130. stop: undefined,
  21131. // callback on layoutstop
  21132. transform: function transform(node, position) {
  21133. return position;
  21134. } // transform a given node position. Useful for changing flow direction in discrete layouts
  21135. };
  21136. function RandomLayout(options) {
  21137. this.options = extend({}, defaults, options);
  21138. }
  21139. RandomLayout.prototype.run = function () {
  21140. var options = this.options;
  21141. var cy = options.cy;
  21142. var eles = options.eles;
  21143. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  21144. x1: 0,
  21145. y1: 0,
  21146. w: cy.width(),
  21147. h: cy.height()
  21148. });
  21149. var getPos = function getPos(node, i) {
  21150. return {
  21151. x: bb.x1 + Math.round(Math.random() * bb.w),
  21152. y: bb.y1 + Math.round(Math.random() * bb.h)
  21153. };
  21154. };
  21155. eles.nodes().layoutPositions(this, options, getPos);
  21156. return this; // chaining
  21157. };
  21158. var layout = [{
  21159. name: 'breadthfirst',
  21160. impl: BreadthFirstLayout
  21161. }, {
  21162. name: 'circle',
  21163. impl: CircleLayout
  21164. }, {
  21165. name: 'concentric',
  21166. impl: ConcentricLayout
  21167. }, {
  21168. name: 'cose',
  21169. impl: CoseLayout
  21170. }, {
  21171. name: 'grid',
  21172. impl: GridLayout
  21173. }, {
  21174. name: 'null',
  21175. impl: NullLayout
  21176. }, {
  21177. name: 'preset',
  21178. impl: PresetLayout
  21179. }, {
  21180. name: 'random',
  21181. impl: RandomLayout
  21182. }];
  21183. function NullRenderer(options) {
  21184. this.options = options;
  21185. this.notifications = 0; // for testing
  21186. }
  21187. var noop = function noop() {};
  21188. var throwImgErr = function throwImgErr() {
  21189. throw new Error('A headless instance can not render images');
  21190. };
  21191. NullRenderer.prototype = {
  21192. recalculateRenderedStyle: noop,
  21193. notify: function notify() {
  21194. this.notifications++;
  21195. },
  21196. init: noop,
  21197. isHeadless: function isHeadless() {
  21198. return true;
  21199. },
  21200. png: throwImgErr,
  21201. jpg: throwImgErr
  21202. };
  21203. var BRp$f = {};
  21204. BRp$f.arrowShapeWidth = 0.3;
  21205. BRp$f.registerArrowShapes = function () {
  21206. var arrowShapes = this.arrowShapes = {};
  21207. var renderer = this;
  21208. // Contract for arrow shapes:
  21209. // 0, 0 is arrow tip
  21210. // (0, 1) is direction towards node
  21211. // (1, 0) is right
  21212. //
  21213. // functional api:
  21214. // collide: check x, y in shape
  21215. // roughCollide: called before collide, no false negatives
  21216. // draw: draw
  21217. // spacing: dist(arrowTip, nodeBoundary)
  21218. // gap: dist(edgeTip, nodeBoundary), edgeTip may != arrowTip
  21219. var bbCollide = function bbCollide(x, y, size, angle, translation, edgeWidth, padding) {
  21220. var x1 = translation.x - size / 2 - padding;
  21221. var x2 = translation.x + size / 2 + padding;
  21222. var y1 = translation.y - size / 2 - padding;
  21223. var y2 = translation.y + size / 2 + padding;
  21224. var inside = x1 <= x && x <= x2 && y1 <= y && y <= y2;
  21225. return inside;
  21226. };
  21227. var transform = function transform(x, y, size, angle, translation) {
  21228. var xRotated = x * Math.cos(angle) - y * Math.sin(angle);
  21229. var yRotated = x * Math.sin(angle) + y * Math.cos(angle);
  21230. var xScaled = xRotated * size;
  21231. var yScaled = yRotated * size;
  21232. var xTranslated = xScaled + translation.x;
  21233. var yTranslated = yScaled + translation.y;
  21234. return {
  21235. x: xTranslated,
  21236. y: yTranslated
  21237. };
  21238. };
  21239. var transformPoints = function transformPoints(pts, size, angle, translation) {
  21240. var retPts = [];
  21241. for (var i = 0; i < pts.length; i += 2) {
  21242. var x = pts[i];
  21243. var y = pts[i + 1];
  21244. retPts.push(transform(x, y, size, angle, translation));
  21245. }
  21246. return retPts;
  21247. };
  21248. var pointsToArr = function pointsToArr(pts) {
  21249. var ret = [];
  21250. for (var i = 0; i < pts.length; i++) {
  21251. var p = pts[i];
  21252. ret.push(p.x, p.y);
  21253. }
  21254. return ret;
  21255. };
  21256. var standardGap = function standardGap(edge) {
  21257. return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;
  21258. };
  21259. var defineArrowShape = function defineArrowShape(name, defn) {
  21260. if (string(defn)) {
  21261. defn = arrowShapes[defn];
  21262. }
  21263. arrowShapes[name] = extend({
  21264. name: name,
  21265. points: [-0.15, -0.3, 0.15, -0.3, 0.15, 0.3, -0.15, 0.3],
  21266. collide: function collide(x, y, size, angle, translation, padding) {
  21267. var points = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21268. var inside = pointInsidePolygonPoints(x, y, points);
  21269. return inside;
  21270. },
  21271. roughCollide: bbCollide,
  21272. draw: function draw(context, size, angle, translation) {
  21273. var points = transformPoints(this.points, size, angle, translation);
  21274. renderer.arrowShapeImpl('polygon')(context, points);
  21275. },
  21276. spacing: function spacing(edge) {
  21277. return 0;
  21278. },
  21279. gap: standardGap
  21280. }, defn);
  21281. };
  21282. defineArrowShape('none', {
  21283. collide: falsify,
  21284. roughCollide: falsify,
  21285. draw: noop$1,
  21286. spacing: zeroify,
  21287. gap: zeroify
  21288. });
  21289. defineArrowShape('triangle', {
  21290. points: [-0.15, -0.3, 0, 0, 0.15, -0.3]
  21291. });
  21292. defineArrowShape('arrow', 'triangle');
  21293. defineArrowShape('triangle-backcurve', {
  21294. points: arrowShapes['triangle'].points,
  21295. controlPoint: [0, -0.15],
  21296. roughCollide: bbCollide,
  21297. draw: function draw(context, size, angle, translation, edgeWidth) {
  21298. var ptsTrans = transformPoints(this.points, size, angle, translation);
  21299. var ctrlPt = this.controlPoint;
  21300. var ctrlPtTrans = transform(ctrlPt[0], ctrlPt[1], size, angle, translation);
  21301. renderer.arrowShapeImpl(this.name)(context, ptsTrans, ctrlPtTrans);
  21302. },
  21303. gap: function gap(edge) {
  21304. return standardGap(edge) * 0.8;
  21305. }
  21306. });
  21307. defineArrowShape('triangle-tee', {
  21308. points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
  21309. pointsTee: [-0.15, -0.4, -0.15, -0.5, 0.15, -0.5, 0.15, -0.4],
  21310. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21311. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21312. var teePts = pointsToArr(transformPoints(this.pointsTee, size + 2 * padding, angle, translation));
  21313. var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
  21314. return inside;
  21315. },
  21316. draw: function draw(context, size, angle, translation, edgeWidth) {
  21317. var triPts = transformPoints(this.points, size, angle, translation);
  21318. var teePts = transformPoints(this.pointsTee, size, angle, translation);
  21319. renderer.arrowShapeImpl(this.name)(context, triPts, teePts);
  21320. }
  21321. });
  21322. defineArrowShape('circle-triangle', {
  21323. radius: 0.15,
  21324. pointsTr: [0, -0.15, 0.15, -0.45, -0.15, -0.45, 0, -0.15],
  21325. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21326. var t = translation;
  21327. var circleInside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
  21328. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21329. return pointInsidePolygonPoints(x, y, triPts) || circleInside;
  21330. },
  21331. draw: function draw(context, size, angle, translation, edgeWidth) {
  21332. var triPts = transformPoints(this.pointsTr, size, angle, translation);
  21333. renderer.arrowShapeImpl(this.name)(context, triPts, translation.x, translation.y, this.radius * size);
  21334. },
  21335. spacing: function spacing(edge) {
  21336. return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
  21337. }
  21338. });
  21339. defineArrowShape('triangle-cross', {
  21340. points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
  21341. baseCrossLinePts: [-0.15, -0.4,
  21342. // first half of the rectangle
  21343. -0.15, -0.4, 0.15, -0.4,
  21344. // second half of the rectangle
  21345. 0.15, -0.4],
  21346. crossLinePts: function crossLinePts(size, edgeWidth) {
  21347. // shift points so that the distance between the cross points matches edge width
  21348. var p = this.baseCrossLinePts.slice();
  21349. var shiftFactor = edgeWidth / size;
  21350. var y0 = 3;
  21351. var y1 = 5;
  21352. p[y0] = p[y0] - shiftFactor;
  21353. p[y1] = p[y1] - shiftFactor;
  21354. return p;
  21355. },
  21356. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21357. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21358. var teePts = pointsToArr(transformPoints(this.crossLinePts(size, edgeWidth), size + 2 * padding, angle, translation));
  21359. var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
  21360. return inside;
  21361. },
  21362. draw: function draw(context, size, angle, translation, edgeWidth) {
  21363. var triPts = transformPoints(this.points, size, angle, translation);
  21364. var crossLinePts = transformPoints(this.crossLinePts(size, edgeWidth), size, angle, translation);
  21365. renderer.arrowShapeImpl(this.name)(context, triPts, crossLinePts);
  21366. }
  21367. });
  21368. defineArrowShape('vee', {
  21369. points: [-0.15, -0.3, 0, 0, 0.15, -0.3, 0, -0.15],
  21370. gap: function gap(edge) {
  21371. return standardGap(edge) * 0.525;
  21372. }
  21373. });
  21374. defineArrowShape('circle', {
  21375. radius: 0.15,
  21376. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21377. var t = translation;
  21378. var inside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
  21379. return inside;
  21380. },
  21381. draw: function draw(context, size, angle, translation, edgeWidth) {
  21382. renderer.arrowShapeImpl(this.name)(context, translation.x, translation.y, this.radius * size);
  21383. },
  21384. spacing: function spacing(edge) {
  21385. return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
  21386. }
  21387. });
  21388. defineArrowShape('tee', {
  21389. points: [-0.15, 0, -0.15, -0.1, 0.15, -0.1, 0.15, 0],
  21390. spacing: function spacing(edge) {
  21391. return 1;
  21392. },
  21393. gap: function gap(edge) {
  21394. return 1;
  21395. }
  21396. });
  21397. defineArrowShape('square', {
  21398. points: [-0.15, 0.00, 0.15, 0.00, 0.15, -0.3, -0.15, -0.3]
  21399. });
  21400. defineArrowShape('diamond', {
  21401. points: [-0.15, -0.15, 0, -0.3, 0.15, -0.15, 0, 0],
  21402. gap: function gap(edge) {
  21403. return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
  21404. }
  21405. });
  21406. defineArrowShape('chevron', {
  21407. points: [0, 0, -0.15, -0.15, -0.1, -0.2, 0, -0.1, 0.1, -0.2, 0.15, -0.15],
  21408. gap: function gap(edge) {
  21409. return 0.95 * edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
  21410. }
  21411. });
  21412. };
  21413. var BRp$e = {};
  21414. // Project mouse
  21415. BRp$e.projectIntoViewport = function (clientX, clientY) {
  21416. var cy = this.cy;
  21417. var offsets = this.findContainerClientCoords();
  21418. var offsetLeft = offsets[0];
  21419. var offsetTop = offsets[1];
  21420. var scale = offsets[4];
  21421. var pan = cy.pan();
  21422. var zoom = cy.zoom();
  21423. var x = ((clientX - offsetLeft) / scale - pan.x) / zoom;
  21424. var y = ((clientY - offsetTop) / scale - pan.y) / zoom;
  21425. return [x, y];
  21426. };
  21427. BRp$e.findContainerClientCoords = function () {
  21428. if (this.containerBB) {
  21429. return this.containerBB;
  21430. }
  21431. var container = this.container;
  21432. var rect = container.getBoundingClientRect();
  21433. var style = this.cy.window().getComputedStyle(container);
  21434. var styleValue = function styleValue(name) {
  21435. return parseFloat(style.getPropertyValue(name));
  21436. };
  21437. var padding = {
  21438. left: styleValue('padding-left'),
  21439. right: styleValue('padding-right'),
  21440. top: styleValue('padding-top'),
  21441. bottom: styleValue('padding-bottom')
  21442. };
  21443. var border = {
  21444. left: styleValue('border-left-width'),
  21445. right: styleValue('border-right-width'),
  21446. top: styleValue('border-top-width'),
  21447. bottom: styleValue('border-bottom-width')
  21448. };
  21449. var clientWidth = container.clientWidth;
  21450. var clientHeight = container.clientHeight;
  21451. var paddingHor = padding.left + padding.right;
  21452. var paddingVer = padding.top + padding.bottom;
  21453. var borderHor = border.left + border.right;
  21454. var scale = rect.width / (clientWidth + borderHor);
  21455. var unscaledW = clientWidth - paddingHor;
  21456. var unscaledH = clientHeight - paddingVer;
  21457. var left = rect.left + padding.left + border.left;
  21458. var top = rect.top + padding.top + border.top;
  21459. return this.containerBB = [left, top, unscaledW, unscaledH, scale];
  21460. };
  21461. BRp$e.invalidateContainerClientCoordsCache = function () {
  21462. this.containerBB = null;
  21463. };
  21464. BRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {
  21465. return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];
  21466. };
  21467. BRp$e.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  21468. var self = this;
  21469. var r = this;
  21470. var eles = r.getCachedZSortedEles();
  21471. var near = []; // 1 node max, 1 edge max
  21472. var zoom = r.cy.zoom();
  21473. var hasCompounds = r.cy.hasCompoundNodes();
  21474. var edgeThreshold = (isTouch ? 24 : 8) / zoom;
  21475. var nodeThreshold = (isTouch ? 8 : 2) / zoom;
  21476. var labelThreshold = (isTouch ? 8 : 2) / zoom;
  21477. var minSqDist = Infinity;
  21478. var nearEdge;
  21479. var nearNode;
  21480. if (interactiveElementsOnly) {
  21481. eles = eles.interactive;
  21482. }
  21483. function addEle(ele, sqDist) {
  21484. if (ele.isNode()) {
  21485. if (nearNode) {
  21486. return; // can't replace node
  21487. } else {
  21488. nearNode = ele;
  21489. near.push(ele);
  21490. }
  21491. }
  21492. if (ele.isEdge() && (sqDist == null || sqDist < minSqDist)) {
  21493. if (nearEdge) {
  21494. // then replace existing edge
  21495. // can replace only if same z-index
  21496. 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) {
  21497. for (var i = 0; i < near.length; i++) {
  21498. if (near[i].isEdge()) {
  21499. near[i] = ele;
  21500. nearEdge = ele;
  21501. minSqDist = sqDist != null ? sqDist : minSqDist;
  21502. break;
  21503. }
  21504. }
  21505. }
  21506. } else {
  21507. near.push(ele);
  21508. nearEdge = ele;
  21509. minSqDist = sqDist != null ? sqDist : minSqDist;
  21510. }
  21511. }
  21512. }
  21513. function checkNode(node) {
  21514. var width = node.outerWidth() + 2 * nodeThreshold;
  21515. var height = node.outerHeight() + 2 * nodeThreshold;
  21516. var hw = width / 2;
  21517. var hh = height / 2;
  21518. var pos = node.position();
  21519. var cornerRadius = node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue;
  21520. var rs = node._private.rscratch;
  21521. if (pos.x - hw <= x && x <= pos.x + hw // bb check x
  21522. && pos.y - hh <= y && y <= pos.y + hh // bb check y
  21523. ) {
  21524. var shape = r.nodeShapes[self.getNodeShape(node)];
  21525. if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y, cornerRadius, rs)) {
  21526. addEle(node, 0);
  21527. return true;
  21528. }
  21529. }
  21530. }
  21531. function checkEdge(edge) {
  21532. var _p = edge._private;
  21533. var rs = _p.rscratch;
  21534. var styleWidth = edge.pstyle('width').pfValue;
  21535. var scale = edge.pstyle('arrow-scale').value;
  21536. var width = styleWidth / 2 + edgeThreshold; // more like a distance radius from centre
  21537. var widthSq = width * width;
  21538. var width2 = width * 2;
  21539. var src = _p.source;
  21540. var tgt = _p.target;
  21541. var sqDist;
  21542. if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {
  21543. var pts = rs.allpts;
  21544. for (var i = 0; i + 3 < pts.length; i += 2) {
  21545. 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]))) {
  21546. addEle(edge, sqDist);
  21547. return true;
  21548. }
  21549. }
  21550. } else if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
  21551. var pts = rs.allpts;
  21552. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  21553. 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]))) {
  21554. addEle(edge, sqDist);
  21555. return true;
  21556. }
  21557. }
  21558. }
  21559. // if we're close to the edge but didn't hit it, maybe we hit its arrows
  21560. var src = src || _p.source;
  21561. var tgt = tgt || _p.target;
  21562. var arSize = self.getArrowWidth(styleWidth, scale);
  21563. var arrows = [{
  21564. name: 'source',
  21565. x: rs.arrowStartX,
  21566. y: rs.arrowStartY,
  21567. angle: rs.srcArrowAngle
  21568. }, {
  21569. name: 'target',
  21570. x: rs.arrowEndX,
  21571. y: rs.arrowEndY,
  21572. angle: rs.tgtArrowAngle
  21573. }, {
  21574. name: 'mid-source',
  21575. x: rs.midX,
  21576. y: rs.midY,
  21577. angle: rs.midsrcArrowAngle
  21578. }, {
  21579. name: 'mid-target',
  21580. x: rs.midX,
  21581. y: rs.midY,
  21582. angle: rs.midtgtArrowAngle
  21583. }];
  21584. for (var i = 0; i < arrows.length; i++) {
  21585. var ar = arrows[i];
  21586. var shape = r.arrowShapes[edge.pstyle(ar.name + '-arrow-shape').value];
  21587. var edgeWidth = edge.pstyle('width').pfValue;
  21588. if (shape.roughCollide(x, y, arSize, ar.angle, {
  21589. x: ar.x,
  21590. y: ar.y
  21591. }, edgeWidth, edgeThreshold) && shape.collide(x, y, arSize, ar.angle, {
  21592. x: ar.x,
  21593. y: ar.y
  21594. }, edgeWidth, edgeThreshold)) {
  21595. addEle(edge);
  21596. return true;
  21597. }
  21598. }
  21599. // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)
  21600. if (hasCompounds && near.length > 0) {
  21601. checkNode(src);
  21602. checkNode(tgt);
  21603. }
  21604. }
  21605. function preprop(obj, name, pre) {
  21606. return getPrefixedProperty(obj, name, pre);
  21607. }
  21608. function checkLabel(ele, prefix) {
  21609. var _p = ele._private;
  21610. var th = labelThreshold;
  21611. var prefixDash;
  21612. if (prefix) {
  21613. prefixDash = prefix + '-';
  21614. } else {
  21615. prefixDash = '';
  21616. }
  21617. ele.boundingBox();
  21618. var bb = _p.labelBounds[prefix || 'main'];
  21619. var text = ele.pstyle(prefixDash + 'label').value;
  21620. var eventsEnabled = ele.pstyle('text-events').strValue === 'yes';
  21621. if (!eventsEnabled || !text) {
  21622. return;
  21623. }
  21624. var lx = preprop(_p.rscratch, 'labelX', prefix);
  21625. var ly = preprop(_p.rscratch, 'labelY', prefix);
  21626. var theta = preprop(_p.rscratch, 'labelAngle', prefix);
  21627. var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  21628. var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  21629. var lx1 = bb.x1 - th - ox; // (-ox, -oy) as bb already includes margin
  21630. var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)
  21631. var ly1 = bb.y1 - th - oy;
  21632. var ly2 = bb.y2 + th - oy;
  21633. if (theta) {
  21634. var cos = Math.cos(theta);
  21635. var sin = Math.sin(theta);
  21636. var rotate = function rotate(x, y) {
  21637. x = x - lx;
  21638. y = y - ly;
  21639. return {
  21640. x: x * cos - y * sin + lx,
  21641. y: x * sin + y * cos + ly
  21642. };
  21643. };
  21644. var px1y1 = rotate(lx1, ly1);
  21645. var px1y2 = rotate(lx1, ly2);
  21646. var px2y1 = rotate(lx2, ly1);
  21647. var px2y2 = rotate(lx2, ly2);
  21648. var points = [
  21649. // with the margin added after the rotation is applied
  21650. px1y1.x + ox, px1y1.y + oy, px2y1.x + ox, px2y1.y + oy, px2y2.x + ox, px2y2.y + oy, px1y2.x + ox, px1y2.y + oy];
  21651. if (pointInsidePolygonPoints(x, y, points)) {
  21652. addEle(ele);
  21653. return true;
  21654. }
  21655. } else {
  21656. // do a cheaper bb check
  21657. if (inBoundingBox(bb, x, y)) {
  21658. addEle(ele);
  21659. return true;
  21660. }
  21661. }
  21662. }
  21663. for (var i = eles.length - 1; i >= 0; i--) {
  21664. // reverse order for precedence
  21665. var ele = eles[i];
  21666. if (ele.isNode()) {
  21667. checkNode(ele) || checkLabel(ele);
  21668. } else {
  21669. // then edge
  21670. checkEdge(ele) || checkLabel(ele) || checkLabel(ele, 'source') || checkLabel(ele, 'target');
  21671. }
  21672. }
  21673. return near;
  21674. };
  21675. // 'Give me everything from this box'
  21676. BRp$e.getAllInBox = function (x1, y1, x2, y2) {
  21677. var eles = this.getCachedZSortedEles().interactive;
  21678. var zoom = this.cy.zoom();
  21679. var labelThreshold = 2 / zoom;
  21680. var box = [];
  21681. var x1c = Math.min(x1, x2);
  21682. var x2c = Math.max(x1, x2);
  21683. var y1c = Math.min(y1, y2);
  21684. var y2c = Math.max(y1, y2);
  21685. x1 = x1c;
  21686. x2 = x2c;
  21687. y1 = y1c;
  21688. y2 = y2c;
  21689. var boxBb = makeBoundingBox({
  21690. x1: x1,
  21691. y1: y1,
  21692. x2: x2,
  21693. y2: y2
  21694. });
  21695. var selectionBox = [{
  21696. x: boxBb.x1,
  21697. y: boxBb.y1
  21698. }, {
  21699. x: boxBb.x2,
  21700. y: boxBb.y1
  21701. }, {
  21702. x: boxBb.x2,
  21703. y: boxBb.y2
  21704. }, {
  21705. x: boxBb.x1,
  21706. y: boxBb.y2
  21707. }];
  21708. var boxEdges = [[selectionBox[0], selectionBox[1]], [selectionBox[1], selectionBox[2]], [selectionBox[2], selectionBox[3]], [selectionBox[3], selectionBox[0]]];
  21709. function preprop(obj, name, pre) {
  21710. return getPrefixedProperty(obj, name, pre);
  21711. }
  21712. function getRotatedLabelBox(ele, prefix) {
  21713. var _p = ele._private;
  21714. var th = labelThreshold;
  21715. var prefixDash = '';
  21716. ele.boundingBox();
  21717. var bb = _p.labelBounds['main'];
  21718. // If the bounding box is not available, return null.
  21719. // This indicates that the label box cannot be calculated, which is consistent
  21720. // with the expected behavior of this function. Returning null allows the caller
  21721. // to handle the absence of a bounding box explicitly.
  21722. if (!bb) {
  21723. return null;
  21724. }
  21725. var lx = preprop(_p.rscratch, 'labelX', prefix);
  21726. var ly = preprop(_p.rscratch, 'labelY', prefix);
  21727. var theta = preprop(_p.rscratch, 'labelAngle', prefix);
  21728. var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  21729. var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  21730. var lx1 = bb.x1 - th - ox;
  21731. var lx2 = bb.x2 + th - ox;
  21732. var ly1 = bb.y1 - th - oy;
  21733. var ly2 = bb.y2 + th - oy;
  21734. if (theta) {
  21735. var cos = Math.cos(theta);
  21736. var sin = Math.sin(theta);
  21737. var rotate = function rotate(x, y) {
  21738. x = x - lx;
  21739. y = y - ly;
  21740. return {
  21741. x: x * cos - y * sin + lx,
  21742. y: x * sin + y * cos + ly
  21743. };
  21744. };
  21745. return [rotate(lx1, ly1), rotate(lx2, ly1), rotate(lx2, ly2), rotate(lx1, ly2)];
  21746. } else {
  21747. return [{
  21748. x: lx1,
  21749. y: ly1
  21750. }, {
  21751. x: lx2,
  21752. y: ly1
  21753. }, {
  21754. x: lx2,
  21755. y: ly2
  21756. }, {
  21757. x: lx1,
  21758. y: ly2
  21759. }];
  21760. }
  21761. }
  21762. function doLinesIntersect(p1, p2, q1, q2) {
  21763. function ccw(a, b, c) {
  21764. return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
  21765. }
  21766. return ccw(p1, q1, q2) !== ccw(p2, q1, q2) && ccw(p1, p2, q1) !== ccw(p1, p2, q2);
  21767. }
  21768. for (var e = 0; e < eles.length; e++) {
  21769. var ele = eles[e];
  21770. if (ele.isNode()) {
  21771. var node = ele;
  21772. var textEvents = node.pstyle('text-events').strValue === 'yes';
  21773. var nodeBoxSelectMode = node.pstyle('box-selection').strValue;
  21774. var labelBoxSelectEnabled = node.pstyle('box-select-labels').strValue === 'yes';
  21775. if (nodeBoxSelectMode === 'none') {
  21776. continue;
  21777. }
  21778. var includeLabels = (nodeBoxSelectMode === 'overlap' || labelBoxSelectEnabled) && textEvents;
  21779. var nodeBb = node.boundingBox({
  21780. includeNodes: true,
  21781. includeEdges: false,
  21782. includeLabels: includeLabels
  21783. });
  21784. if (nodeBoxSelectMode === 'contain') {
  21785. var selected = false;
  21786. if (labelBoxSelectEnabled && textEvents) {
  21787. var rotatedLabelBox = getRotatedLabelBox(node);
  21788. if (rotatedLabelBox && satPolygonIntersection(rotatedLabelBox, selectionBox)) {
  21789. box.push(node);
  21790. selected = true;
  21791. }
  21792. }
  21793. if (!selected && boundingBoxInBoundingBox(boxBb, nodeBb)) {
  21794. box.push(node);
  21795. }
  21796. } else if (nodeBoxSelectMode === 'overlap') {
  21797. if (boundingBoxesIntersect(boxBb, nodeBb)) {
  21798. var nodeBodyBb = node.boundingBox({
  21799. includeNodes: true,
  21800. includeEdges: true,
  21801. includeLabels: false,
  21802. includeMainLabels: false,
  21803. includeSourceLabels: false,
  21804. includeTargetLabels: false
  21805. });
  21806. var nodeBodyCorners = [{
  21807. x: nodeBodyBb.x1,
  21808. y: nodeBodyBb.y1
  21809. }, {
  21810. x: nodeBodyBb.x2,
  21811. y: nodeBodyBb.y1
  21812. }, {
  21813. x: nodeBodyBb.x2,
  21814. y: nodeBodyBb.y2
  21815. }, {
  21816. x: nodeBodyBb.x1,
  21817. y: nodeBodyBb.y2
  21818. }];
  21819. // if node body intersects, no need to check label
  21820. if (satPolygonIntersection(nodeBodyCorners, selectionBox)) {
  21821. box.push(node);
  21822. } else {
  21823. // only check label if node body didn't intersect
  21824. var _rotatedLabelBox = getRotatedLabelBox(node);
  21825. if (_rotatedLabelBox && satPolygonIntersection(_rotatedLabelBox, selectionBox)) {
  21826. box.push(node);
  21827. }
  21828. }
  21829. }
  21830. }
  21831. } else {
  21832. var edge = ele;
  21833. var _p = edge._private;
  21834. var rs = _p.rscratch;
  21835. var edgeBoxSelectMode = edge.pstyle('box-selection').strValue;
  21836. if (edgeBoxSelectMode === 'none') {
  21837. continue;
  21838. }
  21839. if (edgeBoxSelectMode === 'contain') {
  21840. if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {
  21841. continue;
  21842. }
  21843. if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {
  21844. continue;
  21845. }
  21846. if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound' || rs.edgeType === 'segments' || rs.edgeType === 'haystack') {
  21847. var pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
  21848. var allInside = true;
  21849. for (var i = 0; i < pts.length; i++) {
  21850. if (!pointInBoundingBox(boxBb, pts[i])) {
  21851. allInside = false;
  21852. break;
  21853. }
  21854. }
  21855. if (allInside) {
  21856. box.push(edge);
  21857. }
  21858. } else if (rs.edgeType === 'straight') {
  21859. box.push(edge);
  21860. }
  21861. } else if (edgeBoxSelectMode === 'overlap') {
  21862. var _selected = false;
  21863. // Check: either endpoint inside box
  21864. 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))) {
  21865. box.push(edge);
  21866. _selected = true;
  21867. }
  21868. // Haystack fallback (only check if not already selected)
  21869. else if (!_selected && rs.edgeType === 'haystack') {
  21870. var haystackPts = _p.rstyle.haystackPts;
  21871. for (var _i = 0; _i < haystackPts.length; _i++) {
  21872. if (pointInBoundingBox(boxBb, haystackPts[_i])) {
  21873. box.push(edge);
  21874. _selected = true;
  21875. break;
  21876. }
  21877. }
  21878. }
  21879. // Segment intersection check (only if not already selected)
  21880. if (!_selected) {
  21881. var _pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
  21882. // straight edges
  21883. if ((!_pts || _pts.length < 2) && rs.edgeType === 'straight') {
  21884. if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null) {
  21885. _pts = [{
  21886. x: rs.startX,
  21887. y: rs.startY
  21888. }, {
  21889. x: rs.endX,
  21890. y: rs.endY
  21891. }];
  21892. }
  21893. }
  21894. if (!_pts || _pts.length < 2) continue;
  21895. for (var _i2 = 0; _i2 < _pts.length - 1; _i2++) {
  21896. var segStart = _pts[_i2];
  21897. var segEnd = _pts[_i2 + 1];
  21898. for (var b = 0; b < boxEdges.length; b++) {
  21899. var _boxEdges$b = _slicedToArray(boxEdges[b], 2),
  21900. boxStart = _boxEdges$b[0],
  21901. boxEnd = _boxEdges$b[1];
  21902. if (doLinesIntersect(segStart, segEnd, boxStart, boxEnd)) {
  21903. box.push(edge);
  21904. _selected = true;
  21905. break;
  21906. }
  21907. }
  21908. if (_selected) break;
  21909. }
  21910. }
  21911. }
  21912. }
  21913. }
  21914. return box;
  21915. };
  21916. var BRp$d = {};
  21917. BRp$d.calculateArrowAngles = function (edge) {
  21918. var rs = edge._private.rscratch;
  21919. var isHaystack = rs.edgeType === 'haystack';
  21920. var isBezier = rs.edgeType === 'bezier';
  21921. var isMultibezier = rs.edgeType === 'multibezier';
  21922. var isSegments = rs.edgeType === 'segments';
  21923. var isCompound = rs.edgeType === 'compound';
  21924. var isSelf = rs.edgeType === 'self';
  21925. // Displacement gives direction for arrowhead orientation
  21926. var dispX, dispY;
  21927. var startX, startY, endX, endY, midX, midY;
  21928. if (isHaystack) {
  21929. startX = rs.haystackPts[0];
  21930. startY = rs.haystackPts[1];
  21931. endX = rs.haystackPts[2];
  21932. endY = rs.haystackPts[3];
  21933. } else {
  21934. startX = rs.arrowStartX;
  21935. startY = rs.arrowStartY;
  21936. endX = rs.arrowEndX;
  21937. endY = rs.arrowEndY;
  21938. }
  21939. midX = rs.midX;
  21940. midY = rs.midY;
  21941. // source
  21942. //
  21943. if (isSegments) {
  21944. dispX = startX - rs.segpts[0];
  21945. dispY = startY - rs.segpts[1];
  21946. } else if (isMultibezier || isCompound || isSelf || isBezier) {
  21947. var pts = rs.allpts;
  21948. var bX = qbezierAt(pts[0], pts[2], pts[4], 0.1);
  21949. var bY = qbezierAt(pts[1], pts[3], pts[5], 0.1);
  21950. dispX = startX - bX;
  21951. dispY = startY - bY;
  21952. } else {
  21953. dispX = startX - midX;
  21954. dispY = startY - midY;
  21955. }
  21956. rs.srcArrowAngle = getAngleFromDisp(dispX, dispY);
  21957. // mid target
  21958. //
  21959. var midX = rs.midX;
  21960. var midY = rs.midY;
  21961. if (isHaystack) {
  21962. midX = (startX + endX) / 2;
  21963. midY = (startY + endY) / 2;
  21964. }
  21965. dispX = endX - startX;
  21966. dispY = endY - startY;
  21967. if (isSegments) {
  21968. var pts = rs.allpts;
  21969. if (pts.length / 2 % 2 === 0) {
  21970. var i2 = pts.length / 2;
  21971. var i1 = i2 - 2;
  21972. dispX = pts[i2] - pts[i1];
  21973. dispY = pts[i2 + 1] - pts[i1 + 1];
  21974. } else if (rs.isRound) {
  21975. dispX = rs.midVector[1];
  21976. dispY = -rs.midVector[0];
  21977. } else {
  21978. var i2 = pts.length / 2 - 1;
  21979. var i1 = i2 - 2;
  21980. dispX = pts[i2] - pts[i1];
  21981. dispY = pts[i2 + 1] - pts[i1 + 1];
  21982. }
  21983. } else if (isMultibezier || isCompound || isSelf) {
  21984. var pts = rs.allpts;
  21985. var cpts = rs.ctrlpts;
  21986. var bp0x, bp0y;
  21987. var bp1x, bp1y;
  21988. if (cpts.length / 2 % 2 === 0) {
  21989. var p0 = pts.length / 2 - 1; // startpt
  21990. var ic = p0 + 2;
  21991. var p1 = ic + 2;
  21992. bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0);
  21993. bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0);
  21994. bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0001);
  21995. bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0001);
  21996. } else {
  21997. var ic = pts.length / 2 - 1; // ctrpt
  21998. var p0 = ic - 2; // startpt
  21999. var p1 = ic + 2; // endpt
  22000. bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.4999);
  22001. bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.4999);
  22002. bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.5);
  22003. bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.5);
  22004. }
  22005. dispX = bp1x - bp0x;
  22006. dispY = bp1y - bp0y;
  22007. }
  22008. rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);
  22009. rs.midDispX = dispX;
  22010. rs.midDispY = dispY;
  22011. // mid source
  22012. //
  22013. dispX *= -1;
  22014. dispY *= -1;
  22015. if (isSegments) {
  22016. var pts = rs.allpts;
  22017. if (pts.length / 2 % 2 === 0) ; else if (!rs.isRound) {
  22018. var i2 = pts.length / 2 - 1;
  22019. var i3 = i2 + 2;
  22020. dispX = -(pts[i3] - pts[i2]);
  22021. dispY = -(pts[i3 + 1] - pts[i2 + 1]);
  22022. }
  22023. }
  22024. rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY);
  22025. // target
  22026. //
  22027. if (isSegments) {
  22028. dispX = endX - rs.segpts[rs.segpts.length - 2];
  22029. dispY = endY - rs.segpts[rs.segpts.length - 1];
  22030. } else if (isMultibezier || isCompound || isSelf || isBezier) {
  22031. var pts = rs.allpts;
  22032. var l = pts.length;
  22033. var bX = qbezierAt(pts[l - 6], pts[l - 4], pts[l - 2], 0.9);
  22034. var bY = qbezierAt(pts[l - 5], pts[l - 3], pts[l - 1], 0.9);
  22035. dispX = endX - bX;
  22036. dispY = endY - bY;
  22037. } else {
  22038. dispX = endX - midX;
  22039. dispY = endY - midY;
  22040. }
  22041. rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);
  22042. };
  22043. BRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {
  22044. var cache = this.arrowWidthCache = this.arrowWidthCache || {};
  22045. var cachedVal = cache[edgeWidth + ', ' + scale];
  22046. if (cachedVal) {
  22047. return cachedVal;
  22048. }
  22049. cachedVal = Math.max(Math.pow(edgeWidth * 13.37, 0.9), 29) * scale;
  22050. cache[edgeWidth + ', ' + scale] = cachedVal;
  22051. return cachedVal;
  22052. };
  22053. /**
  22054. * Explained by Blindman67 at https://stackoverflow.com/a/44856925/11028828
  22055. */
  22056. // Declare reused variable to avoid reallocating variables every time the function is called
  22057. var x,
  22058. y,
  22059. v1 = {},
  22060. v2 = {},
  22061. sinA,
  22062. sinA90,
  22063. radDirection,
  22064. drawDirection,
  22065. angle,
  22066. halfAngle,
  22067. cRadius,
  22068. lenOut,
  22069. radius,
  22070. limit;
  22071. var startX, startY, stopX, stopY;
  22072. var lastPoint;
  22073. // convert 2 points into vector form, polar form, and normalised
  22074. var asVec = function asVec(p, pp, v) {
  22075. v.x = pp.x - p.x;
  22076. v.y = pp.y - p.y;
  22077. v.len = Math.sqrt(v.x * v.x + v.y * v.y);
  22078. v.nx = v.x / v.len;
  22079. v.ny = v.y / v.len;
  22080. v.ang = Math.atan2(v.ny, v.nx);
  22081. };
  22082. var invertVec = function invertVec(originalV, invertedV) {
  22083. invertedV.x = originalV.x * -1;
  22084. invertedV.y = originalV.y * -1;
  22085. invertedV.nx = originalV.nx * -1;
  22086. invertedV.ny = originalV.ny * -1;
  22087. invertedV.ang = originalV.ang > 0 ? -(Math.PI - originalV.ang) : Math.PI + originalV.ang;
  22088. };
  22089. var calcCornerArc = function calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius) {
  22090. //-----------------------------------------
  22091. // Part 1
  22092. previousPoint !== lastPoint ? asVec(currentPoint, previousPoint, v1) : invertVec(v2, v1); // Avoid recalculating vec if it is the invert of the last one calculated
  22093. asVec(currentPoint, nextPoint, v2);
  22094. sinA = v1.nx * v2.ny - v1.ny * v2.nx;
  22095. sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;
  22096. angle = Math.asin(Math.max(-1, Math.min(1, sinA)));
  22097. if (Math.abs(angle) < 1e-6) {
  22098. x = currentPoint.x;
  22099. y = currentPoint.y;
  22100. cRadius = radius = 0;
  22101. return;
  22102. }
  22103. //-----------------------------------------
  22104. radDirection = 1;
  22105. drawDirection = false;
  22106. if (sinA90 < 0) {
  22107. if (angle < 0) {
  22108. angle = Math.PI + angle;
  22109. } else {
  22110. angle = Math.PI - angle;
  22111. radDirection = -1;
  22112. drawDirection = true;
  22113. }
  22114. } else {
  22115. if (angle > 0) {
  22116. radDirection = -1;
  22117. drawDirection = true;
  22118. }
  22119. }
  22120. if (currentPoint.radius !== undefined) {
  22121. radius = currentPoint.radius;
  22122. } else {
  22123. radius = radiusMax;
  22124. }
  22125. //-----------------------------------------
  22126. // Part 2
  22127. halfAngle = angle / 2;
  22128. //-----------------------------------------
  22129. limit = Math.min(v1.len / 2, v2.len / 2);
  22130. if (isArcRadius) {
  22131. //-----------------------------------------
  22132. // Part 3
  22133. lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));
  22134. //-----------------------------------------
  22135. // Special part A
  22136. if (lenOut > limit) {
  22137. lenOut = limit;
  22138. cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  22139. } else {
  22140. cRadius = radius;
  22141. }
  22142. } else {
  22143. lenOut = Math.min(limit, radius);
  22144. cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  22145. }
  22146. //-----------------------------------------
  22147. //-----------------------------------------
  22148. // Part 4
  22149. stopX = currentPoint.x + v2.nx * lenOut;
  22150. stopY = currentPoint.y + v2.ny * lenOut;
  22151. //-----------------------------------------
  22152. // Part 5
  22153. x = stopX - v2.ny * cRadius * radDirection;
  22154. y = stopY + v2.nx * cRadius * radDirection;
  22155. //-----------------------------------------
  22156. // Additional Part : calculate start point E
  22157. startX = currentPoint.x + v1.nx * lenOut;
  22158. startY = currentPoint.y + v1.ny * lenOut;
  22159. // Save last point to avoid recalculating vector when not needed
  22160. lastPoint = currentPoint;
  22161. };
  22162. /**
  22163. * Draw corner provided by {@link getRoundCorner}
  22164. *
  22165. * @param ctx :CanvasRenderingContext2D
  22166. * @param roundCorner {{cx:number, cy:number, radius:number, endAngle: number, startAngle: number, counterClockwise: boolean}}
  22167. */
  22168. function drawPreparedRoundCorner(ctx, roundCorner) {
  22169. 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);
  22170. }
  22171. /**
  22172. * Get round corner from a point and its previous and next neighbours in a path
  22173. *
  22174. * @param previousPoint {{x: number, y:number, radius: number?}}
  22175. * @param currentPoint {{x: number, y:number, radius: number?}}
  22176. * @param nextPoint {{x: number, y:number, radius: number?}}
  22177. * @param radiusMax :number
  22178. * @param isArcRadius :boolean
  22179. * @return {{
  22180. * cx:number, cy:number, radius:number,
  22181. * startX:number, startY:number,
  22182. * stopX:number, stopY: number,
  22183. * endAngle: number, startAngle: number, counterClockwise: boolean
  22184. * }}
  22185. */
  22186. function getRoundCorner(previousPoint, currentPoint, nextPoint, radiusMax) {
  22187. var isArcRadius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  22188. if (radiusMax === 0 || currentPoint.radius === 0) return {
  22189. cx: currentPoint.x,
  22190. cy: currentPoint.y,
  22191. radius: 0,
  22192. startX: currentPoint.x,
  22193. startY: currentPoint.y,
  22194. stopX: currentPoint.x,
  22195. stopY: currentPoint.y,
  22196. startAngle: undefined,
  22197. endAngle: undefined,
  22198. counterClockwise: undefined
  22199. };
  22200. calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius);
  22201. return {
  22202. cx: x,
  22203. cy: y,
  22204. radius: cRadius,
  22205. startX: startX,
  22206. startY: startY,
  22207. stopX: stopX,
  22208. stopY: stopY,
  22209. startAngle: v1.ang + Math.PI / 2 * radDirection,
  22210. endAngle: v2.ang - Math.PI / 2 * radDirection,
  22211. counterClockwise: drawDirection
  22212. };
  22213. }
  22214. var AVOID_IMPOSSIBLE_BEZIER_CONSTANT = 0.01;
  22215. var AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L = Math.sqrt(2 * AVOID_IMPOSSIBLE_BEZIER_CONSTANT);
  22216. var BRp$c = {};
  22217. BRp$c.findMidptPtsEtc = function (edge, pairInfo) {
  22218. var posPts = pairInfo.posPts,
  22219. intersectionPts = pairInfo.intersectionPts,
  22220. vectorNormInverse = pairInfo.vectorNormInverse;
  22221. var midptPts;
  22222. // n.b. assumes all edges in bezier bundle have same endpoints specified
  22223. var srcManEndpt = edge.pstyle('source-endpoint');
  22224. var tgtManEndpt = edge.pstyle('target-endpoint');
  22225. var haveManualEndPts = srcManEndpt.units != null && tgtManEndpt.units != null;
  22226. var recalcVectorNormInverse = function recalcVectorNormInverse(x1, y1, x2, y2) {
  22227. var dy = y2 - y1;
  22228. var dx = x2 - x1;
  22229. var l = Math.sqrt(dx * dx + dy * dy);
  22230. return {
  22231. x: -dy / l,
  22232. y: dx / l
  22233. };
  22234. };
  22235. var edgeDistances = edge.pstyle('edge-distances').value;
  22236. switch (edgeDistances) {
  22237. case 'node-position':
  22238. midptPts = posPts;
  22239. break;
  22240. case 'intersection':
  22241. midptPts = intersectionPts;
  22242. break;
  22243. case 'endpoints':
  22244. {
  22245. if (haveManualEndPts) {
  22246. var _this$manualEndptToPx = this.manualEndptToPx(edge.source()[0], srcManEndpt),
  22247. _this$manualEndptToPx2 = _slicedToArray(_this$manualEndptToPx, 2),
  22248. x1 = _this$manualEndptToPx2[0],
  22249. y1 = _this$manualEndptToPx2[1];
  22250. var _this$manualEndptToPx3 = this.manualEndptToPx(edge.target()[0], tgtManEndpt),
  22251. _this$manualEndptToPx4 = _slicedToArray(_this$manualEndptToPx3, 2),
  22252. x2 = _this$manualEndptToPx4[0],
  22253. y2 = _this$manualEndptToPx4[1];
  22254. var endPts = {
  22255. x1: x1,
  22256. y1: y1,
  22257. x2: x2,
  22258. y2: y2
  22259. };
  22260. vectorNormInverse = recalcVectorNormInverse(x1, y1, x2, y2);
  22261. midptPts = endPts;
  22262. } else {
  22263. 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)."));
  22264. midptPts = intersectionPts; // back to default
  22265. }
  22266. break;
  22267. }
  22268. }
  22269. return {
  22270. midptPts: midptPts,
  22271. vectorNormInverse: vectorNormInverse
  22272. };
  22273. };
  22274. BRp$c.findHaystackPoints = function (edges) {
  22275. for (var i = 0; i < edges.length; i++) {
  22276. var edge = edges[i];
  22277. var _p = edge._private;
  22278. var rs = _p.rscratch;
  22279. if (!rs.haystack) {
  22280. var angle = Math.random() * 2 * Math.PI;
  22281. rs.source = {
  22282. x: Math.cos(angle),
  22283. y: Math.sin(angle)
  22284. };
  22285. angle = Math.random() * 2 * Math.PI;
  22286. rs.target = {
  22287. x: Math.cos(angle),
  22288. y: Math.sin(angle)
  22289. };
  22290. }
  22291. var src = _p.source;
  22292. var tgt = _p.target;
  22293. var srcPos = src.position();
  22294. var tgtPos = tgt.position();
  22295. var srcW = src.width();
  22296. var tgtW = tgt.width();
  22297. var srcH = src.height();
  22298. var tgtH = tgt.height();
  22299. var radius = edge.pstyle('haystack-radius').value;
  22300. var halfRadius = radius / 2; // b/c have to half width/height
  22301. 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];
  22302. rs.midX = (rs.allpts[0] + rs.allpts[2]) / 2;
  22303. rs.midY = (rs.allpts[1] + rs.allpts[3]) / 2;
  22304. // always override as haystack in case set to different type previously
  22305. rs.edgeType = 'haystack';
  22306. rs.haystack = true;
  22307. this.storeEdgeProjections(edge);
  22308. this.calculateArrowAngles(edge);
  22309. this.recalculateEdgeLabelProjections(edge);
  22310. this.calculateLabelAngles(edge);
  22311. }
  22312. };
  22313. BRp$c.findSegmentsPoints = function (edge, pairInfo) {
  22314. // Segments (multiple straight lines)
  22315. var rs = edge._private.rscratch;
  22316. var segmentWs = edge.pstyle('segment-weights');
  22317. var segmentDs = edge.pstyle('segment-distances');
  22318. var segmentRs = edge.pstyle('segment-radii');
  22319. var segmentTs = edge.pstyle('radius-type');
  22320. var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);
  22321. var lastRadius = segmentRs.pfValue[segmentRs.pfValue.length - 1];
  22322. var lastRadiusType = segmentTs.pfValue[segmentTs.pfValue.length - 1];
  22323. rs.edgeType = 'segments';
  22324. rs.segpts = [];
  22325. rs.radii = [];
  22326. rs.isArcRadius = [];
  22327. for (var s = 0; s < segmentsN; s++) {
  22328. var w = segmentWs.pfValue[s];
  22329. var d = segmentDs.pfValue[s];
  22330. var w1 = 1 - w;
  22331. var w2 = w;
  22332. var _this$findMidptPtsEtc = this.findMidptPtsEtc(edge, pairInfo),
  22333. midptPts = _this$findMidptPtsEtc.midptPts,
  22334. vectorNormInverse = _this$findMidptPtsEtc.vectorNormInverse;
  22335. var adjustedMidpt = {
  22336. x: midptPts.x1 * w1 + midptPts.x2 * w2,
  22337. y: midptPts.y1 * w1 + midptPts.y2 * w2
  22338. };
  22339. rs.segpts.push(adjustedMidpt.x + vectorNormInverse.x * d, adjustedMidpt.y + vectorNormInverse.y * d);
  22340. rs.radii.push(segmentRs.pfValue[s] !== undefined ? segmentRs.pfValue[s] : lastRadius);
  22341. rs.isArcRadius.push((segmentTs.pfValue[s] !== undefined ? segmentTs.pfValue[s] : lastRadiusType) === 'arc-radius');
  22342. }
  22343. };
  22344. BRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  22345. // Self-edge
  22346. var rs = edge._private.rscratch;
  22347. var dirCounts = pairInfo.dirCounts,
  22348. srcPos = pairInfo.srcPos;
  22349. var ctrlptDists = edge.pstyle('control-point-distances');
  22350. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22351. var loopDir = edge.pstyle('loop-direction').pfValue;
  22352. var loopSwp = edge.pstyle('loop-sweep').pfValue;
  22353. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22354. rs.edgeType = 'self';
  22355. var j = i;
  22356. var loopDist = stepSize;
  22357. if (edgeIsUnbundled) {
  22358. j = 0;
  22359. loopDist = ctrlptDist;
  22360. }
  22361. var loopAngle = loopDir - Math.PI / 2;
  22362. var outAngle = loopAngle - loopSwp / 2;
  22363. var inAngle = loopAngle + loopSwp / 2;
  22364. // increase by step size for overlapping loops, keyed on direction and sweep values
  22365. var dc = String(loopDir + '_' + loopSwp);
  22366. j = dirCounts[dc] === undefined ? dirCounts[dc] = 0 : ++dirCounts[dc];
  22367. 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)];
  22368. };
  22369. BRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  22370. // Compound edge
  22371. var rs = edge._private.rscratch;
  22372. rs.edgeType = 'compound';
  22373. var srcPos = pairInfo.srcPos,
  22374. tgtPos = pairInfo.tgtPos,
  22375. srcW = pairInfo.srcW,
  22376. srcH = pairInfo.srcH,
  22377. tgtW = pairInfo.tgtW,
  22378. tgtH = pairInfo.tgtH;
  22379. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22380. var ctrlptDists = edge.pstyle('control-point-distances');
  22381. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22382. var j = i;
  22383. var loopDist = stepSize;
  22384. if (edgeIsUnbundled) {
  22385. j = 0;
  22386. loopDist = ctrlptDist;
  22387. }
  22388. var loopW = 50;
  22389. var loopaPos = {
  22390. x: srcPos.x - srcW / 2,
  22391. y: srcPos.y - srcH / 2
  22392. };
  22393. var loopbPos = {
  22394. x: tgtPos.x - tgtW / 2,
  22395. y: tgtPos.y - tgtH / 2
  22396. };
  22397. var loopPos = {
  22398. x: Math.min(loopaPos.x, loopbPos.x),
  22399. y: Math.min(loopaPos.y, loopbPos.y)
  22400. };
  22401. // avoids cases with impossible beziers
  22402. var minCompoundStretch = 0.5;
  22403. var compoundStretchA = Math.max(minCompoundStretch, Math.log(srcW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22404. var compoundStretchB = Math.max(minCompoundStretch, Math.log(tgtW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22405. 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];
  22406. };
  22407. BRp$c.findStraightEdgePoints = function (edge) {
  22408. // Straight edge within bundle
  22409. edge._private.rscratch.edgeType = 'straight';
  22410. };
  22411. BRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {
  22412. var rs = edge._private.rscratch;
  22413. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22414. var ctrlptDists = edge.pstyle('control-point-distances');
  22415. var ctrlptWs = edge.pstyle('control-point-weights');
  22416. var bezierN = ctrlptDists && ctrlptWs ? Math.min(ctrlptDists.value.length, ctrlptWs.value.length) : 1;
  22417. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22418. var ctrlptWeight = ctrlptWs.value[0];
  22419. // (Multi)bezier
  22420. var multi = edgeIsUnbundled;
  22421. rs.edgeType = multi ? 'multibezier' : 'bezier';
  22422. rs.ctrlpts = [];
  22423. for (var b = 0; b < bezierN; b++) {
  22424. var normctrlptDist = (0.5 - pairInfo.eles.length / 2 + i) * stepSize * (edgeIsSwapped ? -1 : 1);
  22425. var manctrlptDist = undefined;
  22426. var sign = signum(normctrlptDist);
  22427. if (multi) {
  22428. ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size
  22429. ctrlptWeight = ctrlptWs.value[b];
  22430. }
  22431. if (edgeIsUnbundled) {
  22432. // multi or single unbundled
  22433. manctrlptDist = ctrlptDist;
  22434. } else {
  22435. manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;
  22436. }
  22437. var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;
  22438. var w1 = 1 - ctrlptWeight;
  22439. var w2 = ctrlptWeight;
  22440. var _this$findMidptPtsEtc2 = this.findMidptPtsEtc(edge, pairInfo),
  22441. midptPts = _this$findMidptPtsEtc2.midptPts,
  22442. vectorNormInverse = _this$findMidptPtsEtc2.vectorNormInverse;
  22443. var adjustedMidpt = {
  22444. x: midptPts.x1 * w1 + midptPts.x2 * w2,
  22445. y: midptPts.y1 * w1 + midptPts.y2 * w2
  22446. };
  22447. rs.ctrlpts.push(adjustedMidpt.x + vectorNormInverse.x * distanceFromMidpoint, adjustedMidpt.y + vectorNormInverse.y * distanceFromMidpoint);
  22448. }
  22449. };
  22450. BRp$c.findTaxiPoints = function (edge, pairInfo) {
  22451. // Taxicab geometry with two turns maximum
  22452. var rs = edge._private.rscratch;
  22453. rs.edgeType = 'segments';
  22454. var VERTICAL = 'vertical';
  22455. var HORIZONTAL = 'horizontal';
  22456. var LEFTWARD = 'leftward';
  22457. var RIGHTWARD = 'rightward';
  22458. var DOWNWARD = 'downward';
  22459. var UPWARD = 'upward';
  22460. var AUTO = 'auto';
  22461. var posPts = pairInfo.posPts,
  22462. srcW = pairInfo.srcW,
  22463. srcH = pairInfo.srcH,
  22464. tgtW = pairInfo.tgtW,
  22465. tgtH = pairInfo.tgtH;
  22466. var edgeDistances = edge.pstyle('edge-distances').value;
  22467. var dIncludesNodeBody = edgeDistances !== 'node-position';
  22468. var taxiDir = edge.pstyle('taxi-direction').value;
  22469. var rawTaxiDir = taxiDir; // unprocessed value
  22470. var taxiTurn = edge.pstyle('taxi-turn');
  22471. var turnIsPercent = taxiTurn.units === '%';
  22472. var taxiTurnPfVal = taxiTurn.pfValue;
  22473. var turnIsNegative = taxiTurnPfVal < 0; // i.e. from target side
  22474. var minD = edge.pstyle('taxi-turn-min-distance').pfValue;
  22475. var dw = dIncludesNodeBody ? (srcW + tgtW) / 2 : 0;
  22476. var dh = dIncludesNodeBody ? (srcH + tgtH) / 2 : 0;
  22477. var pdx = posPts.x2 - posPts.x1;
  22478. var pdy = posPts.y2 - posPts.y1;
  22479. // take away the effective w/h from the magnitude of the delta value
  22480. var subDWH = function subDWH(dxy, dwh) {
  22481. if (dxy > 0) {
  22482. return Math.max(dxy - dwh, 0);
  22483. } else {
  22484. return Math.min(dxy + dwh, 0);
  22485. }
  22486. };
  22487. var dx = subDWH(pdx, dw);
  22488. var dy = subDWH(pdy, dh);
  22489. var isExplicitDir = false;
  22490. if (rawTaxiDir === AUTO) {
  22491. taxiDir = Math.abs(dx) > Math.abs(dy) ? HORIZONTAL : VERTICAL;
  22492. } else if (rawTaxiDir === UPWARD || rawTaxiDir === DOWNWARD) {
  22493. taxiDir = VERTICAL;
  22494. isExplicitDir = true;
  22495. } else if (rawTaxiDir === LEFTWARD || rawTaxiDir === RIGHTWARD) {
  22496. taxiDir = HORIZONTAL;
  22497. isExplicitDir = true;
  22498. }
  22499. var isVert = taxiDir === VERTICAL;
  22500. var l = isVert ? dy : dx;
  22501. var pl = isVert ? pdy : pdx;
  22502. var sgnL = signum(pl);
  22503. var forcedDir = false;
  22504. if (!(isExplicitDir && (turnIsPercent || turnIsNegative)) // forcing in this case would cause weird growing in the opposite direction
  22505. && (rawTaxiDir === DOWNWARD && pl < 0 || rawTaxiDir === UPWARD && pl > 0 || rawTaxiDir === LEFTWARD && pl > 0 || rawTaxiDir === RIGHTWARD && pl < 0)) {
  22506. sgnL *= -1;
  22507. l = sgnL * Math.abs(l);
  22508. forcedDir = true;
  22509. }
  22510. var d;
  22511. if (turnIsPercent) {
  22512. var p = taxiTurnPfVal < 0 ? 1 + taxiTurnPfVal : taxiTurnPfVal;
  22513. d = p * l;
  22514. } else {
  22515. var k = taxiTurnPfVal < 0 ? l : 0;
  22516. d = k + taxiTurnPfVal * sgnL;
  22517. }
  22518. var getIsTooClose = function getIsTooClose(d) {
  22519. return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);
  22520. };
  22521. var isTooCloseSrc = getIsTooClose(d);
  22522. var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));
  22523. var isTooClose = isTooCloseSrc || isTooCloseTgt;
  22524. if (isTooClose && !forcedDir) {
  22525. // non-ideal routing
  22526. if (isVert) {
  22527. // vertical fallbacks
  22528. var lShapeInsideSrc = Math.abs(pl) <= srcH / 2;
  22529. var lShapeInsideTgt = Math.abs(pdx) <= tgtW / 2;
  22530. if (lShapeInsideSrc) {
  22531. // horizontal Z-shape (direction not respected)
  22532. var x = (posPts.x1 + posPts.x2) / 2;
  22533. var y1 = posPts.y1,
  22534. y2 = posPts.y2;
  22535. rs.segpts = [x, y1, x, y2];
  22536. } else if (lShapeInsideTgt) {
  22537. // vertical Z-shape (distance not respected)
  22538. var y = (posPts.y1 + posPts.y2) / 2;
  22539. var x1 = posPts.x1,
  22540. x2 = posPts.x2;
  22541. rs.segpts = [x1, y, x2, y];
  22542. } else {
  22543. // L-shape fallback (turn distance not respected, but works well with tree siblings)
  22544. rs.segpts = [posPts.x1, posPts.y2];
  22545. }
  22546. } else {
  22547. // horizontal fallbacks
  22548. var _lShapeInsideSrc = Math.abs(pl) <= srcW / 2;
  22549. var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;
  22550. if (_lShapeInsideSrc) {
  22551. // vertical Z-shape (direction not respected)
  22552. var _y = (posPts.y1 + posPts.y2) / 2;
  22553. var _x = posPts.x1,
  22554. _x2 = posPts.x2;
  22555. rs.segpts = [_x, _y, _x2, _y];
  22556. } else if (_lShapeInsideTgt) {
  22557. // horizontal Z-shape (turn distance not respected)
  22558. var _x3 = (posPts.x1 + posPts.x2) / 2;
  22559. var _y2 = posPts.y1,
  22560. _y3 = posPts.y2;
  22561. rs.segpts = [_x3, _y2, _x3, _y3];
  22562. } else {
  22563. // L-shape (turn distance not respected, but works well for tree siblings)
  22564. rs.segpts = [posPts.x2, posPts.y1];
  22565. }
  22566. }
  22567. } else {
  22568. // ideal routing
  22569. if (isVert) {
  22570. var _y4 = posPts.y1 + d + (dIncludesNodeBody ? srcH / 2 * sgnL : 0);
  22571. var _x4 = posPts.x1,
  22572. _x5 = posPts.x2;
  22573. rs.segpts = [_x4, _y4, _x5, _y4];
  22574. } else {
  22575. // horizontal
  22576. var _x6 = posPts.x1 + d + (dIncludesNodeBody ? srcW / 2 * sgnL : 0);
  22577. var _y5 = posPts.y1,
  22578. _y6 = posPts.y2;
  22579. rs.segpts = [_x6, _y5, _x6, _y6];
  22580. }
  22581. }
  22582. if (rs.isRound) {
  22583. var radius = edge.pstyle('taxi-radius').value;
  22584. var isArcRadius = edge.pstyle('radius-type').value[0] === 'arc-radius';
  22585. rs.radii = new Array(rs.segpts.length / 2).fill(radius);
  22586. rs.isArcRadius = new Array(rs.segpts.length / 2).fill(isArcRadius);
  22587. }
  22588. };
  22589. BRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {
  22590. var rs = edge._private.rscratch;
  22591. // can only correct beziers for now...
  22592. if (rs.edgeType === 'bezier') {
  22593. var srcPos = pairInfo.srcPos,
  22594. tgtPos = pairInfo.tgtPos,
  22595. srcW = pairInfo.srcW,
  22596. srcH = pairInfo.srcH,
  22597. tgtW = pairInfo.tgtW,
  22598. tgtH = pairInfo.tgtH,
  22599. srcShape = pairInfo.srcShape,
  22600. tgtShape = pairInfo.tgtShape,
  22601. srcCornerRadius = pairInfo.srcCornerRadius,
  22602. tgtCornerRadius = pairInfo.tgtCornerRadius,
  22603. srcRs = pairInfo.srcRs,
  22604. tgtRs = pairInfo.tgtRs;
  22605. var badStart = !number$1(rs.startX) || !number$1(rs.startY);
  22606. var badAStart = !number$1(rs.arrowStartX) || !number$1(rs.arrowStartY);
  22607. var badEnd = !number$1(rs.endX) || !number$1(rs.endY);
  22608. var badAEnd = !number$1(rs.arrowEndX) || !number$1(rs.arrowEndY);
  22609. var minCpADistFactor = 3;
  22610. var arrowW = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
  22611. var minCpADist = minCpADistFactor * arrowW;
  22612. var startACpDist = dist({
  22613. x: rs.ctrlpts[0],
  22614. y: rs.ctrlpts[1]
  22615. }, {
  22616. x: rs.startX,
  22617. y: rs.startY
  22618. });
  22619. var closeStartACp = startACpDist < minCpADist;
  22620. var endACpDist = dist({
  22621. x: rs.ctrlpts[0],
  22622. y: rs.ctrlpts[1]
  22623. }, {
  22624. x: rs.endX,
  22625. y: rs.endY
  22626. });
  22627. var closeEndACp = endACpDist < minCpADist;
  22628. var overlapping = false;
  22629. if (badStart || badAStart || closeStartACp) {
  22630. overlapping = true;
  22631. // project control point along line from src centre to outside the src shape
  22632. // (otherwise intersection will yield nothing)
  22633. var cpD = {
  22634. // delta
  22635. x: rs.ctrlpts[0] - srcPos.x,
  22636. y: rs.ctrlpts[1] - srcPos.y
  22637. };
  22638. var cpL = Math.sqrt(cpD.x * cpD.x + cpD.y * cpD.y); // length of line
  22639. var cpM = {
  22640. // normalised delta
  22641. x: cpD.x / cpL,
  22642. y: cpD.y / cpL
  22643. };
  22644. var radius = Math.max(srcW, srcH);
  22645. var cpProj = {
  22646. // *2 radius guarantees outside shape
  22647. x: rs.ctrlpts[0] + cpM.x * 2 * radius,
  22648. y: rs.ctrlpts[1] + cpM.y * 2 * radius
  22649. };
  22650. var srcCtrlPtIntn = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, cpProj.x, cpProj.y, 0, srcCornerRadius, srcRs);
  22651. if (closeStartACp) {
  22652. rs.ctrlpts[0] = rs.ctrlpts[0] + cpM.x * (minCpADist - startACpDist);
  22653. rs.ctrlpts[1] = rs.ctrlpts[1] + cpM.y * (minCpADist - startACpDist);
  22654. } else {
  22655. rs.ctrlpts[0] = srcCtrlPtIntn[0] + cpM.x * minCpADist;
  22656. rs.ctrlpts[1] = srcCtrlPtIntn[1] + cpM.y * minCpADist;
  22657. }
  22658. }
  22659. if (badEnd || badAEnd || closeEndACp) {
  22660. overlapping = true;
  22661. // project control point along line from tgt centre to outside the tgt shape
  22662. // (otherwise intersection will yield nothing)
  22663. var _cpD = {
  22664. // delta
  22665. x: rs.ctrlpts[0] - tgtPos.x,
  22666. y: rs.ctrlpts[1] - tgtPos.y
  22667. };
  22668. var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line
  22669. var _cpM = {
  22670. // normalised delta
  22671. x: _cpD.x / _cpL,
  22672. y: _cpD.y / _cpL
  22673. };
  22674. var _radius = Math.max(srcW, srcH);
  22675. var _cpProj = {
  22676. // *2 radius guarantees outside shape
  22677. x: rs.ctrlpts[0] + _cpM.x * 2 * _radius,
  22678. y: rs.ctrlpts[1] + _cpM.y * 2 * _radius
  22679. };
  22680. var tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0, tgtCornerRadius, tgtRs);
  22681. if (closeEndACp) {
  22682. rs.ctrlpts[0] = rs.ctrlpts[0] + _cpM.x * (minCpADist - endACpDist);
  22683. rs.ctrlpts[1] = rs.ctrlpts[1] + _cpM.y * (minCpADist - endACpDist);
  22684. } else {
  22685. rs.ctrlpts[0] = tgtCtrlPtIntn[0] + _cpM.x * minCpADist;
  22686. rs.ctrlpts[1] = tgtCtrlPtIntn[1] + _cpM.y * minCpADist;
  22687. }
  22688. }
  22689. if (overlapping) {
  22690. // recalc endpts
  22691. this.findEndpoints(edge);
  22692. }
  22693. }
  22694. };
  22695. BRp$c.storeAllpts = function (edge) {
  22696. var rs = edge._private.rscratch;
  22697. if (rs.edgeType === 'multibezier' || rs.edgeType === 'bezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
  22698. rs.allpts = [];
  22699. rs.allpts.push(rs.startX, rs.startY);
  22700. for (var b = 0; b + 1 < rs.ctrlpts.length; b += 2) {
  22701. // ctrl pt itself
  22702. rs.allpts.push(rs.ctrlpts[b], rs.ctrlpts[b + 1]);
  22703. // the midpt between ctrlpts as intermediate destination pts
  22704. if (b + 3 < rs.ctrlpts.length) {
  22705. rs.allpts.push((rs.ctrlpts[b] + rs.ctrlpts[b + 2]) / 2, (rs.ctrlpts[b + 1] + rs.ctrlpts[b + 3]) / 2);
  22706. }
  22707. }
  22708. rs.allpts.push(rs.endX, rs.endY);
  22709. var m, mt;
  22710. if (rs.ctrlpts.length / 2 % 2 === 0) {
  22711. m = rs.allpts.length / 2 - 1;
  22712. rs.midX = rs.allpts[m];
  22713. rs.midY = rs.allpts[m + 1];
  22714. } else {
  22715. m = rs.allpts.length / 2 - 3;
  22716. mt = 0.5;
  22717. rs.midX = qbezierAt(rs.allpts[m], rs.allpts[m + 2], rs.allpts[m + 4], mt);
  22718. rs.midY = qbezierAt(rs.allpts[m + 1], rs.allpts[m + 3], rs.allpts[m + 5], mt);
  22719. }
  22720. } else if (rs.edgeType === 'straight') {
  22721. // need to calc these after endpts
  22722. rs.allpts = [rs.startX, rs.startY, rs.endX, rs.endY];
  22723. // default midpt for labels etc
  22724. rs.midX = (rs.startX + rs.endX + rs.arrowStartX + rs.arrowEndX) / 4;
  22725. rs.midY = (rs.startY + rs.endY + rs.arrowStartY + rs.arrowEndY) / 4;
  22726. } else if (rs.edgeType === 'segments') {
  22727. rs.allpts = [];
  22728. rs.allpts.push(rs.startX, rs.startY);
  22729. rs.allpts.push.apply(rs.allpts, rs.segpts);
  22730. rs.allpts.push(rs.endX, rs.endY);
  22731. if (rs.isRound) {
  22732. rs.roundCorners = [];
  22733. for (var i = 2; i + 3 < rs.allpts.length; i += 2) {
  22734. var radius = rs.radii[i / 2 - 1];
  22735. var isArcRadius = rs.isArcRadius[i / 2 - 1];
  22736. rs.roundCorners.push(getRoundCorner({
  22737. x: rs.allpts[i - 2],
  22738. y: rs.allpts[i - 1]
  22739. }, {
  22740. x: rs.allpts[i],
  22741. y: rs.allpts[i + 1],
  22742. radius: radius
  22743. }, {
  22744. x: rs.allpts[i + 2],
  22745. y: rs.allpts[i + 3]
  22746. }, radius, isArcRadius));
  22747. }
  22748. }
  22749. if (rs.segpts.length % 4 === 0) {
  22750. var i2 = rs.segpts.length / 2;
  22751. var i1 = i2 - 2;
  22752. rs.midX = (rs.segpts[i1] + rs.segpts[i2]) / 2;
  22753. rs.midY = (rs.segpts[i1 + 1] + rs.segpts[i2 + 1]) / 2;
  22754. } else {
  22755. var _i = rs.segpts.length / 2 - 1;
  22756. if (!rs.isRound) {
  22757. rs.midX = rs.segpts[_i];
  22758. rs.midY = rs.segpts[_i + 1];
  22759. } else {
  22760. var point = {
  22761. x: rs.segpts[_i],
  22762. y: rs.segpts[_i + 1]
  22763. };
  22764. var corner = rs.roundCorners[_i / 2];
  22765. if (corner.radius === 0) {
  22766. // On collinear points
  22767. var nextPoint = {
  22768. x: rs.segpts[_i + 2],
  22769. y: rs.segpts[_i + 3]
  22770. };
  22771. rs.midX = point.x;
  22772. rs.midY = point.y;
  22773. rs.midVector = [point.y - nextPoint.y, nextPoint.x - point.x];
  22774. } else {
  22775. // On rounded points
  22776. var v = [point.x - corner.cx, point.y - corner.cy];
  22777. var factor = corner.radius / Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));
  22778. v = v.map(function (c) {
  22779. return c * factor;
  22780. });
  22781. rs.midX = corner.cx + v[0];
  22782. rs.midY = corner.cy + v[1];
  22783. rs.midVector = v;
  22784. }
  22785. }
  22786. }
  22787. }
  22788. };
  22789. BRp$c.checkForInvalidEdgeWarning = function (edge) {
  22790. var rs = edge[0]._private.rscratch;
  22791. if (rs.nodesOverlap || number$1(rs.startX) && number$1(rs.startY) && number$1(rs.endX) && number$1(rs.endY)) {
  22792. rs.loggedErr = false;
  22793. } else {
  22794. if (!rs.loggedErr) {
  22795. rs.loggedErr = true;
  22796. 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.');
  22797. }
  22798. }
  22799. };
  22800. BRp$c.findEdgeControlPoints = function (edges) {
  22801. var _this = this;
  22802. if (!edges || edges.length === 0) {
  22803. return;
  22804. }
  22805. var r = this;
  22806. var cy = r.cy;
  22807. var hasCompounds = cy.hasCompoundNodes();
  22808. var hashTable = new Map$1();
  22809. var getKey = function getKey(pairId, edgeIsUnbundled) {
  22810. return [].concat(_toConsumableArray(pairId), [edgeIsUnbundled ? 1 : 0]).join('-');
  22811. };
  22812. var pairIds = [];
  22813. var haystackEdges = [];
  22814. // create a table of edge (src, tgt) => list of edges between them
  22815. for (var i = 0; i < edges.length; i++) {
  22816. var edge = edges[i];
  22817. var _p = edge._private;
  22818. var curveStyle = edge.pstyle('curve-style').value;
  22819. // ignore edges who are not to be displayed
  22820. // they shouldn't take up space
  22821. if (edge.removed() || !edge.takesUpSpace()) {
  22822. continue;
  22823. }
  22824. if (curveStyle === 'haystack') {
  22825. haystackEdges.push(edge);
  22826. continue;
  22827. }
  22828. var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || curveStyle === 'straight' || curveStyle === 'straight-triangle' || endsWith(curveStyle, 'taxi');
  22829. var edgeIsBezier = curveStyle === 'unbundled-bezier' || curveStyle === 'bezier';
  22830. var src = _p.source;
  22831. var tgt = _p.target;
  22832. var srcIndex = src.poolIndex();
  22833. var tgtIndex = tgt.poolIndex();
  22834. var pairId = [srcIndex, tgtIndex].sort();
  22835. var key = getKey(pairId, edgeIsUnbundled);
  22836. var tableEntry = hashTable.get(key);
  22837. if (tableEntry == null) {
  22838. tableEntry = {
  22839. eles: []
  22840. };
  22841. pairIds.push({
  22842. pairId: pairId,
  22843. edgeIsUnbundled: edgeIsUnbundled
  22844. });
  22845. hashTable.set(key, tableEntry);
  22846. }
  22847. tableEntry.eles.push(edge);
  22848. if (edgeIsUnbundled) {
  22849. tableEntry.hasUnbundled = true;
  22850. }
  22851. if (edgeIsBezier) {
  22852. tableEntry.hasBezier = true;
  22853. }
  22854. }
  22855. // for each pair (src, tgt), create the ctrl pts
  22856. // Nested for loop is OK; total number of iterations for both loops = edgeCount
  22857. var _loop = function _loop() {
  22858. var _pairIds$p = pairIds[p],
  22859. pairId = _pairIds$p.pairId,
  22860. edgeIsUnbundled = _pairIds$p.edgeIsUnbundled;
  22861. var key = getKey(pairId, edgeIsUnbundled);
  22862. var pairInfo = hashTable.get(key);
  22863. var swappedpairInfo;
  22864. if (!pairInfo.hasUnbundled) {
  22865. var pllEdges = pairInfo.eles[0].parallelEdges().filter(function (e) {
  22866. return e.isBundledBezier();
  22867. });
  22868. clearArray(pairInfo.eles);
  22869. pllEdges.forEach(function (edge) {
  22870. return pairInfo.eles.push(edge);
  22871. });
  22872. // for each pair id, the edges should be sorted by index
  22873. pairInfo.eles.sort(function (edge1, edge2) {
  22874. return edge1.poolIndex() - edge2.poolIndex();
  22875. });
  22876. }
  22877. var firstEdge = pairInfo.eles[0];
  22878. var src = firstEdge.source();
  22879. var tgt = firstEdge.target();
  22880. // make sure src/tgt distinction is consistent w.r.t. pairId
  22881. if (src.poolIndex() > tgt.poolIndex()) {
  22882. var temp = src;
  22883. src = tgt;
  22884. tgt = temp;
  22885. }
  22886. var srcPos = pairInfo.srcPos = src.position();
  22887. var tgtPos = pairInfo.tgtPos = tgt.position();
  22888. var srcW = pairInfo.srcW = src.outerWidth();
  22889. var srcH = pairInfo.srcH = src.outerHeight();
  22890. var tgtW = pairInfo.tgtW = tgt.outerWidth();
  22891. var tgtH = pairInfo.tgtH = tgt.outerHeight();
  22892. var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];
  22893. var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];
  22894. var srcCornerRadius = pairInfo.srcCornerRadius = src.pstyle('corner-radius').value === 'auto' ? 'auto' : src.pstyle('corner-radius').pfValue;
  22895. var tgtCornerRadius = pairInfo.tgtCornerRadius = tgt.pstyle('corner-radius').value === 'auto' ? 'auto' : tgt.pstyle('corner-radius').pfValue;
  22896. var tgtRs = pairInfo.tgtRs = tgt._private.rscratch;
  22897. var srcRs = pairInfo.srcRs = src._private.rscratch;
  22898. pairInfo.dirCounts = {
  22899. 'north': 0,
  22900. 'west': 0,
  22901. 'south': 0,
  22902. 'east': 0,
  22903. 'northwest': 0,
  22904. 'southwest': 0,
  22905. 'northeast': 0,
  22906. 'southeast': 0
  22907. };
  22908. for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {
  22909. var _edge = pairInfo.eles[_i2];
  22910. var rs = _edge[0]._private.rscratch;
  22911. var _curveStyle = _edge.pstyle('curve-style').value;
  22912. var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || endsWith(_curveStyle, 'segments') || endsWith(_curveStyle, 'taxi');
  22913. // whether the normalised pair order is the reverse of the edge's src-tgt order
  22914. var edgeIsSwapped = !src.same(_edge.source());
  22915. if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {
  22916. pairInfo.calculatedIntersection = true;
  22917. // pt outside src shape to calc distance/displacement from src to tgt
  22918. var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0, srcCornerRadius, srcRs);
  22919. var srcIntn = pairInfo.srcIntn = srcOutside;
  22920. // pt outside tgt shape to calc distance/displacement from src to tgt
  22921. var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0, tgtCornerRadius, tgtRs);
  22922. var tgtIntn = pairInfo.tgtIntn = tgtOutside;
  22923. var intersectionPts = pairInfo.intersectionPts = {
  22924. x1: srcOutside[0],
  22925. x2: tgtOutside[0],
  22926. y1: srcOutside[1],
  22927. y2: tgtOutside[1]
  22928. };
  22929. var posPts = pairInfo.posPts = {
  22930. x1: srcPos.x,
  22931. x2: tgtPos.x,
  22932. y1: srcPos.y,
  22933. y2: tgtPos.y
  22934. };
  22935. var dy = tgtOutside[1] - srcOutside[1];
  22936. var dx = tgtOutside[0] - srcOutside[0];
  22937. var l = Math.sqrt(dx * dx + dy * dy);
  22938. if (number$1(l) && l >= AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L) ; else {
  22939. l = Math.sqrt(Math.max(dx * dx, AVOID_IMPOSSIBLE_BEZIER_CONSTANT) + Math.max(dy * dy, AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22940. }
  22941. var vector = pairInfo.vector = {
  22942. x: dx,
  22943. y: dy
  22944. };
  22945. var vectorNorm = pairInfo.vectorNorm = {
  22946. x: vector.x / l,
  22947. y: vector.y / l
  22948. };
  22949. var vectorNormInverse = {
  22950. x: -vectorNorm.y,
  22951. y: vectorNorm.x
  22952. };
  22953. // if node shapes overlap, then no ctrl pts to draw
  22954. 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);
  22955. pairInfo.vectorNormInverse = vectorNormInverse;
  22956. swappedpairInfo = {
  22957. nodesOverlap: pairInfo.nodesOverlap,
  22958. dirCounts: pairInfo.dirCounts,
  22959. calculatedIntersection: true,
  22960. hasBezier: pairInfo.hasBezier,
  22961. hasUnbundled: pairInfo.hasUnbundled,
  22962. eles: pairInfo.eles,
  22963. srcPos: tgtPos,
  22964. srcRs: tgtRs,
  22965. tgtPos: srcPos,
  22966. tgtRs: srcRs,
  22967. srcW: tgtW,
  22968. srcH: tgtH,
  22969. tgtW: srcW,
  22970. tgtH: srcH,
  22971. srcIntn: tgtIntn,
  22972. tgtIntn: srcIntn,
  22973. srcShape: tgtShape,
  22974. tgtShape: srcShape,
  22975. posPts: {
  22976. x1: posPts.x2,
  22977. y1: posPts.y2,
  22978. x2: posPts.x1,
  22979. y2: posPts.y1
  22980. },
  22981. intersectionPts: {
  22982. x1: intersectionPts.x2,
  22983. y1: intersectionPts.y2,
  22984. x2: intersectionPts.x1,
  22985. y2: intersectionPts.y1
  22986. },
  22987. vector: {
  22988. x: -vector.x,
  22989. y: -vector.y
  22990. },
  22991. vectorNorm: {
  22992. x: -vectorNorm.x,
  22993. y: -vectorNorm.y
  22994. },
  22995. vectorNormInverse: {
  22996. x: -vectorNormInverse.x,
  22997. y: -vectorNormInverse.y
  22998. }
  22999. };
  23000. }
  23001. var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;
  23002. rs.nodesOverlap = passedPairInfo.nodesOverlap;
  23003. rs.srcIntn = passedPairInfo.srcIntn;
  23004. rs.tgtIntn = passedPairInfo.tgtIntn;
  23005. rs.isRound = _curveStyle.startsWith('round');
  23006. if (hasCompounds && (src.isParent() || src.isChild() || tgt.isParent() || tgt.isChild()) && (src.parents().anySame(tgt) || tgt.parents().anySame(src) || src.same(tgt) && src.isParent())) {
  23007. _this.findCompoundLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
  23008. } else if (src === tgt) {
  23009. _this.findLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
  23010. } else if (_curveStyle.endsWith('segments')) {
  23011. _this.findSegmentsPoints(_edge, passedPairInfo);
  23012. } else if (_curveStyle.endsWith('taxi')) {
  23013. _this.findTaxiPoints(_edge, passedPairInfo);
  23014. } else if (_curveStyle === 'straight' || !_edgeIsUnbundled && pairInfo.eles.length % 2 === 1 && _i2 === Math.floor(pairInfo.eles.length / 2)) {
  23015. _this.findStraightEdgePoints(_edge);
  23016. } else {
  23017. _this.findBezierPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled, edgeIsSwapped);
  23018. }
  23019. _this.findEndpoints(_edge);
  23020. _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);
  23021. _this.checkForInvalidEdgeWarning(_edge);
  23022. _this.storeAllpts(_edge);
  23023. _this.storeEdgeProjections(_edge);
  23024. _this.calculateArrowAngles(_edge);
  23025. _this.recalculateEdgeLabelProjections(_edge);
  23026. _this.calculateLabelAngles(_edge);
  23027. } // for pair edges
  23028. };
  23029. for (var p = 0; p < pairIds.length; p++) {
  23030. _loop();
  23031. } // for pair ids
  23032. // haystacks avoid the expense of pairInfo stuff (intersections etc.)
  23033. this.findHaystackPoints(haystackEdges);
  23034. };
  23035. function getPts(pts) {
  23036. var retPts = [];
  23037. if (pts == null) {
  23038. return;
  23039. }
  23040. for (var i = 0; i < pts.length; i += 2) {
  23041. var x = pts[i];
  23042. var y = pts[i + 1];
  23043. retPts.push({
  23044. x: x,
  23045. y: y
  23046. });
  23047. }
  23048. return retPts;
  23049. }
  23050. BRp$c.getSegmentPoints = function (edge) {
  23051. var rs = edge[0]._private.rscratch;
  23052. this.recalculateRenderedStyle(edge);
  23053. var type = rs.edgeType;
  23054. if (type === 'segments') {
  23055. return getPts(rs.segpts);
  23056. }
  23057. };
  23058. BRp$c.getControlPoints = function (edge) {
  23059. var rs = edge[0]._private.rscratch;
  23060. this.recalculateRenderedStyle(edge);
  23061. var type = rs.edgeType;
  23062. if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {
  23063. return getPts(rs.ctrlpts);
  23064. }
  23065. };
  23066. BRp$c.getEdgeMidpoint = function (edge) {
  23067. var rs = edge[0]._private.rscratch;
  23068. this.recalculateRenderedStyle(edge);
  23069. return {
  23070. x: rs.midX,
  23071. y: rs.midY
  23072. };
  23073. };
  23074. var BRp$b = {};
  23075. BRp$b.manualEndptToPx = function (node, prop) {
  23076. var r = this;
  23077. var npos = node.position();
  23078. var w = node.outerWidth();
  23079. var h = node.outerHeight();
  23080. var rs = node._private.rscratch;
  23081. if (prop.value.length === 2) {
  23082. var p = [prop.pfValue[0], prop.pfValue[1]];
  23083. if (prop.units[0] === '%') {
  23084. p[0] = p[0] * w;
  23085. }
  23086. if (prop.units[1] === '%') {
  23087. p[1] = p[1] * h;
  23088. }
  23089. p[0] += npos.x;
  23090. p[1] += npos.y;
  23091. return p;
  23092. } else {
  23093. var angle = prop.pfValue[0];
  23094. angle = -Math.PI / 2 + angle; // start at 12 o'clock
  23095. var l = 2 * Math.max(w, h);
  23096. var _p = [npos.x + Math.cos(angle) * l, npos.y + Math.sin(angle) * l];
  23097. 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);
  23098. }
  23099. };
  23100. BRp$b.findEndpoints = function (edge) {
  23101. var _ref, _tgtManEndpt$pfValue, _ref2, _srcManEndpt$pfValue;
  23102. var r = this;
  23103. var intersect;
  23104. var source = edge.source()[0];
  23105. var target = edge.target()[0];
  23106. var srcPos = source.position();
  23107. var tgtPos = target.position();
  23108. var tgtArShape = edge.pstyle('target-arrow-shape').value;
  23109. var srcArShape = edge.pstyle('source-arrow-shape').value;
  23110. var tgtDist = edge.pstyle('target-distance-from-node').pfValue;
  23111. var srcDist = edge.pstyle('source-distance-from-node').pfValue;
  23112. var srcRs = source._private.rscratch;
  23113. var tgtRs = target._private.rscratch;
  23114. var curveStyle = edge.pstyle('curve-style').value;
  23115. var rs = edge._private.rscratch;
  23116. var et = rs.edgeType;
  23117. var taxi = endsWith(curveStyle, 'taxi'); // Covers taxi and round-taxi
  23118. var self = et === 'self' || et === 'compound';
  23119. var bezier = et === 'bezier' || et === 'multibezier' || self;
  23120. var multi = et !== 'bezier';
  23121. var lines = et === 'straight' || et === 'segments';
  23122. var segments = et === 'segments';
  23123. var hasEndpts = bezier || multi || lines;
  23124. var overrideEndpts = self || taxi;
  23125. var srcManEndpt = edge.pstyle('source-endpoint');
  23126. var srcManEndptVal = overrideEndpts ? 'outside-to-node' : srcManEndpt.value;
  23127. var srcCornerRadius = source.pstyle('corner-radius').value === 'auto' ? 'auto' : source.pstyle('corner-radius').pfValue;
  23128. var tgtManEndpt = edge.pstyle('target-endpoint');
  23129. var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;
  23130. var tgtCornerRadius = target.pstyle('corner-radius').value === 'auto' ? 'auto' : target.pstyle('corner-radius').pfValue;
  23131. rs.srcManEndpt = srcManEndpt;
  23132. rs.tgtManEndpt = tgtManEndpt;
  23133. var p1; // last known point of edge on target side
  23134. var p2; // last known point of edge on source side
  23135. var p1_i; // point to intersect with target shape
  23136. var p2_i; // point to intersect with source shape
  23137. 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];
  23138. 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];
  23139. if (bezier) {
  23140. var cpStart = [rs.ctrlpts[0], rs.ctrlpts[1]];
  23141. var cpEnd = multi ? [rs.ctrlpts[rs.ctrlpts.length - 2], rs.ctrlpts[rs.ctrlpts.length - 1]] : cpStart;
  23142. p1 = cpEnd;
  23143. p2 = cpStart;
  23144. } else if (lines) {
  23145. var srcArrowFromPt = !segments ? [tgtPos.x + tgtManEndptPt[0], tgtPos.y + tgtManEndptPt[1]] : rs.segpts.slice(0, 2);
  23146. var tgtArrowFromPt = !segments ? [srcPos.x + srcManEndptPt[0], srcPos.y + srcManEndptPt[1]] : rs.segpts.slice(rs.segpts.length - 2);
  23147. p1 = tgtArrowFromPt;
  23148. p2 = srcArrowFromPt;
  23149. }
  23150. if (tgtManEndptVal === 'inside-to-node') {
  23151. intersect = [tgtPos.x, tgtPos.y];
  23152. } else if (tgtManEndpt.units) {
  23153. intersect = this.manualEndptToPx(target, tgtManEndpt);
  23154. } else if (tgtManEndptVal === 'outside-to-line') {
  23155. intersect = rs.tgtIntn; // use cached value from ctrlpt calc
  23156. } else {
  23157. if (tgtManEndptVal === 'outside-to-node' || tgtManEndptVal === 'outside-to-node-or-label') {
  23158. p1_i = p1;
  23159. } else if (tgtManEndptVal === 'outside-to-line' || tgtManEndptVal === 'outside-to-line-or-label') {
  23160. p1_i = [srcPos.x, srcPos.y];
  23161. }
  23162. intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0, tgtCornerRadius, tgtRs);
  23163. if (tgtManEndptVal === 'outside-to-node-or-label' || tgtManEndptVal === 'outside-to-line-or-label') {
  23164. var trs = target._private.rscratch;
  23165. var lw = trs.labelWidth;
  23166. var lh = trs.labelHeight;
  23167. var lx = trs.labelX;
  23168. var ly = trs.labelY;
  23169. var lw2 = lw / 2;
  23170. var lh2 = lh / 2;
  23171. var va = target.pstyle('text-valign').value;
  23172. if (va === 'top') {
  23173. ly -= lh2;
  23174. } else if (va === 'bottom') {
  23175. ly += lh2;
  23176. }
  23177. var ha = target.pstyle('text-halign').value;
  23178. if (ha === 'left') {
  23179. lx -= lw2;
  23180. } else if (ha === 'right') {
  23181. lx += lw2;
  23182. }
  23183. 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);
  23184. if (labelIntersect.length > 0) {
  23185. var refPt = srcPos;
  23186. var intSqdist = sqdist(refPt, array2point(intersect));
  23187. var labIntSqdist = sqdist(refPt, array2point(labelIntersect));
  23188. var minSqDist = intSqdist;
  23189. if (labIntSqdist < intSqdist) {
  23190. intersect = labelIntersect;
  23191. minSqDist = labIntSqdist;
  23192. }
  23193. if (labelIntersect.length > 2) {
  23194. var labInt2SqDist = sqdist(refPt, {
  23195. x: labelIntersect[2],
  23196. y: labelIntersect[3]
  23197. });
  23198. if (labInt2SqDist < minSqDist) {
  23199. intersect = [labelIntersect[2], labelIntersect[3]];
  23200. }
  23201. }
  23202. }
  23203. }
  23204. }
  23205. var arrowEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].spacing(edge) + tgtDist);
  23206. var edgeEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].gap(edge) + tgtDist);
  23207. rs.endX = edgeEnd[0];
  23208. rs.endY = edgeEnd[1];
  23209. rs.arrowEndX = arrowEnd[0];
  23210. rs.arrowEndY = arrowEnd[1];
  23211. if (srcManEndptVal === 'inside-to-node') {
  23212. intersect = [srcPos.x, srcPos.y];
  23213. } else if (srcManEndpt.units) {
  23214. intersect = this.manualEndptToPx(source, srcManEndpt);
  23215. } else if (srcManEndptVal === 'outside-to-line') {
  23216. intersect = rs.srcIntn; // use cached value from ctrlpt calc
  23217. } else {
  23218. if (srcManEndptVal === 'outside-to-node' || srcManEndptVal === 'outside-to-node-or-label') {
  23219. p2_i = p2;
  23220. } else if (srcManEndptVal === 'outside-to-line' || srcManEndptVal === 'outside-to-line-or-label') {
  23221. p2_i = [tgtPos.x, tgtPos.y];
  23222. }
  23223. intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0, srcCornerRadius, srcRs);
  23224. if (srcManEndptVal === 'outside-to-node-or-label' || srcManEndptVal === 'outside-to-line-or-label') {
  23225. var srs = source._private.rscratch;
  23226. var _lw = srs.labelWidth;
  23227. var _lh = srs.labelHeight;
  23228. var _lx = srs.labelX;
  23229. var _ly = srs.labelY;
  23230. var _lw2 = _lw / 2;
  23231. var _lh2 = _lh / 2;
  23232. var _va = source.pstyle('text-valign').value;
  23233. if (_va === 'top') {
  23234. _ly -= _lh2;
  23235. } else if (_va === 'bottom') {
  23236. _ly += _lh2;
  23237. }
  23238. var _ha = source.pstyle('text-halign').value;
  23239. if (_ha === 'left') {
  23240. _lx -= _lw2;
  23241. } else if (_ha === 'right') {
  23242. _lx += _lw2;
  23243. }
  23244. 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);
  23245. if (_labelIntersect.length > 0) {
  23246. var _refPt = tgtPos;
  23247. var _intSqdist = sqdist(_refPt, array2point(intersect));
  23248. var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));
  23249. var _minSqDist = _intSqdist;
  23250. if (_labIntSqdist < _intSqdist) {
  23251. intersect = [_labelIntersect[0], _labelIntersect[1]];
  23252. _minSqDist = _labIntSqdist;
  23253. }
  23254. if (_labelIntersect.length > 2) {
  23255. var _labInt2SqDist = sqdist(_refPt, {
  23256. x: _labelIntersect[2],
  23257. y: _labelIntersect[3]
  23258. });
  23259. if (_labInt2SqDist < _minSqDist) {
  23260. intersect = [_labelIntersect[2], _labelIntersect[3]];
  23261. }
  23262. }
  23263. }
  23264. }
  23265. }
  23266. var arrowStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].spacing(edge) + srcDist);
  23267. var edgeStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].gap(edge) + srcDist);
  23268. rs.startX = edgeStart[0];
  23269. rs.startY = edgeStart[1];
  23270. rs.arrowStartX = arrowStart[0];
  23271. rs.arrowStartY = arrowStart[1];
  23272. if (hasEndpts) {
  23273. if (!number$1(rs.startX) || !number$1(rs.startY) || !number$1(rs.endX) || !number$1(rs.endY)) {
  23274. rs.badLine = true;
  23275. } else {
  23276. rs.badLine = false;
  23277. }
  23278. }
  23279. };
  23280. BRp$b.getSourceEndpoint = function (edge) {
  23281. var rs = edge[0]._private.rscratch;
  23282. this.recalculateRenderedStyle(edge);
  23283. switch (rs.edgeType) {
  23284. case 'haystack':
  23285. return {
  23286. x: rs.haystackPts[0],
  23287. y: rs.haystackPts[1]
  23288. };
  23289. default:
  23290. return {
  23291. x: rs.arrowStartX,
  23292. y: rs.arrowStartY
  23293. };
  23294. }
  23295. };
  23296. BRp$b.getTargetEndpoint = function (edge) {
  23297. var rs = edge[0]._private.rscratch;
  23298. this.recalculateRenderedStyle(edge);
  23299. switch (rs.edgeType) {
  23300. case 'haystack':
  23301. return {
  23302. x: rs.haystackPts[2],
  23303. y: rs.haystackPts[3]
  23304. };
  23305. default:
  23306. return {
  23307. x: rs.arrowEndX,
  23308. y: rs.arrowEndY
  23309. };
  23310. }
  23311. };
  23312. var BRp$a = {};
  23313. function pushBezierPts(r, edge, pts) {
  23314. var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {
  23315. return qbezierAt(p1, p2, p3, t);
  23316. };
  23317. var _p = edge._private;
  23318. var bpts = _p.rstyle.bezierPts;
  23319. for (var i = 0; i < r.bezierProjPcts.length; i++) {
  23320. var p = r.bezierProjPcts[i];
  23321. bpts.push({
  23322. x: qbezierAt$1(pts[0], pts[2], pts[4], p),
  23323. y: qbezierAt$1(pts[1], pts[3], pts[5], p)
  23324. });
  23325. }
  23326. }
  23327. BRp$a.storeEdgeProjections = function (edge) {
  23328. var _p = edge._private;
  23329. var rs = _p.rscratch;
  23330. var et = rs.edgeType;
  23331. // clear the cached points state
  23332. _p.rstyle.bezierPts = null;
  23333. _p.rstyle.linePts = null;
  23334. _p.rstyle.haystackPts = null;
  23335. if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {
  23336. _p.rstyle.bezierPts = [];
  23337. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  23338. pushBezierPts(this, edge, rs.allpts.slice(i, i + 6));
  23339. }
  23340. } else if (et === 'segments') {
  23341. var lpts = _p.rstyle.linePts = [];
  23342. for (var i = 0; i + 1 < rs.allpts.length; i += 2) {
  23343. lpts.push({
  23344. x: rs.allpts[i],
  23345. y: rs.allpts[i + 1]
  23346. });
  23347. }
  23348. } else if (et === 'haystack') {
  23349. var hpts = rs.haystackPts;
  23350. _p.rstyle.haystackPts = [{
  23351. x: hpts[0],
  23352. y: hpts[1]
  23353. }, {
  23354. x: hpts[2],
  23355. y: hpts[3]
  23356. }];
  23357. }
  23358. _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
  23359. };
  23360. BRp$a.recalculateEdgeProjections = function (edges) {
  23361. this.findEdgeControlPoints(edges);
  23362. };
  23363. var BRp$9 = {};
  23364. BRp$9.recalculateNodeLabelProjection = function (node) {
  23365. var content = node.pstyle('label').strValue;
  23366. if (emptyString(content)) {
  23367. return;
  23368. }
  23369. var textX, textY;
  23370. var _p = node._private;
  23371. var nodeWidth = node.width();
  23372. var nodeHeight = node.height();
  23373. var padding = node.padding();
  23374. var nodePos = node.position();
  23375. var textHalign = node.pstyle('text-halign').strValue;
  23376. var textValign = node.pstyle('text-valign').strValue;
  23377. var rs = _p.rscratch;
  23378. var rstyle = _p.rstyle;
  23379. switch (textHalign) {
  23380. case 'left':
  23381. textX = nodePos.x - nodeWidth / 2 - padding;
  23382. break;
  23383. case 'right':
  23384. textX = nodePos.x + nodeWidth / 2 + padding;
  23385. break;
  23386. default:
  23387. // e.g. center
  23388. textX = nodePos.x;
  23389. }
  23390. switch (textValign) {
  23391. case 'top':
  23392. textY = nodePos.y - nodeHeight / 2 - padding;
  23393. break;
  23394. case 'bottom':
  23395. textY = nodePos.y + nodeHeight / 2 + padding;
  23396. break;
  23397. default:
  23398. // e.g. middle
  23399. textY = nodePos.y;
  23400. }
  23401. rs.labelX = textX;
  23402. rs.labelY = textY;
  23403. rstyle.labelX = textX;
  23404. rstyle.labelY = textY;
  23405. this.calculateLabelAngles(node);
  23406. this.applyLabelDimensions(node);
  23407. };
  23408. var lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {
  23409. var angle = Math.atan(dy / dx);
  23410. if (dx === 0 && angle < 0) {
  23411. angle = angle * -1;
  23412. }
  23413. return angle;
  23414. };
  23415. var lineAngle = function lineAngle(p0, p1) {
  23416. var dx = p1.x - p0.x;
  23417. var dy = p1.y - p0.y;
  23418. return lineAngleFromDelta(dx, dy);
  23419. };
  23420. var bezierAngle = function bezierAngle(p0, p1, p2, t) {
  23421. var t0 = bound(0, t - 0.001, 1);
  23422. var t1 = bound(0, t + 0.001, 1);
  23423. var lp0 = qbezierPtAt(p0, p1, p2, t0);
  23424. var lp1 = qbezierPtAt(p0, p1, p2, t1);
  23425. return lineAngle(lp0, lp1);
  23426. };
  23427. BRp$9.recalculateEdgeLabelProjections = function (edge) {
  23428. var p;
  23429. var _p = edge._private;
  23430. var rs = _p.rscratch;
  23431. var r = this;
  23432. var content = {
  23433. mid: edge.pstyle('label').strValue,
  23434. source: edge.pstyle('source-label').strValue,
  23435. target: edge.pstyle('target-label').strValue
  23436. };
  23437. if (content.mid || content.source || content.target) ; else {
  23438. return; // no labels => no calcs
  23439. }
  23440. // add center point to style so bounding box calculations can use it
  23441. //
  23442. p = {
  23443. x: rs.midX,
  23444. y: rs.midY
  23445. };
  23446. var setRs = function setRs(propName, prefix, value) {
  23447. setPrefixedProperty(_p.rscratch, propName, prefix, value);
  23448. setPrefixedProperty(_p.rstyle, propName, prefix, value);
  23449. };
  23450. setRs('labelX', null, p.x);
  23451. setRs('labelY', null, p.y);
  23452. var midAngle = lineAngleFromDelta(rs.midDispX, rs.midDispY);
  23453. setRs('labelAutoAngle', null, midAngle);
  23454. var _createControlPointInfo = function createControlPointInfo() {
  23455. if (_createControlPointInfo.cache) {
  23456. return _createControlPointInfo.cache;
  23457. } // use cache so only 1x per edge
  23458. var ctrlpts = [];
  23459. // store each ctrlpt info init
  23460. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  23461. var p0 = {
  23462. x: rs.allpts[i],
  23463. y: rs.allpts[i + 1]
  23464. };
  23465. var p1 = {
  23466. x: rs.allpts[i + 2],
  23467. y: rs.allpts[i + 3]
  23468. }; // ctrlpt
  23469. var p2 = {
  23470. x: rs.allpts[i + 4],
  23471. y: rs.allpts[i + 5]
  23472. };
  23473. ctrlpts.push({
  23474. p0: p0,
  23475. p1: p1,
  23476. p2: p2,
  23477. startDist: 0,
  23478. length: 0,
  23479. segments: []
  23480. });
  23481. }
  23482. var bpts = _p.rstyle.bezierPts;
  23483. var nProjs = r.bezierProjPcts.length;
  23484. function addSegment(cp, p0, p1, t0, t1) {
  23485. var length = dist(p0, p1);
  23486. var prevSegment = cp.segments[cp.segments.length - 1];
  23487. var segment = {
  23488. p0: p0,
  23489. p1: p1,
  23490. t0: t0,
  23491. t1: t1,
  23492. startDist: prevSegment ? prevSegment.startDist + prevSegment.length : 0,
  23493. length: length
  23494. };
  23495. cp.segments.push(segment);
  23496. cp.length += length;
  23497. }
  23498. // update each ctrlpt with segment info
  23499. for (var _i = 0; _i < ctrlpts.length; _i++) {
  23500. var cp = ctrlpts[_i];
  23501. var prevCp = ctrlpts[_i - 1];
  23502. if (prevCp) {
  23503. cp.startDist = prevCp.startDist + prevCp.length;
  23504. }
  23505. addSegment(cp, cp.p0, bpts[_i * nProjs], 0, r.bezierProjPcts[0]); // first
  23506. for (var j = 0; j < nProjs - 1; j++) {
  23507. addSegment(cp, bpts[_i * nProjs + j], bpts[_i * nProjs + j + 1], r.bezierProjPcts[j], r.bezierProjPcts[j + 1]);
  23508. }
  23509. addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last
  23510. }
  23511. return _createControlPointInfo.cache = ctrlpts;
  23512. };
  23513. var calculateEndProjection = function calculateEndProjection(prefix) {
  23514. var angle;
  23515. var isSrc = prefix === 'source';
  23516. if (!content[prefix]) {
  23517. return;
  23518. }
  23519. var offset = edge.pstyle(prefix + '-text-offset').pfValue;
  23520. switch (rs.edgeType) {
  23521. case 'self':
  23522. case 'compound':
  23523. case 'bezier':
  23524. case 'multibezier':
  23525. {
  23526. var cps = _createControlPointInfo();
  23527. var selected;
  23528. var startDist = 0;
  23529. var totalDist = 0;
  23530. // find the segment we're on
  23531. for (var i = 0; i < cps.length; i++) {
  23532. var _cp = cps[isSrc ? i : cps.length - 1 - i];
  23533. for (var j = 0; j < _cp.segments.length; j++) {
  23534. var _seg = _cp.segments[isSrc ? j : _cp.segments.length - 1 - j];
  23535. var lastSeg = i === cps.length - 1 && j === _cp.segments.length - 1;
  23536. startDist = totalDist;
  23537. totalDist += _seg.length;
  23538. if (totalDist >= offset || lastSeg) {
  23539. selected = {
  23540. cp: _cp,
  23541. segment: _seg
  23542. };
  23543. break;
  23544. }
  23545. }
  23546. if (selected) {
  23547. break;
  23548. }
  23549. }
  23550. var cp = selected.cp;
  23551. var seg = selected.segment;
  23552. var tSegment = (offset - startDist) / seg.length;
  23553. var segDt = seg.t1 - seg.t0;
  23554. var t = isSrc ? seg.t0 + segDt * tSegment : seg.t1 - segDt * tSegment;
  23555. t = bound(0, t, 1);
  23556. p = qbezierPtAt(cp.p0, cp.p1, cp.p2, t);
  23557. angle = bezierAngle(cp.p0, cp.p1, cp.p2, t);
  23558. break;
  23559. }
  23560. case 'straight':
  23561. case 'segments':
  23562. case 'haystack':
  23563. {
  23564. var d = 0,
  23565. di,
  23566. d0;
  23567. var p0, p1;
  23568. var l = rs.allpts.length;
  23569. for (var _i2 = 0; _i2 + 3 < l; _i2 += 2) {
  23570. if (isSrc) {
  23571. p0 = {
  23572. x: rs.allpts[_i2],
  23573. y: rs.allpts[_i2 + 1]
  23574. };
  23575. p1 = {
  23576. x: rs.allpts[_i2 + 2],
  23577. y: rs.allpts[_i2 + 3]
  23578. };
  23579. } else {
  23580. p0 = {
  23581. x: rs.allpts[l - 2 - _i2],
  23582. y: rs.allpts[l - 1 - _i2]
  23583. };
  23584. p1 = {
  23585. x: rs.allpts[l - 4 - _i2],
  23586. y: rs.allpts[l - 3 - _i2]
  23587. };
  23588. }
  23589. di = dist(p0, p1);
  23590. d0 = d;
  23591. d += di;
  23592. if (d >= offset) {
  23593. break;
  23594. }
  23595. }
  23596. var pD = offset - d0;
  23597. var _t = pD / di;
  23598. _t = bound(0, _t, 1);
  23599. p = lineAt(p0, p1, _t);
  23600. angle = lineAngle(p0, p1);
  23601. break;
  23602. }
  23603. }
  23604. setRs('labelX', prefix, p.x);
  23605. setRs('labelY', prefix, p.y);
  23606. setRs('labelAutoAngle', prefix, angle);
  23607. };
  23608. calculateEndProjection('source');
  23609. calculateEndProjection('target');
  23610. this.applyLabelDimensions(edge);
  23611. };
  23612. BRp$9.applyLabelDimensions = function (ele) {
  23613. this.applyPrefixedLabelDimensions(ele);
  23614. if (ele.isEdge()) {
  23615. this.applyPrefixedLabelDimensions(ele, 'source');
  23616. this.applyPrefixedLabelDimensions(ele, 'target');
  23617. }
  23618. };
  23619. BRp$9.applyPrefixedLabelDimensions = function (ele, prefix) {
  23620. var _p = ele._private;
  23621. var text = this.getLabelText(ele, prefix);
  23622. var cacheKey = hashString(text, ele._private.labelDimsKey);
  23623. // save recalc if the label is the same as before
  23624. if (getPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix) === cacheKey) {
  23625. return; // then the label dimensions + text are the same
  23626. }
  23627. // save the key
  23628. setPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix, cacheKey);
  23629. var labelDims = this.calculateLabelDimensions(ele, text);
  23630. var lineHeight = ele.pstyle('line-height').pfValue;
  23631. var textWrap = ele.pstyle('text-wrap').strValue;
  23632. var lines = getPrefixedProperty(_p.rscratch, 'labelWrapCachedLines', prefix) || [];
  23633. var numLines = textWrap !== 'wrap' ? 1 : Math.max(lines.length, 1);
  23634. var normPerLineHeight = labelDims.height / numLines;
  23635. var labelLineHeight = normPerLineHeight * lineHeight;
  23636. var width = labelDims.width;
  23637. var height = labelDims.height + (numLines - 1) * (lineHeight - 1) * normPerLineHeight;
  23638. setPrefixedProperty(_p.rstyle, 'labelWidth', prefix, width);
  23639. setPrefixedProperty(_p.rscratch, 'labelWidth', prefix, width);
  23640. setPrefixedProperty(_p.rstyle, 'labelHeight', prefix, height);
  23641. setPrefixedProperty(_p.rscratch, 'labelHeight', prefix, height);
  23642. setPrefixedProperty(_p.rscratch, 'labelLineHeight', prefix, labelLineHeight);
  23643. };
  23644. BRp$9.getLabelText = function (ele, prefix) {
  23645. var _p = ele._private;
  23646. var pfd = prefix ? prefix + '-' : '';
  23647. var text = ele.pstyle(pfd + 'label').strValue;
  23648. var textTransform = ele.pstyle('text-transform').value;
  23649. var rscratch = function rscratch(propName, value) {
  23650. if (value) {
  23651. setPrefixedProperty(_p.rscratch, propName, prefix, value);
  23652. return value;
  23653. } else {
  23654. return getPrefixedProperty(_p.rscratch, propName, prefix);
  23655. }
  23656. };
  23657. // for empty text, skip all processing
  23658. if (!text) {
  23659. return '';
  23660. }
  23661. if (textTransform == 'none') ; else if (textTransform == 'uppercase') {
  23662. text = text.toUpperCase();
  23663. } else if (textTransform == 'lowercase') {
  23664. text = text.toLowerCase();
  23665. }
  23666. var wrapStyle = ele.pstyle('text-wrap').value;
  23667. if (wrapStyle === 'wrap') {
  23668. var labelKey = rscratch('labelKey');
  23669. // save recalc if the label is the same as before
  23670. if (labelKey != null && rscratch('labelWrapKey') === labelKey) {
  23671. return rscratch('labelWrapCachedText');
  23672. }
  23673. var zwsp = "\u200B";
  23674. var lines = text.split('\n');
  23675. var maxW = ele.pstyle('text-max-width').pfValue;
  23676. var overflow = ele.pstyle('text-overflow-wrap').value;
  23677. var overflowAny = overflow === 'anywhere';
  23678. var wrappedLines = [];
  23679. var separatorRegex = /[\s\u200b]+|$/g; // Include end of string to add last word
  23680. for (var l = 0; l < lines.length; l++) {
  23681. var line = lines[l];
  23682. var lineDims = this.calculateLabelDimensions(ele, line);
  23683. var lineW = lineDims.width;
  23684. if (overflowAny) {
  23685. var processedLine = line.split('').join(zwsp);
  23686. line = processedLine;
  23687. }
  23688. if (lineW > maxW) {
  23689. // line is too long
  23690. var separatorMatches = line.matchAll(separatorRegex);
  23691. var subline = '';
  23692. var previousIndex = 0;
  23693. // Add fake match
  23694. var _iterator = _createForOfIteratorHelper(separatorMatches),
  23695. _step;
  23696. try {
  23697. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  23698. var separatorMatch = _step.value;
  23699. var wordSeparator = separatorMatch[0];
  23700. var word = line.substring(previousIndex, separatorMatch.index);
  23701. previousIndex = separatorMatch.index + wordSeparator.length;
  23702. var testLine = subline.length === 0 ? word : subline + word + wordSeparator;
  23703. var testDims = this.calculateLabelDimensions(ele, testLine);
  23704. var testW = testDims.width;
  23705. if (testW <= maxW) {
  23706. // word fits on current line
  23707. subline += word + wordSeparator;
  23708. } else {
  23709. // word starts new line
  23710. if (subline) {
  23711. wrappedLines.push(subline);
  23712. }
  23713. subline = word + wordSeparator;
  23714. }
  23715. }
  23716. // if there's remaining text, put it in a wrapped line
  23717. } catch (err) {
  23718. _iterator.e(err);
  23719. } finally {
  23720. _iterator.f();
  23721. }
  23722. if (!subline.match(/^[\s\u200b]+$/)) {
  23723. wrappedLines.push(subline);
  23724. }
  23725. } else {
  23726. // line is already short enough
  23727. wrappedLines.push(line);
  23728. }
  23729. } // for
  23730. rscratch('labelWrapCachedLines', wrappedLines);
  23731. text = rscratch('labelWrapCachedText', wrappedLines.join('\n'));
  23732. rscratch('labelWrapKey', labelKey);
  23733. } else if (wrapStyle === 'ellipsis') {
  23734. var _maxW = ele.pstyle('text-max-width').pfValue;
  23735. var ellipsized = '';
  23736. var ellipsis = "\u2026";
  23737. var incLastCh = false;
  23738. if (this.calculateLabelDimensions(ele, text).width < _maxW) {
  23739. // the label already fits
  23740. return text;
  23741. }
  23742. for (var i = 0; i < text.length; i++) {
  23743. var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;
  23744. if (widthWithNextCh > _maxW) {
  23745. break;
  23746. }
  23747. ellipsized += text[i];
  23748. if (i === text.length - 1) {
  23749. incLastCh = true;
  23750. }
  23751. }
  23752. if (!incLastCh) {
  23753. ellipsized += ellipsis;
  23754. }
  23755. return ellipsized;
  23756. } // if ellipsize
  23757. return text;
  23758. };
  23759. BRp$9.getLabelJustification = function (ele) {
  23760. var justification = ele.pstyle('text-justification').strValue;
  23761. var textHalign = ele.pstyle('text-halign').strValue;
  23762. if (justification === 'auto') {
  23763. if (ele.isNode()) {
  23764. switch (textHalign) {
  23765. case 'left':
  23766. return 'right';
  23767. case 'right':
  23768. return 'left';
  23769. default:
  23770. return 'center';
  23771. }
  23772. } else {
  23773. return 'center';
  23774. }
  23775. } else {
  23776. return justification;
  23777. }
  23778. };
  23779. BRp$9.calculateLabelDimensions = function (ele, text) {
  23780. var r = this;
  23781. var containerWindow = r.cy.window();
  23782. var document = containerWindow.document;
  23783. var padding = 0; // add padding around text dims, as the measurement isn't that accurate
  23784. var fStyle = ele.pstyle('font-style').strValue;
  23785. var size = ele.pstyle('font-size').pfValue;
  23786. var family = ele.pstyle('font-family').strValue;
  23787. var weight = ele.pstyle('font-weight').strValue;
  23788. var canvas = this.labelCalcCanvas;
  23789. var c2d = this.labelCalcCanvasContext;
  23790. if (!canvas) {
  23791. canvas = this.labelCalcCanvas = document.createElement('canvas');
  23792. c2d = this.labelCalcCanvasContext = canvas.getContext('2d');
  23793. var ds = canvas.style;
  23794. ds.position = 'absolute';
  23795. ds.left = '-9999px';
  23796. ds.top = '-9999px';
  23797. ds.zIndex = '-1';
  23798. ds.visibility = 'hidden';
  23799. ds.pointerEvents = 'none';
  23800. }
  23801. c2d.font = "".concat(fStyle, " ").concat(weight, " ").concat(size, "px ").concat(family);
  23802. var width = 0;
  23803. var height = 0;
  23804. var lines = text.split('\n');
  23805. for (var i = 0; i < lines.length; i++) {
  23806. var line = lines[i];
  23807. var metrics = c2d.measureText(line);
  23808. var w = Math.ceil(metrics.width);
  23809. var h = size;
  23810. width = Math.max(w, width);
  23811. height += h;
  23812. }
  23813. width += padding;
  23814. height += padding;
  23815. return {
  23816. width: width,
  23817. height: height
  23818. };
  23819. };
  23820. BRp$9.calculateLabelAngle = function (ele, prefix) {
  23821. var _p = ele._private;
  23822. var rs = _p.rscratch;
  23823. var isEdge = ele.isEdge();
  23824. var prefixDash = prefix ? prefix + '-' : '';
  23825. var rot = ele.pstyle(prefixDash + 'text-rotation');
  23826. var rotStr = rot.strValue;
  23827. if (rotStr === 'none') {
  23828. return 0;
  23829. } else if (isEdge && rotStr === 'autorotate') {
  23830. return rs.labelAutoAngle;
  23831. } else if (rotStr === 'autorotate') {
  23832. return 0;
  23833. } else {
  23834. return rot.pfValue;
  23835. }
  23836. };
  23837. BRp$9.calculateLabelAngles = function (ele) {
  23838. var r = this;
  23839. var isEdge = ele.isEdge();
  23840. var _p = ele._private;
  23841. var rs = _p.rscratch;
  23842. rs.labelAngle = r.calculateLabelAngle(ele);
  23843. if (isEdge) {
  23844. rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');
  23845. rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');
  23846. }
  23847. };
  23848. var BRp$8 = {};
  23849. var TOO_SMALL_CUT_RECT = 28;
  23850. var warnedCutRect = false;
  23851. BRp$8.getNodeShape = function (node) {
  23852. var r = this;
  23853. var shape = node.pstyle('shape').value;
  23854. if (shape === 'cutrectangle' && (node.width() < TOO_SMALL_CUT_RECT || node.height() < TOO_SMALL_CUT_RECT)) {
  23855. if (!warnedCutRect) {
  23856. warn('The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead');
  23857. warnedCutRect = true;
  23858. }
  23859. return 'rectangle';
  23860. }
  23861. if (node.isParent()) {
  23862. if (shape === 'rectangle' || shape === 'roundrectangle' || shape === 'round-rectangle' || shape === 'cutrectangle' || shape === 'cut-rectangle' || shape === 'barrel') {
  23863. return shape;
  23864. } else {
  23865. return 'rectangle';
  23866. }
  23867. }
  23868. if (shape === 'polygon') {
  23869. var points = node.pstyle('shape-polygon-points').value;
  23870. return r.nodeShapes.makePolygon(points).name;
  23871. }
  23872. return shape;
  23873. };
  23874. var BRp$7 = {};
  23875. BRp$7.registerCalculationListeners = function () {
  23876. var cy = this.cy;
  23877. var elesToUpdate = cy.collection();
  23878. var r = this;
  23879. var enqueue = function enqueue(eles) {
  23880. var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  23881. elesToUpdate.merge(eles);
  23882. if (dirtyStyleCaches) {
  23883. for (var i = 0; i < eles.length; i++) {
  23884. var ele = eles[i];
  23885. var _p = ele._private;
  23886. var rstyle = _p.rstyle;
  23887. rstyle.clean = false;
  23888. rstyle.cleanConnected = false;
  23889. }
  23890. }
  23891. };
  23892. r.binder(cy).on('bounds.* dirty.*', function onDirtyBounds(e) {
  23893. var ele = e.target;
  23894. enqueue(ele);
  23895. }).on('style.* background.*', function onDirtyStyle(e) {
  23896. var ele = e.target;
  23897. enqueue(ele, false);
  23898. });
  23899. var updateEleCalcs = function updateEleCalcs(willDraw) {
  23900. if (willDraw) {
  23901. var fns = r.onUpdateEleCalcsFns;
  23902. // because we need to have up-to-date style (e.g. stylesheet mappers)
  23903. // before calculating rendered style (and pstyle might not be called yet)
  23904. elesToUpdate.cleanStyle();
  23905. for (var i = 0; i < elesToUpdate.length; i++) {
  23906. var ele = elesToUpdate[i];
  23907. var rstyle = ele._private.rstyle;
  23908. if (ele.isNode() && !rstyle.cleanConnected) {
  23909. enqueue(ele.connectedEdges());
  23910. rstyle.cleanConnected = true;
  23911. }
  23912. }
  23913. if (fns) {
  23914. for (var _i = 0; _i < fns.length; _i++) {
  23915. var fn = fns[_i];
  23916. fn(willDraw, elesToUpdate);
  23917. }
  23918. }
  23919. r.recalculateRenderedStyle(elesToUpdate);
  23920. elesToUpdate = cy.collection();
  23921. }
  23922. };
  23923. r.flushRenderedStyleQueue = function () {
  23924. updateEleCalcs(true);
  23925. };
  23926. r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);
  23927. };
  23928. BRp$7.onUpdateEleCalcs = function (fn) {
  23929. var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];
  23930. fns.push(fn);
  23931. };
  23932. BRp$7.recalculateRenderedStyle = function (eles, useCache) {
  23933. var isCleanConnected = function isCleanConnected(ele) {
  23934. return ele._private.rstyle.cleanConnected;
  23935. };
  23936. if (eles.length === 0) {
  23937. return;
  23938. }
  23939. var edges = [];
  23940. var nodes = [];
  23941. // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()
  23942. if (this.destroyed) {
  23943. return;
  23944. }
  23945. // use cache by default for perf
  23946. if (useCache === undefined) {
  23947. useCache = true;
  23948. }
  23949. for (var i = 0; i < eles.length; i++) {
  23950. var ele = eles[i];
  23951. var _p = ele._private;
  23952. var rstyle = _p.rstyle;
  23953. // an edge may be implicitly dirty b/c of one of its connected nodes
  23954. // (and a request for recalc may come in between frames)
  23955. if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {
  23956. rstyle.clean = false;
  23957. }
  23958. if (ele.isEdge() && ele.isBundledBezier()) {
  23959. if (ele.parallelEdges().some(function (ele) {
  23960. return !ele._private.rstyle.clean && ele.isBundledBezier();
  23961. })) {
  23962. rstyle.clean = false;
  23963. }
  23964. }
  23965. // only update if dirty and in graph
  23966. if (useCache && rstyle.clean || ele.removed()) {
  23967. continue;
  23968. }
  23969. // only update if not display: none
  23970. if (ele.pstyle('display').value === 'none') {
  23971. continue;
  23972. }
  23973. if (_p.group === 'nodes') {
  23974. nodes.push(ele);
  23975. } else {
  23976. // edges
  23977. edges.push(ele);
  23978. }
  23979. rstyle.clean = true;
  23980. }
  23981. // update node data from projections
  23982. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  23983. var _ele = nodes[_i2];
  23984. var _p2 = _ele._private;
  23985. var _rstyle = _p2.rstyle;
  23986. var pos = _ele.position();
  23987. this.recalculateNodeLabelProjection(_ele);
  23988. _rstyle.nodeX = pos.x;
  23989. _rstyle.nodeY = pos.y;
  23990. _rstyle.nodeW = _ele.pstyle('width').pfValue;
  23991. _rstyle.nodeH = _ele.pstyle('height').pfValue;
  23992. }
  23993. this.recalculateEdgeProjections(edges);
  23994. // update edge data from projections
  23995. for (var _i3 = 0; _i3 < edges.length; _i3++) {
  23996. var _ele2 = edges[_i3];
  23997. var _p3 = _ele2._private;
  23998. var _rstyle2 = _p3.rstyle;
  23999. var rs = _p3.rscratch;
  24000. // update rstyle positions
  24001. _rstyle2.srcX = rs.arrowStartX;
  24002. _rstyle2.srcY = rs.arrowStartY;
  24003. _rstyle2.tgtX = rs.arrowEndX;
  24004. _rstyle2.tgtY = rs.arrowEndY;
  24005. _rstyle2.midX = rs.midX;
  24006. _rstyle2.midY = rs.midY;
  24007. _rstyle2.labelAngle = rs.labelAngle;
  24008. _rstyle2.sourceLabelAngle = rs.sourceLabelAngle;
  24009. _rstyle2.targetLabelAngle = rs.targetLabelAngle;
  24010. }
  24011. };
  24012. var BRp$6 = {};
  24013. BRp$6.updateCachedGrabbedEles = function () {
  24014. var eles = this.cachedZSortedEles;
  24015. if (!eles) {
  24016. // just let this be recalculated on the next z sort tick
  24017. return;
  24018. }
  24019. eles.drag = [];
  24020. eles.nondrag = [];
  24021. var grabTargets = [];
  24022. for (var i = 0; i < eles.length; i++) {
  24023. var ele = eles[i];
  24024. var rs = ele._private.rscratch;
  24025. if (ele.grabbed() && !ele.isParent()) {
  24026. grabTargets.push(ele);
  24027. } else if (rs.inDragLayer) {
  24028. eles.drag.push(ele);
  24029. } else {
  24030. eles.nondrag.push(ele);
  24031. }
  24032. }
  24033. // put the grab target nodes last so it's on top of its neighbourhood
  24034. for (var i = 0; i < grabTargets.length; i++) {
  24035. var ele = grabTargets[i];
  24036. eles.drag.push(ele);
  24037. }
  24038. };
  24039. BRp$6.invalidateCachedZSortedEles = function () {
  24040. this.cachedZSortedEles = null;
  24041. };
  24042. BRp$6.getCachedZSortedEles = function (forceRecalc) {
  24043. if (forceRecalc || !this.cachedZSortedEles) {
  24044. var eles = this.cy.mutableElements().toArray();
  24045. eles.sort(zIndexSort);
  24046. eles.interactive = eles.filter(function (ele) {
  24047. return ele.interactive();
  24048. });
  24049. this.cachedZSortedEles = eles;
  24050. this.updateCachedGrabbedEles();
  24051. } else {
  24052. eles = this.cachedZSortedEles;
  24053. }
  24054. return eles;
  24055. };
  24056. var BRp$5 = {};
  24057. [BRp$e, BRp$d, BRp$c, BRp$b, BRp$a, BRp$9, BRp$8, BRp$7, BRp$6].forEach(function (props) {
  24058. extend(BRp$5, props);
  24059. });
  24060. var BRp$4 = {};
  24061. BRp$4.getCachedImage = function (url, crossOrigin, onLoad) {
  24062. var r = this;
  24063. var imageCache = r.imageCache = r.imageCache || {};
  24064. var cache = imageCache[url];
  24065. if (cache) {
  24066. if (!cache.image.complete) {
  24067. cache.image.addEventListener('load', onLoad);
  24068. }
  24069. return cache.image;
  24070. } else {
  24071. cache = imageCache[url] = imageCache[url] || {};
  24072. var image = cache.image = new Image(); // eslint-disable-line no-undef
  24073. image.addEventListener('load', onLoad);
  24074. image.addEventListener('error', function () {
  24075. image.error = true;
  24076. });
  24077. // #1582 safari doesn't load data uris with crossOrigin properly
  24078. // https://bugs.webkit.org/show_bug.cgi?id=123978
  24079. var dataUriPrefix = 'data:';
  24080. var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;
  24081. if (!isDataUri) {
  24082. // if crossorigin is 'null'(stringified), then manually set it to null
  24083. crossOrigin = crossOrigin === 'null' ? null : crossOrigin;
  24084. image.crossOrigin = crossOrigin; // prevent tainted canvas
  24085. }
  24086. image.src = url;
  24087. return image;
  24088. }
  24089. };
  24090. var BRp$3 = {};
  24091. /* global document, ResizeObserver, MutationObserver */
  24092. BRp$3.registerBinding = function (target, event, handler, useCapture) {
  24093. // eslint-disable-line no-unused-vars
  24094. var args = Array.prototype.slice.apply(arguments, [1]); // copy
  24095. if (Array.isArray(target)) {
  24096. var res = [];
  24097. for (var i = 0; i < target.length; i++) {
  24098. var t = target[i];
  24099. if (t !== undefined) {
  24100. var b = this.binder(t);
  24101. res.push(b.on.apply(b, args));
  24102. }
  24103. }
  24104. return res;
  24105. }
  24106. var b = this.binder(target);
  24107. return b.on.apply(b, args);
  24108. };
  24109. BRp$3.binder = function (tgt) {
  24110. var r = this;
  24111. var containerWindow = r.cy.window();
  24112. var tgtIsDom = tgt === containerWindow || tgt === containerWindow.document || tgt === containerWindow.document.body || domElement(tgt);
  24113. if (r.supportsPassiveEvents == null) {
  24114. // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  24115. var supportsPassive = false;
  24116. try {
  24117. var opts = Object.defineProperty({}, 'passive', {
  24118. get: function get() {
  24119. supportsPassive = true;
  24120. return true;
  24121. }
  24122. });
  24123. containerWindow.addEventListener('test', null, opts);
  24124. } catch (err) {
  24125. // not supported
  24126. }
  24127. r.supportsPassiveEvents = supportsPassive;
  24128. }
  24129. var on = function on(event, handler, useCapture) {
  24130. var args = Array.prototype.slice.call(arguments);
  24131. if (tgtIsDom && r.supportsPassiveEvents) {
  24132. // replace useCapture w/ opts obj
  24133. args[2] = {
  24134. capture: useCapture != null ? useCapture : false,
  24135. passive: false,
  24136. once: false
  24137. };
  24138. }
  24139. r.bindings.push({
  24140. target: tgt,
  24141. args: args
  24142. });
  24143. (tgt.addEventListener || tgt.on).apply(tgt, args);
  24144. return this;
  24145. };
  24146. return {
  24147. on: on,
  24148. addEventListener: on,
  24149. addListener: on,
  24150. bind: on
  24151. };
  24152. };
  24153. BRp$3.nodeIsDraggable = function (node) {
  24154. return node && node.isNode() && !node.locked() && node.grabbable();
  24155. };
  24156. BRp$3.nodeIsGrabbable = function (node) {
  24157. return this.nodeIsDraggable(node) && node.interactive();
  24158. };
  24159. BRp$3.load = function () {
  24160. var r = this;
  24161. var containerWindow = r.cy.window();
  24162. var isSelected = function isSelected(ele) {
  24163. return ele.selected();
  24164. };
  24165. var getShadowRoot = function getShadowRoot(element) {
  24166. var rootNode = element.getRootNode();
  24167. // Check if the root node is a shadow root
  24168. if (rootNode && rootNode.nodeType === 11 && rootNode.host !== undefined) {
  24169. return rootNode;
  24170. }
  24171. };
  24172. var triggerEvents = function triggerEvents(target, names, e, position) {
  24173. if (target == null) {
  24174. target = r.cy;
  24175. }
  24176. for (var i = 0; i < names.length; i++) {
  24177. var name = names[i];
  24178. target.emit({
  24179. originalEvent: e,
  24180. type: name,
  24181. position: position
  24182. });
  24183. }
  24184. };
  24185. var isMultSelKeyDown = function isMultSelKeyDown(e) {
  24186. return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey
  24187. };
  24188. var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {
  24189. var allowPassthrough = true;
  24190. if (r.cy.hasCompoundNodes() && down && down.pannable()) {
  24191. // a grabbable compound node below the ele => no passthrough panning
  24192. for (var i = 0; downs && i < downs.length; i++) {
  24193. var down = downs[i];
  24194. //if any parent node in event hierarchy isn't pannable, reject passthrough
  24195. if (down.isNode() && down.isParent() && !down.pannable()) {
  24196. allowPassthrough = false;
  24197. break;
  24198. }
  24199. }
  24200. } else {
  24201. allowPassthrough = true;
  24202. }
  24203. return allowPassthrough;
  24204. };
  24205. var setGrabbed = function setGrabbed(ele) {
  24206. ele[0]._private.grabbed = true;
  24207. };
  24208. var setFreed = function setFreed(ele) {
  24209. ele[0]._private.grabbed = false;
  24210. };
  24211. var setInDragLayer = function setInDragLayer(ele) {
  24212. ele[0]._private.rscratch.inDragLayer = true;
  24213. };
  24214. var setOutDragLayer = function setOutDragLayer(ele) {
  24215. ele[0]._private.rscratch.inDragLayer = false;
  24216. };
  24217. var setGrabTarget = function setGrabTarget(ele) {
  24218. ele[0]._private.rscratch.isGrabTarget = true;
  24219. };
  24220. var removeGrabTarget = function removeGrabTarget(ele) {
  24221. ele[0]._private.rscratch.isGrabTarget = false;
  24222. };
  24223. var addToDragList = function addToDragList(ele, opts) {
  24224. var list = opts.addToList;
  24225. var listHasEle = list.has(ele);
  24226. if (!listHasEle && ele.grabbable() && !ele.locked()) {
  24227. list.merge(ele);
  24228. setGrabbed(ele);
  24229. }
  24230. };
  24231. // helper function to determine which child nodes and inner edges
  24232. // of a compound node to be dragged as well as the grabbed and selected nodes
  24233. var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {
  24234. if (!node.cy().hasCompoundNodes()) {
  24235. return;
  24236. }
  24237. if (opts.inDragLayer == null && opts.addToList == null) {
  24238. return;
  24239. } // nothing to do
  24240. var innerNodes = node.descendants();
  24241. if (opts.inDragLayer) {
  24242. innerNodes.forEach(setInDragLayer);
  24243. innerNodes.connectedEdges().forEach(setInDragLayer);
  24244. }
  24245. if (opts.addToList) {
  24246. addToDragList(innerNodes, opts);
  24247. }
  24248. };
  24249. // adds the given nodes and its neighbourhood to the drag layer
  24250. var addNodesToDrag = function addNodesToDrag(nodes, opts) {
  24251. opts = opts || {};
  24252. var hasCompoundNodes = nodes.cy().hasCompoundNodes();
  24253. if (opts.inDragLayer) {
  24254. nodes.forEach(setInDragLayer);
  24255. nodes.neighborhood().stdFilter(function (ele) {
  24256. return !hasCompoundNodes || ele.isEdge();
  24257. }).forEach(setInDragLayer);
  24258. }
  24259. if (opts.addToList) {
  24260. nodes.forEach(function (ele) {
  24261. addToDragList(ele, opts);
  24262. });
  24263. }
  24264. addDescendantsToDrag(nodes, opts); // always add to drag
  24265. // also add nodes and edges related to the topmost ancestor
  24266. updateAncestorsInDragLayer(nodes, {
  24267. inDragLayer: opts.inDragLayer
  24268. });
  24269. r.updateCachedGrabbedEles();
  24270. };
  24271. var addNodeToDrag = addNodesToDrag;
  24272. var freeDraggedElements = function freeDraggedElements(grabbedEles) {
  24273. if (!grabbedEles) {
  24274. return;
  24275. }
  24276. // just go over all elements rather than doing a bunch of (possibly expensive) traversals
  24277. r.getCachedZSortedEles().forEach(function (ele) {
  24278. setFreed(ele);
  24279. setOutDragLayer(ele);
  24280. removeGrabTarget(ele);
  24281. });
  24282. r.updateCachedGrabbedEles();
  24283. };
  24284. // helper function to determine which ancestor nodes and edges should go
  24285. // to the drag layer (or should be removed from drag layer).
  24286. var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {
  24287. if (opts.inDragLayer == null && opts.addToList == null) {
  24288. return;
  24289. } // nothing to do
  24290. if (!node.cy().hasCompoundNodes()) {
  24291. return;
  24292. }
  24293. // find top-level parent
  24294. var parent = node.ancestors().orphans();
  24295. // no parent node: no nodes to add to the drag layer
  24296. if (parent.same(node)) {
  24297. return;
  24298. }
  24299. var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());
  24300. var edges = nodes.connectedEdges();
  24301. if (opts.inDragLayer) {
  24302. edges.forEach(setInDragLayer);
  24303. nodes.forEach(setInDragLayer);
  24304. }
  24305. if (opts.addToList) {
  24306. nodes.forEach(function (ele) {
  24307. addToDragList(ele, opts);
  24308. });
  24309. }
  24310. };
  24311. var blurActiveDomElement = function blurActiveDomElement() {
  24312. if (document.activeElement != null && document.activeElement.blur != null) {
  24313. document.activeElement.blur();
  24314. }
  24315. };
  24316. var haveMutationsApi = typeof MutationObserver !== 'undefined';
  24317. var haveResizeObserverApi = typeof ResizeObserver !== 'undefined';
  24318. // watch for when the cy container is removed from the dom
  24319. if (haveMutationsApi) {
  24320. r.removeObserver = new MutationObserver(function (mutns) {
  24321. // eslint-disable-line no-undef
  24322. for (var i = 0; i < mutns.length; i++) {
  24323. var mutn = mutns[i];
  24324. var rNodes = mutn.removedNodes;
  24325. if (rNodes) {
  24326. for (var j = 0; j < rNodes.length; j++) {
  24327. var rNode = rNodes[j];
  24328. if (rNode === r.container) {
  24329. r.destroy();
  24330. break;
  24331. }
  24332. }
  24333. }
  24334. }
  24335. });
  24336. if (r.container.parentNode) {
  24337. r.removeObserver.observe(r.container.parentNode, {
  24338. childList: true
  24339. });
  24340. }
  24341. } else {
  24342. r.registerBinding(r.container, 'DOMNodeRemoved', function (e) {
  24343. // eslint-disable-line no-unused-vars
  24344. r.destroy();
  24345. });
  24346. }
  24347. var onResize = debounce(function () {
  24348. r.cy.resize();
  24349. }, 100);
  24350. if (haveMutationsApi) {
  24351. r.styleObserver = new MutationObserver(onResize); // eslint-disable-line no-undef
  24352. r.styleObserver.observe(r.container, {
  24353. attributes: true
  24354. });
  24355. }
  24356. // auto resize
  24357. r.registerBinding(containerWindow, 'resize', onResize); // eslint-disable-line no-undef
  24358. if (haveResizeObserverApi) {
  24359. r.resizeObserver = new ResizeObserver(onResize); // eslint-disable-line no-undef
  24360. r.resizeObserver.observe(r.container);
  24361. }
  24362. var forEachUp = function forEachUp(domEle, fn) {
  24363. while (domEle != null) {
  24364. fn(domEle);
  24365. domEle = domEle.parentNode;
  24366. }
  24367. };
  24368. var invalidateCoords = function invalidateCoords() {
  24369. r.invalidateContainerClientCoordsCache();
  24370. };
  24371. forEachUp(r.container, function (domEle) {
  24372. r.registerBinding(domEle, 'transitionend', invalidateCoords);
  24373. r.registerBinding(domEle, 'animationend', invalidateCoords);
  24374. r.registerBinding(domEle, 'scroll', invalidateCoords);
  24375. });
  24376. // stop right click menu from appearing on cy
  24377. r.registerBinding(r.container, 'contextmenu', function (e) {
  24378. e.preventDefault();
  24379. });
  24380. var inBoxSelection = function inBoxSelection() {
  24381. return r.selection[4] !== 0;
  24382. };
  24383. var eventInContainer = function eventInContainer(e) {
  24384. // save cycles if mouse events aren't to be captured
  24385. var containerPageCoords = r.findContainerClientCoords();
  24386. var x = containerPageCoords[0];
  24387. var y = containerPageCoords[1];
  24388. var width = containerPageCoords[2];
  24389. var height = containerPageCoords[3];
  24390. var positions = e.touches ? e.touches : [e];
  24391. var atLeastOnePosInside = false;
  24392. for (var i = 0; i < positions.length; i++) {
  24393. var p = positions[i];
  24394. if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {
  24395. atLeastOnePosInside = true;
  24396. break;
  24397. }
  24398. }
  24399. if (!atLeastOnePosInside) {
  24400. return false;
  24401. }
  24402. var container = r.container;
  24403. var target = e.target;
  24404. var tParent = target.parentNode;
  24405. var containerIsTarget = false;
  24406. while (tParent) {
  24407. if (tParent === container) {
  24408. containerIsTarget = true;
  24409. break;
  24410. }
  24411. tParent = tParent.parentNode;
  24412. }
  24413. if (!containerIsTarget) {
  24414. return false;
  24415. } // if target is outisde cy container, then this event is not for us
  24416. return true;
  24417. };
  24418. // Primary key
  24419. r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {
  24420. if (!eventInContainer(e)) {
  24421. return;
  24422. }
  24423. // during left mouse button gestures, ignore other buttons
  24424. if (r.hoverData.which === 1 && e.which !== 1) {
  24425. return;
  24426. }
  24427. e.preventDefault();
  24428. blurActiveDomElement();
  24429. r.hoverData.capture = true;
  24430. r.hoverData.which = e.which;
  24431. var cy = r.cy;
  24432. var gpos = [e.clientX, e.clientY];
  24433. var pos = r.projectIntoViewport(gpos[0], gpos[1]);
  24434. var select = r.selection;
  24435. var nears = r.findNearestElements(pos[0], pos[1], true, false);
  24436. var near = nears[0];
  24437. var draggedElements = r.dragData.possibleDragElements;
  24438. r.hoverData.mdownPos = pos;
  24439. r.hoverData.mdownGPos = gpos;
  24440. var makeEvent = function makeEvent(type) {
  24441. return {
  24442. originalEvent: e,
  24443. type: type,
  24444. position: {
  24445. x: pos[0],
  24446. y: pos[1]
  24447. }
  24448. };
  24449. };
  24450. var checkForTaphold = function checkForTaphold() {
  24451. r.hoverData.tapholdCancelled = false;
  24452. clearTimeout(r.hoverData.tapholdTimeout);
  24453. r.hoverData.tapholdTimeout = setTimeout(function () {
  24454. if (r.hoverData.tapholdCancelled) {
  24455. return;
  24456. } else {
  24457. var ele = r.hoverData.down;
  24458. if (ele) {
  24459. ele.emit(makeEvent('taphold'));
  24460. } else {
  24461. cy.emit(makeEvent('taphold'));
  24462. }
  24463. }
  24464. }, r.tapholdDuration);
  24465. };
  24466. // Right click button
  24467. if (e.which == 3) {
  24468. r.hoverData.cxtStarted = true;
  24469. var cxtEvt = {
  24470. originalEvent: e,
  24471. type: 'cxttapstart',
  24472. position: {
  24473. x: pos[0],
  24474. y: pos[1]
  24475. }
  24476. };
  24477. if (near) {
  24478. near.activate();
  24479. near.emit(cxtEvt);
  24480. r.hoverData.down = near;
  24481. } else {
  24482. cy.emit(cxtEvt);
  24483. }
  24484. r.hoverData.downTime = new Date().getTime();
  24485. r.hoverData.cxtDragged = false;
  24486. // Primary button
  24487. } else if (e.which == 1) {
  24488. if (near) {
  24489. near.activate();
  24490. }
  24491. // Element dragging
  24492. {
  24493. // If something is under the cursor and it is draggable, prepare to grab it
  24494. if (near != null) {
  24495. if (r.nodeIsGrabbable(near)) {
  24496. var triggerGrab = function triggerGrab(ele) {
  24497. ele.emit(makeEvent('grab'));
  24498. };
  24499. setGrabTarget(near);
  24500. if (!near.selected()) {
  24501. draggedElements = r.dragData.possibleDragElements = cy.collection();
  24502. addNodeToDrag(near, {
  24503. addToList: draggedElements
  24504. });
  24505. near.emit(makeEvent('grabon')).emit(makeEvent('grab'));
  24506. } else {
  24507. draggedElements = r.dragData.possibleDragElements = cy.collection();
  24508. var selectedNodes = cy.$(function (ele) {
  24509. return ele.isNode() && ele.selected() && r.nodeIsGrabbable(ele);
  24510. });
  24511. addNodesToDrag(selectedNodes, {
  24512. addToList: draggedElements
  24513. });
  24514. near.emit(makeEvent('grabon'));
  24515. selectedNodes.forEach(triggerGrab);
  24516. }
  24517. r.redrawHint('eles', true);
  24518. r.redrawHint('drag', true);
  24519. }
  24520. }
  24521. r.hoverData.down = near;
  24522. r.hoverData.downs = nears;
  24523. r.hoverData.downTime = new Date().getTime();
  24524. }
  24525. triggerEvents(near, ['mousedown', 'tapstart', 'vmousedown'], e, {
  24526. x: pos[0],
  24527. y: pos[1]
  24528. });
  24529. if (near == null) {
  24530. select[4] = 1;
  24531. r.data.bgActivePosistion = {
  24532. x: pos[0],
  24533. y: pos[1]
  24534. };
  24535. r.redrawHint('select', true);
  24536. r.redraw();
  24537. } else if (near.pannable()) {
  24538. select[4] = 1; // for future pan
  24539. }
  24540. checkForTaphold();
  24541. }
  24542. // Initialize selection box coordinates
  24543. select[0] = select[2] = pos[0];
  24544. select[1] = select[3] = pos[1];
  24545. }, false);
  24546. var shadowRoot = getShadowRoot(r.container);
  24547. r.registerBinding([containerWindow, shadowRoot], 'mousemove', function mousemoveHandler(e) {
  24548. // eslint-disable-line no-undef
  24549. var capture = r.hoverData.capture;
  24550. if (!capture && !eventInContainer(e)) {
  24551. return;
  24552. }
  24553. var preventDefault = false;
  24554. var cy = r.cy;
  24555. var zoom = cy.zoom();
  24556. var gpos = [e.clientX, e.clientY];
  24557. var pos = r.projectIntoViewport(gpos[0], gpos[1]);
  24558. var mdownPos = r.hoverData.mdownPos;
  24559. var mdownGPos = r.hoverData.mdownGPos;
  24560. var select = r.selection;
  24561. var near = null;
  24562. if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {
  24563. near = r.findNearestElement(pos[0], pos[1], true, false);
  24564. }
  24565. var last = r.hoverData.last;
  24566. var down = r.hoverData.down;
  24567. var disp = [pos[0] - select[2], pos[1] - select[3]];
  24568. var draggedElements = r.dragData.possibleDragElements;
  24569. var isOverThresholdDrag;
  24570. if (mdownGPos) {
  24571. var dx = gpos[0] - mdownGPos[0];
  24572. var dx2 = dx * dx;
  24573. var dy = gpos[1] - mdownGPos[1];
  24574. var dy2 = dy * dy;
  24575. var dist2 = dx2 + dy2;
  24576. r.hoverData.isOverThresholdDrag = isOverThresholdDrag = dist2 >= r.desktopTapThreshold2;
  24577. }
  24578. var multSelKeyDown = isMultSelKeyDown(e);
  24579. if (isOverThresholdDrag) {
  24580. r.hoverData.tapholdCancelled = true;
  24581. }
  24582. var updateDragDelta = function updateDragDelta() {
  24583. var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];
  24584. if (dragDelta.length === 0) {
  24585. dragDelta.push(disp[0]);
  24586. dragDelta.push(disp[1]);
  24587. } else {
  24588. dragDelta[0] += disp[0];
  24589. dragDelta[1] += disp[1];
  24590. }
  24591. };
  24592. preventDefault = true;
  24593. triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {
  24594. x: pos[0],
  24595. y: pos[1]
  24596. });
  24597. var makeEvent = function makeEvent(type) {
  24598. return {
  24599. originalEvent: e,
  24600. type: type,
  24601. position: {
  24602. x: pos[0],
  24603. y: pos[1]
  24604. }
  24605. };
  24606. };
  24607. var goIntoBoxMode = function goIntoBoxMode() {
  24608. r.data.bgActivePosistion = undefined;
  24609. if (!r.hoverData.selecting) {
  24610. cy.emit(makeEvent('boxstart'));
  24611. }
  24612. select[4] = 1;
  24613. r.hoverData.selecting = true;
  24614. r.redrawHint('select', true);
  24615. r.redraw();
  24616. };
  24617. // trigger context drag if rmouse down
  24618. if (r.hoverData.which === 3) {
  24619. // but only if over threshold
  24620. if (isOverThresholdDrag) {
  24621. var cxtEvt = makeEvent('cxtdrag');
  24622. if (down) {
  24623. down.emit(cxtEvt);
  24624. } else {
  24625. cy.emit(cxtEvt);
  24626. }
  24627. r.hoverData.cxtDragged = true;
  24628. if (!r.hoverData.cxtOver || near !== r.hoverData.cxtOver) {
  24629. if (r.hoverData.cxtOver) {
  24630. r.hoverData.cxtOver.emit(makeEvent('cxtdragout'));
  24631. }
  24632. r.hoverData.cxtOver = near;
  24633. if (near) {
  24634. near.emit(makeEvent('cxtdragover'));
  24635. }
  24636. }
  24637. }
  24638. // Check if we are drag panning the entire graph
  24639. } else if (r.hoverData.dragging) {
  24640. preventDefault = true;
  24641. if (cy.panningEnabled() && cy.userPanningEnabled()) {
  24642. var deltaP;
  24643. if (r.hoverData.justStartedPan) {
  24644. var mdPos = r.hoverData.mdownPos;
  24645. deltaP = {
  24646. x: (pos[0] - mdPos[0]) * zoom,
  24647. y: (pos[1] - mdPos[1]) * zoom
  24648. };
  24649. r.hoverData.justStartedPan = false;
  24650. } else {
  24651. deltaP = {
  24652. x: disp[0] * zoom,
  24653. y: disp[1] * zoom
  24654. };
  24655. }
  24656. cy.panBy(deltaP);
  24657. cy.emit(makeEvent('dragpan'));
  24658. r.hoverData.dragged = true;
  24659. }
  24660. // Needs reproject due to pan changing viewport
  24661. pos = r.projectIntoViewport(e.clientX, e.clientY);
  24662. // Checks primary button down & out of time & mouse not moved much
  24663. } else if (select[4] == 1 && (down == null || down.pannable())) {
  24664. if (isOverThresholdDrag) {
  24665. if (!r.hoverData.dragging && cy.boxSelectionEnabled() && (multSelKeyDown || !cy.panningEnabled() || !cy.userPanningEnabled())) {
  24666. goIntoBoxMode();
  24667. } else if (!r.hoverData.selecting && cy.panningEnabled() && cy.userPanningEnabled()) {
  24668. var allowPassthrough = allowPanningPassthrough(down, r.hoverData.downs);
  24669. if (allowPassthrough) {
  24670. r.hoverData.dragging = true;
  24671. r.hoverData.justStartedPan = true;
  24672. select[4] = 0;
  24673. r.data.bgActivePosistion = array2point(mdownPos);
  24674. r.redrawHint('select', true);
  24675. r.redraw();
  24676. }
  24677. }
  24678. if (down && down.pannable() && down.active()) {
  24679. down.unactivate();
  24680. }
  24681. }
  24682. } else {
  24683. if (down && down.pannable() && down.active()) {
  24684. down.unactivate();
  24685. }
  24686. if ((!down || !down.grabbed()) && near != last) {
  24687. if (last) {
  24688. triggerEvents(last, ['mouseout', 'tapdragout'], e, {
  24689. x: pos[0],
  24690. y: pos[1]
  24691. });
  24692. }
  24693. if (near) {
  24694. triggerEvents(near, ['mouseover', 'tapdragover'], e, {
  24695. x: pos[0],
  24696. y: pos[1]
  24697. });
  24698. }
  24699. r.hoverData.last = near;
  24700. }
  24701. if (down) {
  24702. if (isOverThresholdDrag) {
  24703. // then we can take action
  24704. if (cy.boxSelectionEnabled() && multSelKeyDown) {
  24705. // then selection overrides
  24706. if (down && down.grabbed()) {
  24707. freeDraggedElements(draggedElements);
  24708. down.emit(makeEvent('freeon'));
  24709. draggedElements.emit(makeEvent('free'));
  24710. if (r.dragData.didDrag) {
  24711. down.emit(makeEvent('dragfreeon'));
  24712. draggedElements.emit(makeEvent('dragfree'));
  24713. }
  24714. }
  24715. goIntoBoxMode();
  24716. } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {
  24717. // drag node
  24718. var justStartedDrag = !r.dragData.didDrag;
  24719. if (justStartedDrag) {
  24720. r.redrawHint('eles', true);
  24721. }
  24722. r.dragData.didDrag = true; // indicate that we actually did drag the node
  24723. // now, add the elements to the drag layer if not done already
  24724. if (!r.hoverData.draggingEles) {
  24725. addNodesToDrag(draggedElements, {
  24726. inDragLayer: true
  24727. });
  24728. }
  24729. var totalShift = {
  24730. x: 0,
  24731. y: 0
  24732. };
  24733. if (number$1(disp[0]) && number$1(disp[1])) {
  24734. totalShift.x += disp[0];
  24735. totalShift.y += disp[1];
  24736. if (justStartedDrag) {
  24737. var dragDelta = r.hoverData.dragDelta;
  24738. if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
  24739. totalShift.x += dragDelta[0];
  24740. totalShift.y += dragDelta[1];
  24741. }
  24742. }
  24743. }
  24744. r.hoverData.draggingEles = true;
  24745. draggedElements.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
  24746. r.redrawHint('drag', true);
  24747. r.redraw();
  24748. }
  24749. } else {
  24750. // otherwise save drag delta for when we actually start dragging so the relative grab pos is constant
  24751. updateDragDelta();
  24752. }
  24753. }
  24754. // prevent the dragging from triggering text selection on the page
  24755. preventDefault = true;
  24756. }
  24757. select[2] = pos[0];
  24758. select[3] = pos[1];
  24759. if (preventDefault) {
  24760. if (e.stopPropagation) e.stopPropagation();
  24761. if (e.preventDefault) e.preventDefault();
  24762. return false;
  24763. }
  24764. }, false);
  24765. var clickTimeout, didDoubleClick, prevClickTimeStamp;
  24766. r.registerBinding(containerWindow, 'mouseup', function mouseupHandler(e) {
  24767. // eslint-disable-line no-undef
  24768. // during left mouse button gestures, ignore other buttons
  24769. if (r.hoverData.which === 1 && e.which !== 1 && r.hoverData.capture) {
  24770. return;
  24771. }
  24772. var capture = r.hoverData.capture;
  24773. if (!capture) {
  24774. return;
  24775. }
  24776. r.hoverData.capture = false;
  24777. var cy = r.cy;
  24778. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  24779. var select = r.selection;
  24780. var near = r.findNearestElement(pos[0], pos[1], true, false);
  24781. var draggedElements = r.dragData.possibleDragElements;
  24782. var down = r.hoverData.down;
  24783. var multSelKeyDown = isMultSelKeyDown(e);
  24784. if (r.data.bgActivePosistion) {
  24785. r.redrawHint('select', true);
  24786. r.redraw();
  24787. }
  24788. r.hoverData.tapholdCancelled = true;
  24789. r.data.bgActivePosistion = undefined; // not active bg now
  24790. if (down) {
  24791. down.unactivate();
  24792. }
  24793. var makeEvent = function makeEvent(type) {
  24794. return {
  24795. originalEvent: e,
  24796. type: type,
  24797. position: {
  24798. x: pos[0],
  24799. y: pos[1]
  24800. }
  24801. };
  24802. };
  24803. if (r.hoverData.which === 3) {
  24804. var cxtEvt = makeEvent('cxttapend');
  24805. if (down) {
  24806. down.emit(cxtEvt);
  24807. } else {
  24808. cy.emit(cxtEvt);
  24809. }
  24810. if (!r.hoverData.cxtDragged) {
  24811. var cxtTap = makeEvent('cxttap');
  24812. if (down) {
  24813. down.emit(cxtTap);
  24814. } else {
  24815. cy.emit(cxtTap);
  24816. }
  24817. }
  24818. r.hoverData.cxtDragged = false;
  24819. r.hoverData.which = null;
  24820. } else if (r.hoverData.which === 1) {
  24821. triggerEvents(near, ['mouseup', 'tapend', 'vmouseup'], e, {
  24822. x: pos[0],
  24823. y: pos[1]
  24824. });
  24825. if (!r.dragData.didDrag &&
  24826. // didn't move a node around
  24827. !r.hoverData.dragged &&
  24828. // didn't pan
  24829. !r.hoverData.selecting &&
  24830. // not box selection
  24831. !r.hoverData.isOverThresholdDrag // didn't move too much
  24832. ) {
  24833. triggerEvents(down, ["click", "tap", "vclick"], e, {
  24834. x: pos[0],
  24835. y: pos[1]
  24836. });
  24837. didDoubleClick = false;
  24838. if (e.timeStamp - prevClickTimeStamp <= cy.multiClickDebounceTime()) {
  24839. clickTimeout && clearTimeout(clickTimeout);
  24840. didDoubleClick = true;
  24841. prevClickTimeStamp = null;
  24842. triggerEvents(down, ["dblclick", "dbltap", "vdblclick"], e, {
  24843. x: pos[0],
  24844. y: pos[1]
  24845. });
  24846. } else {
  24847. clickTimeout = setTimeout(function () {
  24848. if (didDoubleClick) return;
  24849. triggerEvents(down, ["oneclick", "onetap", "voneclick"], e, {
  24850. x: pos[0],
  24851. y: pos[1]
  24852. });
  24853. }, cy.multiClickDebounceTime());
  24854. prevClickTimeStamp = e.timeStamp;
  24855. }
  24856. }
  24857. // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something
  24858. if (down == null // not mousedown on node
  24859. && !r.dragData.didDrag // didn't move the node around
  24860. && !r.hoverData.selecting // not box selection
  24861. && !r.hoverData.dragged // didn't pan
  24862. && !isMultSelKeyDown(e)) {
  24863. cy.$(isSelected).unselect(['tapunselect']);
  24864. if (draggedElements.length > 0) {
  24865. r.redrawHint('eles', true);
  24866. }
  24867. r.dragData.possibleDragElements = draggedElements = cy.collection();
  24868. }
  24869. // Single selection
  24870. if (near == down && !r.dragData.didDrag && !r.hoverData.selecting) {
  24871. if (near != null && near._private.selectable) {
  24872. if (r.hoverData.dragging) ; else if (cy.selectionType() === 'additive' || multSelKeyDown) {
  24873. if (near.selected()) {
  24874. near.unselect(['tapunselect']);
  24875. } else {
  24876. near.select(['tapselect']);
  24877. }
  24878. } else {
  24879. if (!multSelKeyDown) {
  24880. cy.$(isSelected).unmerge(near).unselect(['tapunselect']);
  24881. near.select(['tapselect']);
  24882. }
  24883. }
  24884. r.redrawHint('eles', true);
  24885. }
  24886. }
  24887. if (r.hoverData.selecting) {
  24888. var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
  24889. r.redrawHint('select', true);
  24890. if (box.length > 0) {
  24891. r.redrawHint('eles', true);
  24892. }
  24893. cy.emit(makeEvent('boxend'));
  24894. var eleWouldBeSelected = function eleWouldBeSelected(ele) {
  24895. return ele.selectable() && !ele.selected();
  24896. };
  24897. if (cy.selectionType() === 'additive') {
  24898. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  24899. } else {
  24900. if (!multSelKeyDown) {
  24901. cy.$(isSelected).unmerge(box).unselect();
  24902. }
  24903. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  24904. }
  24905. // always need redraw in case eles unselectable
  24906. r.redraw();
  24907. }
  24908. // Cancel drag pan
  24909. if (r.hoverData.dragging) {
  24910. r.hoverData.dragging = false;
  24911. r.redrawHint('select', true);
  24912. r.redrawHint('eles', true);
  24913. r.redraw();
  24914. }
  24915. if (!select[4]) {
  24916. r.redrawHint('drag', true);
  24917. r.redrawHint('eles', true);
  24918. var downWasGrabbed = down && down.grabbed();
  24919. freeDraggedElements(draggedElements);
  24920. if (downWasGrabbed) {
  24921. down.emit(makeEvent('freeon'));
  24922. draggedElements.emit(makeEvent('free'));
  24923. if (r.dragData.didDrag) {
  24924. down.emit(makeEvent('dragfreeon'));
  24925. draggedElements.emit(makeEvent('dragfree'));
  24926. }
  24927. }
  24928. }
  24929. } // else not right mouse
  24930. select[4] = 0;
  24931. r.hoverData.down = null;
  24932. r.hoverData.cxtStarted = false;
  24933. r.hoverData.draggingEles = false;
  24934. r.hoverData.selecting = false;
  24935. r.hoverData.isOverThresholdDrag = false;
  24936. r.dragData.didDrag = false;
  24937. r.hoverData.dragged = false;
  24938. r.hoverData.dragDelta = [];
  24939. r.hoverData.mdownPos = null;
  24940. r.hoverData.mdownGPos = null;
  24941. r.hoverData.which = null;
  24942. }, false);
  24943. var wheelDeltas = []; // log of first N wheel deltas
  24944. var wheelDeltaN = 4; // how many events to log
  24945. var inaccurateScrollDevice;
  24946. var inaccurateScrollFactor = 100000; // base of inaccurate wheel deltas (e.g. base 5 could yield wheels of 10, 25, 50, etc.)
  24947. var allAreDivisibleBy = function allAreDivisibleBy(list, factor) {
  24948. for (var i = 0; i < list.length; i++) {
  24949. if (list[i] % factor !== 0) {
  24950. return false;
  24951. }
  24952. }
  24953. return true;
  24954. };
  24955. var allAreSameMagnitude = function allAreSameMagnitude(list) {
  24956. var firstMag = Math.abs(list[0]);
  24957. for (var i = 1; i < list.length; i++) {
  24958. if (Math.abs(list[i]) !== firstMag) {
  24959. return false;
  24960. }
  24961. }
  24962. return true;
  24963. };
  24964. var wheelHandler = function wheelHandler(e) {
  24965. var clamp = false;
  24966. var delta = e.deltaY;
  24967. if (delta == null) {
  24968. // compatibility with old browsers
  24969. if (e.wheelDeltaY != null) {
  24970. delta = e.wheelDeltaY / 4;
  24971. } else if (e.wheelDelta != null) {
  24972. delta = e.wheelDelta / 4;
  24973. }
  24974. }
  24975. if (delta === 0) {
  24976. return; // no change in zoom (Bug: Zoom becomes erratic on rapid scroll due to deltaY: 0 event #3394)
  24977. }
  24978. if (inaccurateScrollDevice == null) {
  24979. if (wheelDeltas.length >= wheelDeltaN) {
  24980. // use log to determine if inaccurate
  24981. var wds = wheelDeltas;
  24982. inaccurateScrollDevice = allAreDivisibleBy(wds, 5);
  24983. if (!inaccurateScrollDevice) {
  24984. // check for all large values of exact same magnitude
  24985. var firstMag = Math.abs(wds[0]);
  24986. inaccurateScrollDevice = allAreSameMagnitude(wds) && firstMag > 5;
  24987. }
  24988. if (inaccurateScrollDevice) {
  24989. for (var i = 0; i < wds.length; i++) {
  24990. inaccurateScrollFactor = Math.min(Math.abs(wds[i]), inaccurateScrollFactor);
  24991. }
  24992. }
  24993. // console.log('Sampled wheel deltas:', wds);
  24994. // console.log('inaccurateScrollDevice:', inaccurateScrollDevice);
  24995. // console.log('inaccurateScrollFactor:', inaccurateScrollFactor);
  24996. } else {
  24997. // clamp and log until we reach N
  24998. wheelDeltas.push(delta);
  24999. clamp = true;
  25000. // console.log('Clamping initial wheel events until we get a good sample');
  25001. }
  25002. } else if (inaccurateScrollDevice) {
  25003. // keep updating
  25004. inaccurateScrollFactor = Math.min(Math.abs(delta), inaccurateScrollFactor);
  25005. // console.log('Keep updating inaccurateScrollFactor beyond sample in case we did not get the smallest possible val:', inaccurateScrollFactor);
  25006. }
  25007. if (r.scrollingPage) {
  25008. return;
  25009. } // while scrolling, ignore wheel-to-zoom
  25010. var cy = r.cy;
  25011. var zoom = cy.zoom();
  25012. var pan = cy.pan();
  25013. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25014. var rpos = [pos[0] * zoom + pan.x, pos[1] * zoom + pan.y];
  25015. if (r.hoverData.draggingEles || r.hoverData.dragging || r.hoverData.cxtStarted || inBoxSelection()) {
  25016. // if pan dragging or cxt dragging, wheel movements make no zoom
  25017. e.preventDefault();
  25018. return;
  25019. }
  25020. if (cy.panningEnabled() && cy.userPanningEnabled() && cy.zoomingEnabled() && cy.userZoomingEnabled()) {
  25021. e.preventDefault();
  25022. r.data.wheelZooming = true;
  25023. clearTimeout(r.data.wheelTimeout);
  25024. r.data.wheelTimeout = setTimeout(function () {
  25025. r.data.wheelZooming = false;
  25026. r.redrawHint('eles', true);
  25027. r.redraw();
  25028. }, 150);
  25029. var diff;
  25030. if (clamp && Math.abs(delta) > 5) {
  25031. delta = signum(delta) * 5;
  25032. }
  25033. diff = delta / -250;
  25034. if (inaccurateScrollDevice) {
  25035. diff /= inaccurateScrollFactor;
  25036. diff *= 3;
  25037. }
  25038. diff = diff * r.wheelSensitivity;
  25039. // console.log(`delta = ${delta}, diff = ${diff}, mode = ${e.deltaMode}`)
  25040. var needsWheelFix = e.deltaMode === 1;
  25041. if (needsWheelFix) {
  25042. // fixes slow wheel events on ff/linux and ff/windows
  25043. diff *= 33;
  25044. }
  25045. var newZoom = cy.zoom() * Math.pow(10, diff);
  25046. if (e.type === 'gesturechange') {
  25047. newZoom = r.gestureStartZoom * e.scale;
  25048. }
  25049. cy.zoom({
  25050. level: newZoom,
  25051. renderedPosition: {
  25052. x: rpos[0],
  25053. y: rpos[1]
  25054. }
  25055. });
  25056. cy.emit({
  25057. type: e.type === 'gesturechange' ? 'pinchzoom' : 'scrollzoom',
  25058. originalEvent: e,
  25059. position: {
  25060. x: pos[0],
  25061. y: pos[1]
  25062. }
  25063. });
  25064. }
  25065. };
  25066. // Functions to help with whether mouse wheel should trigger zooming
  25067. // --
  25068. r.registerBinding(r.container, 'wheel', wheelHandler, true);
  25069. // disable nonstandard wheel events
  25070. // r.registerBinding(r.container, 'mousewheel', wheelHandler, true);
  25071. // r.registerBinding(r.container, 'DOMMouseScroll', wheelHandler, true);
  25072. // r.registerBinding(r.container, 'MozMousePixelScroll', wheelHandler, true); // older firefox
  25073. r.registerBinding(containerWindow, 'scroll', function scrollHandler(e) {
  25074. // eslint-disable-line no-unused-vars
  25075. r.scrollingPage = true;
  25076. clearTimeout(r.scrollingPageTimeout);
  25077. r.scrollingPageTimeout = setTimeout(function () {
  25078. r.scrollingPage = false;
  25079. }, 250);
  25080. }, true);
  25081. // desktop safari pinch to zoom start
  25082. r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {
  25083. r.gestureStartZoom = r.cy.zoom();
  25084. if (!r.hasTouchStarted) {
  25085. // don't affect touch devices like iphone
  25086. e.preventDefault();
  25087. }
  25088. }, true);
  25089. r.registerBinding(r.container, 'gesturechange', function (e) {
  25090. if (!r.hasTouchStarted) {
  25091. // don't affect touch devices like iphone
  25092. wheelHandler(e);
  25093. }
  25094. }, true);
  25095. // Functions to help with handling mouseout/mouseover on the Cytoscape container
  25096. // Handle mouseout on Cytoscape container
  25097. r.registerBinding(r.container, 'mouseout', function mouseOutHandler(e) {
  25098. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25099. r.cy.emit({
  25100. originalEvent: e,
  25101. type: 'mouseout',
  25102. position: {
  25103. x: pos[0],
  25104. y: pos[1]
  25105. }
  25106. });
  25107. }, false);
  25108. r.registerBinding(r.container, 'mouseover', function mouseOverHandler(e) {
  25109. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25110. r.cy.emit({
  25111. originalEvent: e,
  25112. type: 'mouseover',
  25113. position: {
  25114. x: pos[0],
  25115. y: pos[1]
  25116. }
  25117. });
  25118. }, false);
  25119. var f1x1, f1y1, f2x1, f2y1; // starting points for pinch-to-zoom
  25120. var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom
  25121. var center1, modelCenter1; // center point on start pinch to zoom
  25122. var offsetLeft, offsetTop;
  25123. var containerWidth, containerHeight;
  25124. var twoFingersStartInside;
  25125. var distance = function distance(x1, y1, x2, y2) {
  25126. return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  25127. };
  25128. var distanceSq = function distanceSq(x1, y1, x2, y2) {
  25129. return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
  25130. };
  25131. var touchstartHandler;
  25132. r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {
  25133. r.hasTouchStarted = true;
  25134. if (!eventInContainer(e)) {
  25135. return;
  25136. }
  25137. blurActiveDomElement();
  25138. r.touchData.capture = true;
  25139. r.data.bgActivePosistion = undefined;
  25140. var cy = r.cy;
  25141. var now = r.touchData.now;
  25142. var earlier = r.touchData.earlier;
  25143. if (e.touches[0]) {
  25144. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25145. now[0] = pos[0];
  25146. now[1] = pos[1];
  25147. }
  25148. if (e.touches[1]) {
  25149. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25150. now[2] = pos[0];
  25151. now[3] = pos[1];
  25152. }
  25153. if (e.touches[2]) {
  25154. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25155. now[4] = pos[0];
  25156. now[5] = pos[1];
  25157. }
  25158. var makeEvent = function makeEvent(type) {
  25159. return {
  25160. originalEvent: e,
  25161. type: type,
  25162. position: {
  25163. x: now[0],
  25164. y: now[1]
  25165. }
  25166. };
  25167. };
  25168. // record starting points for pinch-to-zoom
  25169. if (e.touches[1]) {
  25170. r.touchData.singleTouchMoved = true;
  25171. freeDraggedElements(r.dragData.touchDragEles);
  25172. var offsets = r.findContainerClientCoords();
  25173. offsetLeft = offsets[0];
  25174. offsetTop = offsets[1];
  25175. containerWidth = offsets[2];
  25176. containerHeight = offsets[3];
  25177. f1x1 = e.touches[0].clientX - offsetLeft;
  25178. f1y1 = e.touches[0].clientY - offsetTop;
  25179. f2x1 = e.touches[1].clientX - offsetLeft;
  25180. f2y1 = e.touches[1].clientY - offsetTop;
  25181. twoFingersStartInside = 0 <= f1x1 && f1x1 <= containerWidth && 0 <= f2x1 && f2x1 <= containerWidth && 0 <= f1y1 && f1y1 <= containerHeight && 0 <= f2y1 && f2y1 <= containerHeight;
  25182. var pan = cy.pan();
  25183. var zoom = cy.zoom();
  25184. distance1 = distance(f1x1, f1y1, f2x1, f2y1);
  25185. distance1Sq = distanceSq(f1x1, f1y1, f2x1, f2y1);
  25186. center1 = [(f1x1 + f2x1) / 2, (f1y1 + f2y1) / 2];
  25187. modelCenter1 = [(center1[0] - pan.x) / zoom, (center1[1] - pan.y) / zoom];
  25188. // consider context tap
  25189. var cxtDistThreshold = 200;
  25190. var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;
  25191. if (distance1Sq < cxtDistThresholdSq && !e.touches[2]) {
  25192. var near1 = r.findNearestElement(now[0], now[1], true, true);
  25193. var near2 = r.findNearestElement(now[2], now[3], true, true);
  25194. if (near1 && near1.isNode()) {
  25195. near1.activate().emit(makeEvent('cxttapstart'));
  25196. r.touchData.start = near1;
  25197. } else if (near2 && near2.isNode()) {
  25198. near2.activate().emit(makeEvent('cxttapstart'));
  25199. r.touchData.start = near2;
  25200. } else {
  25201. cy.emit(makeEvent('cxttapstart'));
  25202. }
  25203. if (r.touchData.start) {
  25204. r.touchData.start._private.grabbed = false;
  25205. }
  25206. r.touchData.cxt = true;
  25207. r.touchData.cxtDragged = false;
  25208. r.data.bgActivePosistion = undefined;
  25209. r.redraw();
  25210. return;
  25211. }
  25212. }
  25213. if (e.touches[2]) {
  25214. // ignore
  25215. // safari on ios pans the page otherwise (normally you should be able to preventdefault on touchmove...)
  25216. if (cy.boxSelectionEnabled()) {
  25217. e.preventDefault();
  25218. }
  25219. } else if (e.touches[1]) ; else if (e.touches[0]) {
  25220. var nears = r.findNearestElements(now[0], now[1], true, true);
  25221. var near = nears[0];
  25222. if (near != null) {
  25223. near.activate();
  25224. r.touchData.start = near;
  25225. r.touchData.starts = nears;
  25226. if (r.nodeIsGrabbable(near)) {
  25227. var draggedEles = r.dragData.touchDragEles = cy.collection();
  25228. var selectedNodes = null;
  25229. r.redrawHint('eles', true);
  25230. r.redrawHint('drag', true);
  25231. if (near.selected()) {
  25232. // reset drag elements, since near will be added again
  25233. selectedNodes = cy.$(function (ele) {
  25234. return ele.selected() && r.nodeIsGrabbable(ele);
  25235. });
  25236. addNodesToDrag(selectedNodes, {
  25237. addToList: draggedEles
  25238. });
  25239. } else {
  25240. addNodeToDrag(near, {
  25241. addToList: draggedEles
  25242. });
  25243. }
  25244. setGrabTarget(near);
  25245. near.emit(makeEvent('grabon'));
  25246. if (selectedNodes) {
  25247. selectedNodes.forEach(function (n) {
  25248. n.emit(makeEvent('grab'));
  25249. });
  25250. } else {
  25251. near.emit(makeEvent('grab'));
  25252. }
  25253. }
  25254. }
  25255. triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {
  25256. x: now[0],
  25257. y: now[1]
  25258. });
  25259. if (near == null) {
  25260. r.data.bgActivePosistion = {
  25261. x: pos[0],
  25262. y: pos[1]
  25263. };
  25264. r.redrawHint('select', true);
  25265. r.redraw();
  25266. }
  25267. // Tap, taphold
  25268. // -----
  25269. r.touchData.singleTouchMoved = false;
  25270. r.touchData.singleTouchStartTime = +new Date();
  25271. clearTimeout(r.touchData.tapholdTimeout);
  25272. r.touchData.tapholdTimeout = setTimeout(function () {
  25273. if (r.touchData.singleTouchMoved === false && !r.pinching // if pinching, then taphold unselect shouldn't take effect
  25274. && !r.touchData.selecting // box selection shouldn't allow taphold through
  25275. ) {
  25276. triggerEvents(r.touchData.start, ['taphold'], e, {
  25277. x: now[0],
  25278. y: now[1]
  25279. });
  25280. }
  25281. }, r.tapholdDuration);
  25282. }
  25283. if (e.touches.length >= 1) {
  25284. var sPos = r.touchData.startPosition = [null, null, null, null, null, null];
  25285. for (var i = 0; i < now.length; i++) {
  25286. sPos[i] = earlier[i] = now[i];
  25287. }
  25288. var touch0 = e.touches[0];
  25289. r.touchData.startGPosition = [touch0.clientX, touch0.clientY];
  25290. }
  25291. }, false);
  25292. var touchmoveHandler;
  25293. r.registerBinding(containerWindow, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {
  25294. // eslint-disable-line no-undef
  25295. var capture = r.touchData.capture;
  25296. if (!capture && !eventInContainer(e)) {
  25297. return;
  25298. }
  25299. var select = r.selection;
  25300. var cy = r.cy;
  25301. var now = r.touchData.now;
  25302. var earlier = r.touchData.earlier;
  25303. var zoom = cy.zoom();
  25304. if (e.touches[0]) {
  25305. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25306. now[0] = pos[0];
  25307. now[1] = pos[1];
  25308. }
  25309. if (e.touches[1]) {
  25310. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25311. now[2] = pos[0];
  25312. now[3] = pos[1];
  25313. }
  25314. if (e.touches[2]) {
  25315. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25316. now[4] = pos[0];
  25317. now[5] = pos[1];
  25318. }
  25319. var makeEvent = function makeEvent(type) {
  25320. return {
  25321. originalEvent: e,
  25322. type: type,
  25323. position: {
  25324. x: now[0],
  25325. y: now[1]
  25326. }
  25327. };
  25328. };
  25329. var startGPos = r.touchData.startGPosition;
  25330. var isOverThresholdDrag;
  25331. if (capture && e.touches[0] && startGPos) {
  25332. var disp = [];
  25333. for (var j = 0; j < now.length; j++) {
  25334. disp[j] = now[j] - earlier[j];
  25335. }
  25336. var dx = e.touches[0].clientX - startGPos[0];
  25337. var dx2 = dx * dx;
  25338. var dy = e.touches[0].clientY - startGPos[1];
  25339. var dy2 = dy * dy;
  25340. var dist2 = dx2 + dy2;
  25341. isOverThresholdDrag = dist2 >= r.touchTapThreshold2;
  25342. }
  25343. // context swipe cancelling
  25344. if (capture && r.touchData.cxt) {
  25345. e.preventDefault();
  25346. var f1x2 = e.touches[0].clientX - offsetLeft,
  25347. f1y2 = e.touches[0].clientY - offsetTop;
  25348. var f2x2 = e.touches[1].clientX - offsetLeft,
  25349. f2y2 = e.touches[1].clientY - offsetTop;
  25350. // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );
  25351. var distance2Sq = distanceSq(f1x2, f1y2, f2x2, f2y2);
  25352. var factorSq = distance2Sq / distance1Sq;
  25353. var distThreshold = 150;
  25354. var distThresholdSq = distThreshold * distThreshold;
  25355. var factorThreshold = 1.5;
  25356. var factorThresholdSq = factorThreshold * factorThreshold;
  25357. // cancel ctx gestures if the distance b/t the fingers increases
  25358. if (factorSq >= factorThresholdSq || distance2Sq >= distThresholdSq) {
  25359. r.touchData.cxt = false;
  25360. r.data.bgActivePosistion = undefined;
  25361. r.redrawHint('select', true);
  25362. var cxtEvt = makeEvent('cxttapend');
  25363. if (r.touchData.start) {
  25364. r.touchData.start.unactivate().emit(cxtEvt);
  25365. r.touchData.start = null;
  25366. } else {
  25367. cy.emit(cxtEvt);
  25368. }
  25369. }
  25370. }
  25371. // context swipe
  25372. if (capture && r.touchData.cxt) {
  25373. var cxtEvt = makeEvent('cxtdrag');
  25374. r.data.bgActivePosistion = undefined;
  25375. r.redrawHint('select', true);
  25376. if (r.touchData.start) {
  25377. r.touchData.start.emit(cxtEvt);
  25378. } else {
  25379. cy.emit(cxtEvt);
  25380. }
  25381. if (r.touchData.start) {
  25382. r.touchData.start._private.grabbed = false;
  25383. }
  25384. r.touchData.cxtDragged = true;
  25385. var near = r.findNearestElement(now[0], now[1], true, true);
  25386. if (!r.touchData.cxtOver || near !== r.touchData.cxtOver) {
  25387. if (r.touchData.cxtOver) {
  25388. r.touchData.cxtOver.emit(makeEvent('cxtdragout'));
  25389. }
  25390. r.touchData.cxtOver = near;
  25391. if (near) {
  25392. near.emit(makeEvent('cxtdragover'));
  25393. }
  25394. }
  25395. // box selection
  25396. } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {
  25397. e.preventDefault();
  25398. r.data.bgActivePosistion = undefined;
  25399. this.lastThreeTouch = +new Date();
  25400. if (!r.touchData.selecting) {
  25401. cy.emit(makeEvent('boxstart'));
  25402. }
  25403. r.touchData.selecting = true;
  25404. r.touchData.didSelect = true;
  25405. select[4] = 1;
  25406. if (!select || select.length === 0 || select[0] === undefined) {
  25407. select[0] = (now[0] + now[2] + now[4]) / 3;
  25408. select[1] = (now[1] + now[3] + now[5]) / 3;
  25409. select[2] = (now[0] + now[2] + now[4]) / 3 + 1;
  25410. select[3] = (now[1] + now[3] + now[5]) / 3 + 1;
  25411. } else {
  25412. select[2] = (now[0] + now[2] + now[4]) / 3;
  25413. select[3] = (now[1] + now[3] + now[5]) / 3;
  25414. }
  25415. r.redrawHint('select', true);
  25416. r.redraw();
  25417. // pinch to zoom
  25418. } else if (capture && e.touches[1] && !r.touchData.didSelect // don't allow box selection to degrade to pinch-to-zoom
  25419. && cy.zoomingEnabled() && cy.panningEnabled() && cy.userZoomingEnabled() && cy.userPanningEnabled()) {
  25420. // two fingers => pinch to zoom
  25421. e.preventDefault();
  25422. r.data.bgActivePosistion = undefined;
  25423. r.redrawHint('select', true);
  25424. var draggedEles = r.dragData.touchDragEles;
  25425. if (draggedEles) {
  25426. r.redrawHint('drag', true);
  25427. for (var i = 0; i < draggedEles.length; i++) {
  25428. var de_p = draggedEles[i]._private;
  25429. de_p.grabbed = false;
  25430. de_p.rscratch.inDragLayer = false;
  25431. }
  25432. }
  25433. var _start = r.touchData.start;
  25434. // (x2, y2) for fingers 1 and 2
  25435. var f1x2 = e.touches[0].clientX - offsetLeft,
  25436. f1y2 = e.touches[0].clientY - offsetTop;
  25437. var f2x2 = e.touches[1].clientX - offsetLeft,
  25438. f2y2 = e.touches[1].clientY - offsetTop;
  25439. var distance2 = distance(f1x2, f1y2, f2x2, f2y2);
  25440. // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );
  25441. // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );
  25442. var factor = distance2 / distance1;
  25443. if (twoFingersStartInside) {
  25444. // delta finger1
  25445. var df1x = f1x2 - f1x1;
  25446. var df1y = f1y2 - f1y1;
  25447. // delta finger 2
  25448. var df2x = f2x2 - f2x1;
  25449. var df2y = f2y2 - f2y1;
  25450. // translation is the normalised vector of the two fingers movement
  25451. // i.e. so pinching cancels out and moving together pans
  25452. var tx = (df1x + df2x) / 2;
  25453. var ty = (df1y + df2y) / 2;
  25454. // now calculate the zoom
  25455. var zoom1 = cy.zoom();
  25456. var zoom2 = zoom1 * factor;
  25457. var pan1 = cy.pan();
  25458. // the model center point converted to the current rendered pos
  25459. var ctrx = modelCenter1[0] * zoom1 + pan1.x;
  25460. var ctry = modelCenter1[1] * zoom1 + pan1.y;
  25461. var pan2 = {
  25462. x: -zoom2 / zoom1 * (ctrx - pan1.x - tx) + ctrx,
  25463. y: -zoom2 / zoom1 * (ctry - pan1.y - ty) + ctry
  25464. };
  25465. // remove dragged eles
  25466. if (_start && _start.active()) {
  25467. var draggedEles = r.dragData.touchDragEles;
  25468. freeDraggedElements(draggedEles);
  25469. r.redrawHint('drag', true);
  25470. r.redrawHint('eles', true);
  25471. _start.unactivate().emit(makeEvent('freeon'));
  25472. draggedEles.emit(makeEvent('free'));
  25473. if (r.dragData.didDrag) {
  25474. _start.emit(makeEvent('dragfreeon'));
  25475. draggedEles.emit(makeEvent('dragfree'));
  25476. }
  25477. }
  25478. cy.viewport({
  25479. zoom: zoom2,
  25480. pan: pan2,
  25481. cancelOnFailedZoom: true
  25482. });
  25483. cy.emit(makeEvent('pinchzoom'));
  25484. distance1 = distance2;
  25485. f1x1 = f1x2;
  25486. f1y1 = f1y2;
  25487. f2x1 = f2x2;
  25488. f2y1 = f2y2;
  25489. r.pinching = true;
  25490. }
  25491. // Re-project
  25492. if (e.touches[0]) {
  25493. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25494. now[0] = pos[0];
  25495. now[1] = pos[1];
  25496. }
  25497. if (e.touches[1]) {
  25498. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25499. now[2] = pos[0];
  25500. now[3] = pos[1];
  25501. }
  25502. if (e.touches[2]) {
  25503. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25504. now[4] = pos[0];
  25505. now[5] = pos[1];
  25506. }
  25507. } else if (e.touches[0] && !r.touchData.didSelect // don't allow box selection to degrade to single finger events like panning
  25508. ) {
  25509. var start = r.touchData.start;
  25510. var last = r.touchData.last;
  25511. var near;
  25512. if (!r.hoverData.draggingEles && !r.swipePanning) {
  25513. near = r.findNearestElement(now[0], now[1], true, true);
  25514. }
  25515. if (capture && start != null) {
  25516. e.preventDefault();
  25517. }
  25518. // dragging nodes
  25519. if (capture && start != null && r.nodeIsDraggable(start)) {
  25520. if (isOverThresholdDrag) {
  25521. // then dragging can happen
  25522. var draggedEles = r.dragData.touchDragEles;
  25523. var justStartedDrag = !r.dragData.didDrag;
  25524. if (justStartedDrag) {
  25525. addNodesToDrag(draggedEles, {
  25526. inDragLayer: true
  25527. });
  25528. }
  25529. r.dragData.didDrag = true;
  25530. var totalShift = {
  25531. x: 0,
  25532. y: 0
  25533. };
  25534. if (number$1(disp[0]) && number$1(disp[1])) {
  25535. totalShift.x += disp[0];
  25536. totalShift.y += disp[1];
  25537. if (justStartedDrag) {
  25538. r.redrawHint('eles', true);
  25539. var dragDelta = r.touchData.dragDelta;
  25540. if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
  25541. totalShift.x += dragDelta[0];
  25542. totalShift.y += dragDelta[1];
  25543. }
  25544. }
  25545. }
  25546. r.hoverData.draggingEles = true;
  25547. draggedEles.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
  25548. r.redrawHint('drag', true);
  25549. if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {
  25550. r.redrawHint('eles', true);
  25551. }
  25552. r.redraw();
  25553. } else {
  25554. // otherwise keep track of drag delta for later
  25555. var dragDelta = r.touchData.dragDelta = r.touchData.dragDelta || [];
  25556. if (dragDelta.length === 0) {
  25557. dragDelta.push(disp[0]);
  25558. dragDelta.push(disp[1]);
  25559. } else {
  25560. dragDelta[0] += disp[0];
  25561. dragDelta[1] += disp[1];
  25562. }
  25563. }
  25564. }
  25565. // touchmove
  25566. {
  25567. triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {
  25568. x: now[0],
  25569. y: now[1]
  25570. });
  25571. if ((!start || !start.grabbed()) && near != last) {
  25572. if (last) {
  25573. last.emit(makeEvent('tapdragout'));
  25574. }
  25575. if (near) {
  25576. near.emit(makeEvent('tapdragover'));
  25577. }
  25578. }
  25579. r.touchData.last = near;
  25580. }
  25581. // check to cancel taphold
  25582. if (capture) {
  25583. for (var i = 0; i < now.length; i++) {
  25584. if (now[i] && r.touchData.startPosition[i] && isOverThresholdDrag) {
  25585. r.touchData.singleTouchMoved = true;
  25586. }
  25587. }
  25588. }
  25589. // panning
  25590. if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {
  25591. var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);
  25592. if (allowPassthrough) {
  25593. e.preventDefault();
  25594. if (!r.data.bgActivePosistion) {
  25595. r.data.bgActivePosistion = array2point(r.touchData.startPosition);
  25596. }
  25597. if (r.swipePanning) {
  25598. cy.panBy({
  25599. x: disp[0] * zoom,
  25600. y: disp[1] * zoom
  25601. });
  25602. cy.emit(makeEvent('dragpan'));
  25603. } else if (isOverThresholdDrag) {
  25604. r.swipePanning = true;
  25605. cy.panBy({
  25606. x: dx * zoom,
  25607. y: dy * zoom
  25608. });
  25609. cy.emit(makeEvent('dragpan'));
  25610. if (start) {
  25611. start.unactivate();
  25612. r.redrawHint('select', true);
  25613. r.touchData.start = null;
  25614. }
  25615. }
  25616. }
  25617. // Re-project
  25618. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25619. now[0] = pos[0];
  25620. now[1] = pos[1];
  25621. }
  25622. }
  25623. for (var j = 0; j < now.length; j++) {
  25624. earlier[j] = now[j];
  25625. }
  25626. // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning
  25627. if (capture && e.touches.length > 0 && !r.hoverData.draggingEles && !r.swipePanning && r.data.bgActivePosistion != null) {
  25628. r.data.bgActivePosistion = undefined;
  25629. r.redrawHint('select', true);
  25630. r.redraw();
  25631. }
  25632. }, false);
  25633. var touchcancelHandler;
  25634. r.registerBinding(containerWindow, 'touchcancel', touchcancelHandler = function touchcancelHandler(e) {
  25635. // eslint-disable-line no-unused-vars
  25636. var start = r.touchData.start;
  25637. r.touchData.capture = false;
  25638. if (start) {
  25639. start.unactivate();
  25640. }
  25641. });
  25642. var touchendHandler, didDoubleTouch, touchTimeout, prevTouchTimeStamp;
  25643. r.registerBinding(containerWindow, 'touchend', touchendHandler = function touchendHandler(e) {
  25644. // eslint-disable-line no-unused-vars
  25645. var start = r.touchData.start;
  25646. var capture = r.touchData.capture;
  25647. if (capture) {
  25648. if (e.touches.length === 0) {
  25649. r.touchData.capture = false;
  25650. }
  25651. e.preventDefault();
  25652. } else {
  25653. return;
  25654. }
  25655. var select = r.selection;
  25656. r.swipePanning = false;
  25657. r.hoverData.draggingEles = false;
  25658. var cy = r.cy;
  25659. var zoom = cy.zoom();
  25660. var now = r.touchData.now;
  25661. var earlier = r.touchData.earlier;
  25662. if (e.touches[0]) {
  25663. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25664. now[0] = pos[0];
  25665. now[1] = pos[1];
  25666. }
  25667. if (e.touches[1]) {
  25668. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25669. now[2] = pos[0];
  25670. now[3] = pos[1];
  25671. }
  25672. if (e.touches[2]) {
  25673. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25674. now[4] = pos[0];
  25675. now[5] = pos[1];
  25676. }
  25677. var makeEvent = function makeEvent(type) {
  25678. return {
  25679. originalEvent: e,
  25680. type: type,
  25681. position: {
  25682. x: now[0],
  25683. y: now[1]
  25684. }
  25685. };
  25686. };
  25687. if (start) {
  25688. start.unactivate();
  25689. }
  25690. var ctxTapend;
  25691. if (r.touchData.cxt) {
  25692. ctxTapend = makeEvent('cxttapend');
  25693. if (start) {
  25694. start.emit(ctxTapend);
  25695. } else {
  25696. cy.emit(ctxTapend);
  25697. }
  25698. if (!r.touchData.cxtDragged) {
  25699. var ctxTap = makeEvent('cxttap');
  25700. if (start) {
  25701. start.emit(ctxTap);
  25702. } else {
  25703. cy.emit(ctxTap);
  25704. }
  25705. }
  25706. if (r.touchData.start) {
  25707. r.touchData.start._private.grabbed = false;
  25708. }
  25709. r.touchData.cxt = false;
  25710. r.touchData.start = null;
  25711. r.redraw();
  25712. return;
  25713. }
  25714. // no more box selection if we don't have three fingers
  25715. if (!e.touches[2] && cy.boxSelectionEnabled() && r.touchData.selecting) {
  25716. r.touchData.selecting = false;
  25717. var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
  25718. select[0] = undefined;
  25719. select[1] = undefined;
  25720. select[2] = undefined;
  25721. select[3] = undefined;
  25722. select[4] = 0;
  25723. r.redrawHint('select', true);
  25724. cy.emit(makeEvent('boxend'));
  25725. var eleWouldBeSelected = function eleWouldBeSelected(ele) {
  25726. return ele.selectable() && !ele.selected();
  25727. };
  25728. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  25729. if (box.nonempty()) {
  25730. r.redrawHint('eles', true);
  25731. }
  25732. r.redraw();
  25733. }
  25734. if (start != null) {
  25735. start.unactivate();
  25736. }
  25737. if (e.touches[2]) {
  25738. r.data.bgActivePosistion = undefined;
  25739. r.redrawHint('select', true);
  25740. } else if (e.touches[1]) ; else if (e.touches[0]) ; else if (!e.touches[0]) {
  25741. r.data.bgActivePosistion = undefined;
  25742. r.redrawHint('select', true);
  25743. var draggedEles = r.dragData.touchDragEles;
  25744. if (start != null) {
  25745. var startWasGrabbed = start._private.grabbed;
  25746. freeDraggedElements(draggedEles);
  25747. r.redrawHint('drag', true);
  25748. r.redrawHint('eles', true);
  25749. if (startWasGrabbed) {
  25750. start.emit(makeEvent('freeon'));
  25751. draggedEles.emit(makeEvent('free'));
  25752. if (r.dragData.didDrag) {
  25753. start.emit(makeEvent('dragfreeon'));
  25754. draggedEles.emit(makeEvent('dragfree'));
  25755. }
  25756. }
  25757. triggerEvents(start, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
  25758. x: now[0],
  25759. y: now[1]
  25760. });
  25761. start.unactivate();
  25762. r.touchData.start = null;
  25763. } else {
  25764. var near = r.findNearestElement(now[0], now[1], true, true);
  25765. triggerEvents(near, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
  25766. x: now[0],
  25767. y: now[1]
  25768. });
  25769. }
  25770. var dx = r.touchData.startPosition[0] - now[0];
  25771. var dx2 = dx * dx;
  25772. var dy = r.touchData.startPosition[1] - now[1];
  25773. var dy2 = dy * dy;
  25774. var dist2 = dx2 + dy2;
  25775. var rdist2 = dist2 * zoom * zoom;
  25776. // Tap event, roughly same as mouse click event for touch
  25777. if (!r.touchData.singleTouchMoved) {
  25778. if (!start) {
  25779. cy.$(':selected').unselect(['tapunselect']);
  25780. }
  25781. triggerEvents(start, ['tap', 'vclick'], e, {
  25782. x: now[0],
  25783. y: now[1]
  25784. });
  25785. didDoubleTouch = false;
  25786. if (e.timeStamp - prevTouchTimeStamp <= cy.multiClickDebounceTime()) {
  25787. touchTimeout && clearTimeout(touchTimeout);
  25788. didDoubleTouch = true;
  25789. prevTouchTimeStamp = null;
  25790. triggerEvents(start, ['dbltap', 'vdblclick'], e, {
  25791. x: now[0],
  25792. y: now[1]
  25793. });
  25794. } else {
  25795. touchTimeout = setTimeout(function () {
  25796. if (didDoubleTouch) return;
  25797. triggerEvents(start, ['onetap', 'voneclick'], e, {
  25798. x: now[0],
  25799. y: now[1]
  25800. });
  25801. }, cy.multiClickDebounceTime());
  25802. prevTouchTimeStamp = e.timeStamp;
  25803. }
  25804. }
  25805. // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance
  25806. if (start != null && !r.dragData.didDrag // didn't drag nodes around
  25807. && start._private.selectable && rdist2 < r.touchTapThreshold2 && !r.pinching // pinch to zoom should not affect selection
  25808. ) {
  25809. if (cy.selectionType() === 'single') {
  25810. cy.$(isSelected).unmerge(start).unselect(['tapunselect']);
  25811. start.select(['tapselect']);
  25812. } else {
  25813. if (start.selected()) {
  25814. start.unselect(['tapunselect']);
  25815. } else {
  25816. start.select(['tapselect']);
  25817. }
  25818. }
  25819. r.redrawHint('eles', true);
  25820. }
  25821. r.touchData.singleTouchMoved = true;
  25822. }
  25823. for (var j = 0; j < now.length; j++) {
  25824. earlier[j] = now[j];
  25825. }
  25826. r.dragData.didDrag = false; // reset for next touchstart
  25827. if (e.touches.length === 0) {
  25828. r.touchData.dragDelta = [];
  25829. r.touchData.startPosition = [null, null, null, null, null, null];
  25830. r.touchData.startGPosition = null;
  25831. r.touchData.didSelect = false;
  25832. }
  25833. if (e.touches.length < 2) {
  25834. if (e.touches.length === 1) {
  25835. // the old start global pos'n may not be the same finger that remains
  25836. r.touchData.startGPosition = [e.touches[0].clientX, e.touches[0].clientY];
  25837. }
  25838. r.pinching = false;
  25839. r.redrawHint('eles', true);
  25840. r.redraw();
  25841. }
  25842. //r.redraw();
  25843. }, false);
  25844. // fallback compatibility layer for ms pointer events
  25845. if (typeof TouchEvent === 'undefined') {
  25846. var pointers = [];
  25847. var makeTouch = function makeTouch(e) {
  25848. return {
  25849. clientX: e.clientX,
  25850. clientY: e.clientY,
  25851. force: 1,
  25852. identifier: e.pointerId,
  25853. pageX: e.pageX,
  25854. pageY: e.pageY,
  25855. radiusX: e.width / 2,
  25856. radiusY: e.height / 2,
  25857. screenX: e.screenX,
  25858. screenY: e.screenY,
  25859. target: e.target
  25860. };
  25861. };
  25862. var makePointer = function makePointer(e) {
  25863. return {
  25864. event: e,
  25865. touch: makeTouch(e)
  25866. };
  25867. };
  25868. var addPointer = function addPointer(e) {
  25869. pointers.push(makePointer(e));
  25870. };
  25871. var removePointer = function removePointer(e) {
  25872. for (var i = 0; i < pointers.length; i++) {
  25873. var p = pointers[i];
  25874. if (p.event.pointerId === e.pointerId) {
  25875. pointers.splice(i, 1);
  25876. return;
  25877. }
  25878. }
  25879. };
  25880. var updatePointer = function updatePointer(e) {
  25881. var p = pointers.filter(function (p) {
  25882. return p.event.pointerId === e.pointerId;
  25883. })[0];
  25884. p.event = e;
  25885. p.touch = makeTouch(e);
  25886. };
  25887. var addTouchesToEvent = function addTouchesToEvent(e) {
  25888. e.touches = pointers.map(function (p) {
  25889. return p.touch;
  25890. });
  25891. };
  25892. var pointerIsMouse = function pointerIsMouse(e) {
  25893. return e.pointerType === 'mouse' || e.pointerType === 4;
  25894. };
  25895. r.registerBinding(r.container, 'pointerdown', function (e) {
  25896. if (pointerIsMouse(e)) {
  25897. return;
  25898. } // mouse already handled
  25899. e.preventDefault();
  25900. addPointer(e);
  25901. addTouchesToEvent(e);
  25902. touchstartHandler(e);
  25903. });
  25904. r.registerBinding(r.container, 'pointerup', function (e) {
  25905. if (pointerIsMouse(e)) {
  25906. return;
  25907. } // mouse already handled
  25908. removePointer(e);
  25909. addTouchesToEvent(e);
  25910. touchendHandler(e);
  25911. });
  25912. r.registerBinding(r.container, 'pointercancel', function (e) {
  25913. if (pointerIsMouse(e)) {
  25914. return;
  25915. } // mouse already handled
  25916. removePointer(e);
  25917. addTouchesToEvent(e);
  25918. touchcancelHandler(e);
  25919. });
  25920. r.registerBinding(r.container, 'pointermove', function (e) {
  25921. if (pointerIsMouse(e)) {
  25922. return;
  25923. } // mouse already handled
  25924. e.preventDefault();
  25925. updatePointer(e);
  25926. addTouchesToEvent(e);
  25927. touchmoveHandler(e);
  25928. });
  25929. }
  25930. };
  25931. var BRp$2 = {};
  25932. BRp$2.generatePolygon = function (name, points) {
  25933. return this.nodeShapes[name] = {
  25934. renderer: this,
  25935. name: name,
  25936. points: points,
  25937. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  25938. this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);
  25939. },
  25940. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  25941. return polygonIntersectLine(x, y, this.points, nodeX, nodeY, width / 2, height / 2, padding);
  25942. },
  25943. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  25944. return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);
  25945. },
  25946. hasMiterBounds: name !== 'rectangle',
  25947. miterBounds: function miterBounds(centerX, centerY, width, height, strokeWidth, strokePosition) {
  25948. return miterBox(this.points, centerX, centerY, width, height, strokeWidth);
  25949. }
  25950. };
  25951. };
  25952. BRp$2.generateEllipse = function () {
  25953. return this.nodeShapes['ellipse'] = {
  25954. renderer: this,
  25955. name: 'ellipse',
  25956. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  25957. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
  25958. },
  25959. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  25960. return intersectLineEllipse(x, y, nodeX, nodeY, width / 2 + padding, height / 2 + padding);
  25961. },
  25962. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  25963. return checkInEllipse(x, y, width, height, centerX, centerY, padding);
  25964. }
  25965. };
  25966. };
  25967. BRp$2.generateRoundPolygon = function (name, points) {
  25968. return this.nodeShapes[name] = {
  25969. renderer: this,
  25970. name: name,
  25971. points: points,
  25972. getOrCreateCorners: function getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, field) {
  25973. if (rs[field] !== undefined && rs[field + '-cx'] === centerX && rs[field + '-cy'] === centerY) {
  25974. return rs[field];
  25975. }
  25976. rs[field] = new Array(points.length / 2);
  25977. rs[field + '-cx'] = centerX;
  25978. rs[field + '-cy'] = centerY;
  25979. var halfW = width / 2;
  25980. var halfH = height / 2;
  25981. cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(width, height) : cornerRadius;
  25982. var p = new Array(points.length / 2);
  25983. for (var _i = 0; _i < points.length / 2; _i++) {
  25984. p[_i] = {
  25985. x: centerX + halfW * points[_i * 2],
  25986. y: centerY + halfH * points[_i * 2 + 1]
  25987. };
  25988. }
  25989. var i,
  25990. p1,
  25991. p2,
  25992. p3,
  25993. len = p.length;
  25994. p1 = p[len - 1];
  25995. // for each point
  25996. for (i = 0; i < len; i++) {
  25997. p2 = p[i % len];
  25998. p3 = p[(i + 1) % len];
  25999. rs[field][i] = getRoundCorner(p1, p2, p3, cornerRadius);
  26000. p1 = p2;
  26001. p2 = p3;
  26002. }
  26003. return rs[field];
  26004. },
  26005. draw: function draw(context, centerX, centerY, width, height, cornerRadius, rs) {
  26006. this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'drawCorners'));
  26007. },
  26008. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius, rs) {
  26009. return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height, padding, this.getOrCreateCorners(nodeX, nodeY, width, height, cornerRadius, rs, 'corners'));
  26010. },
  26011. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius, rs) {
  26012. return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'corners'));
  26013. }
  26014. };
  26015. };
  26016. BRp$2.generateRoundRectangle = function () {
  26017. return this.nodeShapes['round-rectangle'] = this.nodeShapes['roundrectangle'] = {
  26018. renderer: this,
  26019. name: 'round-rectangle',
  26020. points: generateUnitNgonPointsFitToSquare(4, 0),
  26021. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26022. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
  26023. },
  26024. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26025. return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
  26026. },
  26027. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26028. var halfWidth = width / 2;
  26029. var halfHeight = height / 2;
  26030. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
  26031. cornerRadius = Math.min(halfWidth, halfHeight, cornerRadius);
  26032. var diam = cornerRadius * 2;
  26033. // Check hBox
  26034. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
  26035. return true;
  26036. }
  26037. // Check vBox
  26038. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
  26039. return true;
  26040. }
  26041. // Check top left quarter circle
  26042. if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
  26043. return true;
  26044. }
  26045. // Check top right quarter circle
  26046. if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
  26047. return true;
  26048. }
  26049. // Check bottom right quarter circle
  26050. if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
  26051. return true;
  26052. }
  26053. // Check bottom left quarter circle
  26054. if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
  26055. return true;
  26056. }
  26057. return false;
  26058. }
  26059. };
  26060. };
  26061. BRp$2.generateCutRectangle = function () {
  26062. return this.nodeShapes['cut-rectangle'] = this.nodeShapes['cutrectangle'] = {
  26063. renderer: this,
  26064. name: 'cut-rectangle',
  26065. cornerLength: getCutRectangleCornerLength(),
  26066. points: generateUnitNgonPointsFitToSquare(4, 0),
  26067. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26068. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, null, cornerRadius);
  26069. },
  26070. generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY, cornerRadius) {
  26071. var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
  26072. var hh = height / 2;
  26073. var hw = width / 2;
  26074. var xBegin = centerX - hw;
  26075. var xEnd = centerX + hw;
  26076. var yBegin = centerY - hh;
  26077. var yEnd = centerY + hh;
  26078. // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]
  26079. return {
  26080. topLeft: [xBegin, yBegin + cl, xBegin + cl, yBegin, xBegin + cl, yBegin + cl],
  26081. topRight: [xEnd - cl, yBegin, xEnd, yBegin + cl, xEnd - cl, yBegin + cl],
  26082. bottomRight: [xEnd, yEnd - cl, xEnd - cl, yEnd, xEnd - cl, yEnd - cl],
  26083. bottomLeft: [xBegin + cl, yEnd, xBegin, yEnd - cl, xBegin + cl, yEnd - cl]
  26084. };
  26085. },
  26086. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26087. var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY, cornerRadius);
  26088. var pts = [].concat.apply([], [cPts.topLeft.splice(0, 4), cPts.topRight.splice(0, 4), cPts.bottomRight.splice(0, 4), cPts.bottomLeft.splice(0, 4)]);
  26089. return polygonIntersectLine(x, y, pts, nodeX, nodeY);
  26090. },
  26091. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26092. var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
  26093. // Check hBox
  26094. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * cl, [0, -1], padding)) {
  26095. return true;
  26096. }
  26097. // Check vBox
  26098. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * cl, height, [0, -1], padding)) {
  26099. return true;
  26100. }
  26101. var cutTrianglePts = this.generateCutTrianglePts(width, height, centerX, centerY);
  26102. return pointInsidePolygonPoints(x, y, cutTrianglePts.topLeft) || pointInsidePolygonPoints(x, y, cutTrianglePts.topRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomLeft);
  26103. }
  26104. };
  26105. };
  26106. BRp$2.generateBarrel = function () {
  26107. return this.nodeShapes['barrel'] = {
  26108. renderer: this,
  26109. name: 'barrel',
  26110. points: generateUnitNgonPointsFitToSquare(4, 0),
  26111. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26112. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
  26113. },
  26114. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26115. // use two fixed t values for the bezier curve approximation
  26116. var t0 = 0.15;
  26117. var t1 = 0.5;
  26118. var t2 = 0.85;
  26119. var bPts = this.generateBarrelBezierPts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);
  26120. var approximateBarrelCurvePts = function approximateBarrelCurvePts(pts) {
  26121. // approximate curve pts based on the two t values
  26122. var m0 = qbezierPtAt({
  26123. x: pts[0],
  26124. y: pts[1]
  26125. }, {
  26126. x: pts[2],
  26127. y: pts[3]
  26128. }, {
  26129. x: pts[4],
  26130. y: pts[5]
  26131. }, t0);
  26132. var m1 = qbezierPtAt({
  26133. x: pts[0],
  26134. y: pts[1]
  26135. }, {
  26136. x: pts[2],
  26137. y: pts[3]
  26138. }, {
  26139. x: pts[4],
  26140. y: pts[5]
  26141. }, t1);
  26142. var m2 = qbezierPtAt({
  26143. x: pts[0],
  26144. y: pts[1]
  26145. }, {
  26146. x: pts[2],
  26147. y: pts[3]
  26148. }, {
  26149. x: pts[4],
  26150. y: pts[5]
  26151. }, t2);
  26152. return [pts[0], pts[1], m0.x, m0.y, m1.x, m1.y, m2.x, m2.y, pts[4], pts[5]];
  26153. };
  26154. var pts = [].concat(approximateBarrelCurvePts(bPts.topLeft), approximateBarrelCurvePts(bPts.topRight), approximateBarrelCurvePts(bPts.bottomRight), approximateBarrelCurvePts(bPts.bottomLeft));
  26155. return polygonIntersectLine(x, y, pts, nodeX, nodeY);
  26156. },
  26157. generateBarrelBezierPts: function generateBarrelBezierPts(width, height, centerX, centerY) {
  26158. var hh = height / 2;
  26159. var hw = width / 2;
  26160. var xBegin = centerX - hw;
  26161. var xEnd = centerX + hw;
  26162. var yBegin = centerY - hh;
  26163. var yEnd = centerY + hh;
  26164. var curveConstants = getBarrelCurveConstants(width, height);
  26165. var hOffset = curveConstants.heightOffset;
  26166. var wOffset = curveConstants.widthOffset;
  26167. var ctrlPtXOffset = curveConstants.ctrlPtOffsetPct * width;
  26168. // points are in clockwise order, inner (imaginary) control pt on [4, 5]
  26169. var pts = {
  26170. topLeft: [xBegin, yBegin + hOffset, xBegin + ctrlPtXOffset, yBegin, xBegin + wOffset, yBegin],
  26171. topRight: [xEnd - wOffset, yBegin, xEnd - ctrlPtXOffset, yBegin, xEnd, yBegin + hOffset],
  26172. bottomRight: [xEnd, yEnd - hOffset, xEnd - ctrlPtXOffset, yEnd, xEnd - wOffset, yEnd],
  26173. bottomLeft: [xBegin + wOffset, yEnd, xBegin + ctrlPtXOffset, yEnd, xBegin, yEnd - hOffset]
  26174. };
  26175. pts.topLeft.isTop = true;
  26176. pts.topRight.isTop = true;
  26177. pts.bottomLeft.isBottom = true;
  26178. pts.bottomRight.isBottom = true;
  26179. return pts;
  26180. },
  26181. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26182. var curveConstants = getBarrelCurveConstants(width, height);
  26183. var hOffset = curveConstants.heightOffset;
  26184. var wOffset = curveConstants.widthOffset;
  26185. // Check hBox
  26186. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {
  26187. return true;
  26188. }
  26189. // Check vBox
  26190. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {
  26191. return true;
  26192. }
  26193. var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);
  26194. var getCurveT = function getCurveT(x, y, curvePts) {
  26195. var x0 = curvePts[4];
  26196. var x1 = curvePts[2];
  26197. var x2 = curvePts[0];
  26198. var y0 = curvePts[5];
  26199. // var y1 = curvePts[ 3 ];
  26200. var y2 = curvePts[1];
  26201. var xMin = Math.min(x0, x2);
  26202. var xMax = Math.max(x0, x2);
  26203. var yMin = Math.min(y0, y2);
  26204. var yMax = Math.max(y0, y2);
  26205. if (xMin <= x && x <= xMax && yMin <= y && y <= yMax) {
  26206. var coeff = bezierPtsToQuadCoeff(x0, x1, x2);
  26207. var roots = solveQuadratic(coeff[0], coeff[1], coeff[2], x);
  26208. var validRoots = roots.filter(function (r) {
  26209. return 0 <= r && r <= 1;
  26210. });
  26211. if (validRoots.length > 0) {
  26212. return validRoots[0];
  26213. }
  26214. }
  26215. return null;
  26216. };
  26217. var curveRegions = Object.keys(barrelCurvePts);
  26218. for (var i = 0; i < curveRegions.length; i++) {
  26219. var corner = curveRegions[i];
  26220. var cornerPts = barrelCurvePts[corner];
  26221. var t = getCurveT(x, y, cornerPts);
  26222. if (t == null) {
  26223. continue;
  26224. }
  26225. var y0 = cornerPts[5];
  26226. var y1 = cornerPts[3];
  26227. var y2 = cornerPts[1];
  26228. var bezY = qbezierAt(y0, y1, y2, t);
  26229. if (cornerPts.isTop && bezY <= y) {
  26230. return true;
  26231. }
  26232. if (cornerPts.isBottom && y <= bezY) {
  26233. return true;
  26234. }
  26235. }
  26236. return false;
  26237. }
  26238. };
  26239. };
  26240. BRp$2.generateBottomRoundrectangle = function () {
  26241. return this.nodeShapes['bottom-round-rectangle'] = this.nodeShapes['bottomroundrectangle'] = {
  26242. renderer: this,
  26243. name: 'bottom-round-rectangle',
  26244. points: generateUnitNgonPointsFitToSquare(4, 0),
  26245. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26246. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
  26247. },
  26248. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26249. var topStartX = nodeX - (width / 2 + padding);
  26250. var topStartY = nodeY - (height / 2 + padding);
  26251. var topEndY = topStartY;
  26252. var topEndX = nodeX + (width / 2 + padding);
  26253. var topIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
  26254. if (topIntersections.length > 0) {
  26255. return topIntersections;
  26256. }
  26257. return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
  26258. },
  26259. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26260. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
  26261. var diam = 2 * cornerRadius;
  26262. // Check hBox
  26263. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
  26264. return true;
  26265. }
  26266. // Check vBox
  26267. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
  26268. return true;
  26269. }
  26270. // check non-rounded top side
  26271. var outerWidth = width / 2 + 2 * padding;
  26272. var outerHeight = height / 2 + 2 * padding;
  26273. var points = [centerX - outerWidth, centerY - outerHeight, centerX - outerWidth, centerY, centerX + outerWidth, centerY, centerX + outerWidth, centerY - outerHeight];
  26274. if (pointInsidePolygonPoints(x, y, points)) {
  26275. return true;
  26276. }
  26277. // Check bottom right quarter circle
  26278. if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
  26279. return true;
  26280. }
  26281. // Check bottom left quarter circle
  26282. if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
  26283. return true;
  26284. }
  26285. return false;
  26286. }
  26287. };
  26288. };
  26289. BRp$2.registerNodeShapes = function () {
  26290. var nodeShapes = this.nodeShapes = {};
  26291. var renderer = this;
  26292. this.generateEllipse();
  26293. this.generatePolygon('triangle', generateUnitNgonPointsFitToSquare(3, 0));
  26294. this.generateRoundPolygon('round-triangle', generateUnitNgonPointsFitToSquare(3, 0));
  26295. this.generatePolygon('rectangle', generateUnitNgonPointsFitToSquare(4, 0));
  26296. nodeShapes['square'] = nodeShapes['rectangle'];
  26297. this.generateRoundRectangle();
  26298. this.generateCutRectangle();
  26299. this.generateBarrel();
  26300. this.generateBottomRoundrectangle();
  26301. {
  26302. var diamondPoints = [0, 1, 1, 0, 0, -1, -1, 0];
  26303. this.generatePolygon('diamond', diamondPoints);
  26304. this.generateRoundPolygon('round-diamond', diamondPoints);
  26305. }
  26306. this.generatePolygon('pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  26307. this.generateRoundPolygon('round-pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  26308. this.generatePolygon('hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  26309. this.generateRoundPolygon('round-hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  26310. this.generatePolygon('heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  26311. this.generateRoundPolygon('round-heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  26312. this.generatePolygon('octagon', generateUnitNgonPointsFitToSquare(8, 0));
  26313. this.generateRoundPolygon('round-octagon', generateUnitNgonPointsFitToSquare(8, 0));
  26314. var star5Points = new Array(20);
  26315. {
  26316. var outerPoints = generateUnitNgonPoints(5, 0);
  26317. var innerPoints = generateUnitNgonPoints(5, Math.PI / 5);
  26318. // Outer radius is 1; inner radius of star is smaller
  26319. var innerRadius = 0.5 * (3 - Math.sqrt(5));
  26320. innerRadius *= 1.57;
  26321. for (var i = 0; i < innerPoints.length / 2; i++) {
  26322. innerPoints[i * 2] *= innerRadius;
  26323. innerPoints[i * 2 + 1] *= innerRadius;
  26324. }
  26325. for (var i = 0; i < 20 / 4; i++) {
  26326. star5Points[i * 4] = outerPoints[i * 2];
  26327. star5Points[i * 4 + 1] = outerPoints[i * 2 + 1];
  26328. star5Points[i * 4 + 2] = innerPoints[i * 2];
  26329. star5Points[i * 4 + 3] = innerPoints[i * 2 + 1];
  26330. }
  26331. }
  26332. star5Points = fitPolygonToSquare(star5Points);
  26333. this.generatePolygon('star', star5Points);
  26334. this.generatePolygon('vee', [-1, -1, 0, -0.333, 1, -1, 0, 1]);
  26335. this.generatePolygon('rhomboid', [-1, -1, 0.333, -1, 1, 1, -0.333, 1]);
  26336. this.generatePolygon('right-rhomboid', [-0.333, -1, 1, -1, 0.333, 1, -1, 1]);
  26337. 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]);
  26338. {
  26339. var tagPoints = [-1, -1, 0.25, -1, 1, 0, 0.25, 1, -1, 1];
  26340. this.generatePolygon('tag', tagPoints);
  26341. this.generateRoundPolygon('round-tag', tagPoints);
  26342. }
  26343. nodeShapes.makePolygon = function (points) {
  26344. // use caching on user-specified polygons so they are as fast as native shapes
  26345. var key = points.join('$');
  26346. var name = 'polygon-' + key;
  26347. var shape;
  26348. if (shape = this[name]) {
  26349. // got cached shape
  26350. return shape;
  26351. }
  26352. // create and cache new shape
  26353. return renderer.generatePolygon(name, points);
  26354. };
  26355. };
  26356. var BRp$1 = {};
  26357. BRp$1.timeToRender = function () {
  26358. return this.redrawTotalTime / this.redrawCount;
  26359. };
  26360. BRp$1.redraw = function (options) {
  26361. options = options || staticEmptyObject();
  26362. var r = this;
  26363. if (r.averageRedrawTime === undefined) {
  26364. r.averageRedrawTime = 0;
  26365. }
  26366. if (r.lastRedrawTime === undefined) {
  26367. r.lastRedrawTime = 0;
  26368. }
  26369. if (r.lastDrawTime === undefined) {
  26370. r.lastDrawTime = 0;
  26371. }
  26372. r.requestedFrame = true;
  26373. r.renderOptions = options;
  26374. };
  26375. BRp$1.beforeRender = function (fn, priority) {
  26376. // the renderer can't add tick callbacks when destroyed
  26377. if (this.destroyed) {
  26378. return;
  26379. }
  26380. if (priority == null) {
  26381. error('Priority is not optional for beforeRender');
  26382. }
  26383. var cbs = this.beforeRenderCallbacks;
  26384. cbs.push({
  26385. fn: fn,
  26386. priority: priority
  26387. });
  26388. // higher priority callbacks executed first
  26389. cbs.sort(function (a, b) {
  26390. return b.priority - a.priority;
  26391. });
  26392. };
  26393. var beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {
  26394. var cbs = r.beforeRenderCallbacks;
  26395. for (var i = 0; i < cbs.length; i++) {
  26396. cbs[i].fn(willDraw, startTime);
  26397. }
  26398. };
  26399. BRp$1.startRenderLoop = function () {
  26400. var r = this;
  26401. var cy = r.cy;
  26402. if (r.renderLoopStarted) {
  26403. return;
  26404. } else {
  26405. r.renderLoopStarted = true;
  26406. }
  26407. var _renderFn = function renderFn(requestTime) {
  26408. if (r.destroyed) {
  26409. return;
  26410. }
  26411. if (cy.batching()) ; else if (r.requestedFrame && !r.skipFrame) {
  26412. beforeRenderCallbacks(r, true, requestTime);
  26413. var startTime = performanceNow();
  26414. r.render(r.renderOptions);
  26415. var endTime = r.lastDrawTime = performanceNow();
  26416. if (r.averageRedrawTime === undefined) {
  26417. r.averageRedrawTime = endTime - startTime;
  26418. }
  26419. if (r.redrawCount === undefined) {
  26420. r.redrawCount = 0;
  26421. }
  26422. r.redrawCount++;
  26423. if (r.redrawTotalTime === undefined) {
  26424. r.redrawTotalTime = 0;
  26425. }
  26426. var duration = endTime - startTime;
  26427. r.redrawTotalTime += duration;
  26428. r.lastRedrawTime = duration;
  26429. // use a weighted average with a bias from the previous average so we don't spike so easily
  26430. r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;
  26431. r.requestedFrame = false;
  26432. } else {
  26433. beforeRenderCallbacks(r, false, requestTime);
  26434. }
  26435. r.skipFrame = false;
  26436. requestAnimationFrame(_renderFn);
  26437. };
  26438. requestAnimationFrame(_renderFn);
  26439. };
  26440. var BaseRenderer = function BaseRenderer(options) {
  26441. this.init(options);
  26442. };
  26443. var BR = BaseRenderer;
  26444. var BRp = BR.prototype;
  26445. BRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];
  26446. BRp.init = function (options) {
  26447. var r = this;
  26448. r.options = options;
  26449. r.cy = options.cy;
  26450. var ctr = r.container = options.cy.container();
  26451. var containerWindow = r.cy.window();
  26452. // prepend a stylesheet in the head such that
  26453. if (containerWindow) {
  26454. var document = containerWindow.document;
  26455. var head = document.head;
  26456. var stylesheetId = '__________cytoscape_stylesheet';
  26457. var className = '__________cytoscape_container';
  26458. var stylesheetAlreadyExists = document.getElementById(stylesheetId) != null;
  26459. if (ctr.className.indexOf(className) < 0) {
  26460. ctr.className = (ctr.className || '') + ' ' + className;
  26461. }
  26462. if (!stylesheetAlreadyExists) {
  26463. var stylesheet = document.createElement('style');
  26464. stylesheet.id = stylesheetId;
  26465. stylesheet.textContent = '.' + className + ' { position: relative; }';
  26466. head.insertBefore(stylesheet, head.children[0]); // first so lowest priority
  26467. }
  26468. var computedStyle = containerWindow.getComputedStyle(ctr);
  26469. var position = computedStyle.getPropertyValue('position');
  26470. if (position === 'static') {
  26471. warn('A Cytoscape container has style position:static and so can not use UI extensions properly');
  26472. }
  26473. }
  26474. r.selection = [undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag
  26475. r.bezierProjPcts = [0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95];
  26476. //--Pointer-related data
  26477. r.hoverData = {
  26478. down: null,
  26479. last: null,
  26480. downTime: null,
  26481. triggerMode: null,
  26482. dragging: false,
  26483. initialPan: [null, null],
  26484. capture: false
  26485. };
  26486. r.dragData = {
  26487. possibleDragElements: []
  26488. };
  26489. r.touchData = {
  26490. start: null,
  26491. capture: false,
  26492. // These 3 fields related to tap, taphold events
  26493. startPosition: [null, null, null, null, null, null],
  26494. singleTouchStartTime: null,
  26495. singleTouchMoved: true,
  26496. now: [null, null, null, null, null, null],
  26497. earlier: [null, null, null, null, null, null]
  26498. };
  26499. r.redraws = 0;
  26500. r.showFps = options.showFps;
  26501. r.debug = options.debug;
  26502. r.webgl = options.webgl;
  26503. r.hideEdgesOnViewport = options.hideEdgesOnViewport;
  26504. r.textureOnViewport = options.textureOnViewport;
  26505. r.wheelSensitivity = options.wheelSensitivity;
  26506. r.motionBlurEnabled = options.motionBlur; // on by default
  26507. r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;
  26508. r.motionBlur = options.motionBlur; // for initial kick off
  26509. r.motionBlurOpacity = options.motionBlurOpacity;
  26510. r.motionBlurTransparency = 1 - r.motionBlurOpacity;
  26511. r.motionBlurPxRatio = 1;
  26512. r.mbPxRBlurry = 1; //0.8;
  26513. r.minMbLowQualFrames = 4;
  26514. r.fullQualityMb = false;
  26515. r.clearedForMotionBlur = [];
  26516. r.desktopTapThreshold = options.desktopTapThreshold;
  26517. r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;
  26518. r.touchTapThreshold = options.touchTapThreshold;
  26519. r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;
  26520. r.tapholdDuration = 500;
  26521. r.bindings = [];
  26522. r.beforeRenderCallbacks = [];
  26523. r.beforeRenderPriorities = {
  26524. // higher priority execs before lower one
  26525. animations: 400,
  26526. eleCalcs: 300,
  26527. eleTxrDeq: 200,
  26528. lyrTxrDeq: 150,
  26529. lyrTxrSkip: 100
  26530. };
  26531. r.registerNodeShapes();
  26532. r.registerArrowShapes();
  26533. r.registerCalculationListeners();
  26534. };
  26535. BRp.notify = function (eventName, eles) {
  26536. var r = this;
  26537. var cy = r.cy;
  26538. // the renderer can't be notified after it's destroyed
  26539. if (this.destroyed) {
  26540. return;
  26541. }
  26542. if (eventName === 'init') {
  26543. r.load();
  26544. return;
  26545. }
  26546. if (eventName === 'destroy') {
  26547. r.destroy();
  26548. return;
  26549. }
  26550. if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {
  26551. r.invalidateCachedZSortedEles();
  26552. }
  26553. if (eventName === 'viewport') {
  26554. r.redrawHint('select', true);
  26555. }
  26556. if (eventName === 'gc') {
  26557. r.redrawHint('gc', true);
  26558. }
  26559. if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {
  26560. r.invalidateContainerClientCoordsCache();
  26561. r.matchCanvasSize(r.container);
  26562. }
  26563. r.redrawHint('eles', true);
  26564. r.redrawHint('drag', true);
  26565. this.startRenderLoop();
  26566. this.redraw();
  26567. };
  26568. BRp.destroy = function () {
  26569. var r = this;
  26570. r.destroyed = true;
  26571. r.cy.stopAnimationLoop();
  26572. for (var i = 0; i < r.bindings.length; i++) {
  26573. var binding = r.bindings[i];
  26574. var b = binding;
  26575. var tgt = b.target;
  26576. (tgt.off || tgt.removeEventListener).apply(tgt, b.args);
  26577. }
  26578. r.bindings = [];
  26579. r.beforeRenderCallbacks = [];
  26580. r.onUpdateEleCalcsFns = [];
  26581. if (r.removeObserver) {
  26582. r.removeObserver.disconnect();
  26583. }
  26584. if (r.styleObserver) {
  26585. r.styleObserver.disconnect();
  26586. }
  26587. if (r.resizeObserver) {
  26588. r.resizeObserver.disconnect();
  26589. }
  26590. if (r.labelCalcDiv) {
  26591. try {
  26592. document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef
  26593. } catch (e) {
  26594. // ie10 issue #1014
  26595. }
  26596. }
  26597. };
  26598. BRp.isHeadless = function () {
  26599. return false;
  26600. };
  26601. [BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {
  26602. extend(BRp, props);
  26603. });
  26604. var fullFpsTime = 1000 / 60; // assume 60 frames per second
  26605. var defs = {
  26606. setupDequeueing: function setupDequeueing(opts) {
  26607. return function setupDequeueingImpl() {
  26608. var self = this;
  26609. var r = this.renderer;
  26610. if (self.dequeueingSetup) {
  26611. return;
  26612. } else {
  26613. self.dequeueingSetup = true;
  26614. }
  26615. var queueRedraw = debounce(function () {
  26616. r.redrawHint('eles', true);
  26617. r.redrawHint('drag', true);
  26618. r.redraw();
  26619. }, opts.deqRedrawThreshold);
  26620. var dequeue = function dequeue(willDraw, frameStartTime) {
  26621. var startTime = performanceNow();
  26622. var avgRenderTime = r.averageRedrawTime;
  26623. var renderTime = r.lastRedrawTime;
  26624. var deqd = [];
  26625. var extent = r.cy.extent();
  26626. var pixelRatio = r.getPixelRatio();
  26627. // if we aren't in a tick that causes a draw, then the rendered style
  26628. // queue won't automatically be flushed before dequeueing starts
  26629. if (!willDraw) {
  26630. r.flushRenderedStyleQueue();
  26631. }
  26632. while (true) {
  26633. // eslint-disable-line no-constant-condition
  26634. var now = performanceNow();
  26635. var duration = now - startTime;
  26636. var frameDuration = now - frameStartTime;
  26637. if (renderTime < fullFpsTime) {
  26638. // if we're rendering faster than the ideal fps, then do dequeueing
  26639. // during all of the remaining frame time
  26640. var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);
  26641. if (frameDuration >= opts.deqFastCost * timeAvailable) {
  26642. break;
  26643. }
  26644. } else {
  26645. if (willDraw) {
  26646. if (duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime) {
  26647. break;
  26648. }
  26649. } else if (frameDuration >= opts.deqNoDrawCost * fullFpsTime) {
  26650. break;
  26651. }
  26652. }
  26653. var thisDeqd = opts.deq(self, pixelRatio, extent);
  26654. if (thisDeqd.length > 0) {
  26655. for (var i = 0; i < thisDeqd.length; i++) {
  26656. deqd.push(thisDeqd[i]);
  26657. }
  26658. } else {
  26659. break;
  26660. }
  26661. }
  26662. // callbacks on dequeue
  26663. if (deqd.length > 0) {
  26664. opts.onDeqd(self, deqd);
  26665. if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {
  26666. queueRedraw();
  26667. }
  26668. }
  26669. };
  26670. var priority = opts.priority || noop$1;
  26671. r.beforeRender(dequeue, priority(self));
  26672. };
  26673. }
  26674. };
  26675. // Allows lookups for (ele, lvl) => cache.
  26676. // Uses keys so elements may share the same cache.
  26677. var ElementTextureCacheLookup = /*#__PURE__*/function () {
  26678. function ElementTextureCacheLookup(getKey) {
  26679. var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;
  26680. _classCallCheck(this, ElementTextureCacheLookup);
  26681. this.idsByKey = new Map$1();
  26682. this.keyForId = new Map$1();
  26683. this.cachesByLvl = new Map$1();
  26684. this.lvls = [];
  26685. this.getKey = getKey;
  26686. this.doesEleInvalidateKey = doesEleInvalidateKey;
  26687. }
  26688. return _createClass(ElementTextureCacheLookup, [{
  26689. key: "getIdsFor",
  26690. value: function getIdsFor(key) {
  26691. if (key == null) {
  26692. error("Can not get id list for null key");
  26693. }
  26694. var idsByKey = this.idsByKey;
  26695. var ids = this.idsByKey.get(key);
  26696. if (!ids) {
  26697. ids = new Set$1();
  26698. idsByKey.set(key, ids);
  26699. }
  26700. return ids;
  26701. }
  26702. }, {
  26703. key: "addIdForKey",
  26704. value: function addIdForKey(key, id) {
  26705. if (key != null) {
  26706. this.getIdsFor(key).add(id);
  26707. }
  26708. }
  26709. }, {
  26710. key: "deleteIdForKey",
  26711. value: function deleteIdForKey(key, id) {
  26712. if (key != null) {
  26713. this.getIdsFor(key)["delete"](id);
  26714. }
  26715. }
  26716. }, {
  26717. key: "getNumberOfIdsForKey",
  26718. value: function getNumberOfIdsForKey(key) {
  26719. if (key == null) {
  26720. return 0;
  26721. } else {
  26722. return this.getIdsFor(key).size;
  26723. }
  26724. }
  26725. }, {
  26726. key: "updateKeyMappingFor",
  26727. value: function updateKeyMappingFor(ele) {
  26728. var id = ele.id();
  26729. var prevKey = this.keyForId.get(id);
  26730. var currKey = this.getKey(ele);
  26731. this.deleteIdForKey(prevKey, id);
  26732. this.addIdForKey(currKey, id);
  26733. this.keyForId.set(id, currKey);
  26734. }
  26735. }, {
  26736. key: "deleteKeyMappingFor",
  26737. value: function deleteKeyMappingFor(ele) {
  26738. var id = ele.id();
  26739. var prevKey = this.keyForId.get(id);
  26740. this.deleteIdForKey(prevKey, id);
  26741. this.keyForId["delete"](id);
  26742. }
  26743. }, {
  26744. key: "keyHasChangedFor",
  26745. value: function keyHasChangedFor(ele) {
  26746. var id = ele.id();
  26747. var prevKey = this.keyForId.get(id);
  26748. var newKey = this.getKey(ele);
  26749. return prevKey !== newKey;
  26750. }
  26751. }, {
  26752. key: "isInvalid",
  26753. value: function isInvalid(ele) {
  26754. return this.keyHasChangedFor(ele) || this.doesEleInvalidateKey(ele);
  26755. }
  26756. }, {
  26757. key: "getCachesAt",
  26758. value: function getCachesAt(lvl) {
  26759. var cachesByLvl = this.cachesByLvl,
  26760. lvls = this.lvls;
  26761. var caches = cachesByLvl.get(lvl);
  26762. if (!caches) {
  26763. caches = new Map$1();
  26764. cachesByLvl.set(lvl, caches);
  26765. lvls.push(lvl);
  26766. }
  26767. return caches;
  26768. }
  26769. }, {
  26770. key: "getCache",
  26771. value: function getCache(key, lvl) {
  26772. return this.getCachesAt(lvl).get(key);
  26773. }
  26774. }, {
  26775. key: "get",
  26776. value: function get(ele, lvl) {
  26777. var key = this.getKey(ele);
  26778. var cache = this.getCache(key, lvl);
  26779. // getting for an element may need to add to the id list b/c eles can share keys
  26780. if (cache != null) {
  26781. this.updateKeyMappingFor(ele);
  26782. }
  26783. return cache;
  26784. }
  26785. }, {
  26786. key: "getForCachedKey",
  26787. value: function getForCachedKey(ele, lvl) {
  26788. var key = this.keyForId.get(ele.id()); // n.b. use cached key, not newly computed key
  26789. var cache = this.getCache(key, lvl);
  26790. return cache;
  26791. }
  26792. }, {
  26793. key: "hasCache",
  26794. value: function hasCache(key, lvl) {
  26795. return this.getCachesAt(lvl).has(key);
  26796. }
  26797. }, {
  26798. key: "has",
  26799. value: function has(ele, lvl) {
  26800. var key = this.getKey(ele);
  26801. return this.hasCache(key, lvl);
  26802. }
  26803. }, {
  26804. key: "setCache",
  26805. value: function setCache(key, lvl, cache) {
  26806. cache.key = key;
  26807. this.getCachesAt(lvl).set(key, cache);
  26808. }
  26809. }, {
  26810. key: "set",
  26811. value: function set(ele, lvl, cache) {
  26812. var key = this.getKey(ele);
  26813. this.setCache(key, lvl, cache);
  26814. this.updateKeyMappingFor(ele);
  26815. }
  26816. }, {
  26817. key: "deleteCache",
  26818. value: function deleteCache(key, lvl) {
  26819. this.getCachesAt(lvl)["delete"](key);
  26820. }
  26821. }, {
  26822. key: "delete",
  26823. value: function _delete(ele, lvl) {
  26824. var key = this.getKey(ele);
  26825. this.deleteCache(key, lvl);
  26826. }
  26827. }, {
  26828. key: "invalidateKey",
  26829. value: function invalidateKey(key) {
  26830. var _this = this;
  26831. this.lvls.forEach(function (lvl) {
  26832. return _this.deleteCache(key, lvl);
  26833. });
  26834. }
  26835. // returns true if no other eles reference the invalidated cache (n.b. other eles may need the cache with the same key)
  26836. }, {
  26837. key: "invalidate",
  26838. value: function invalidate(ele) {
  26839. var id = ele.id();
  26840. var key = this.keyForId.get(id); // n.b. use stored key rather than current (potential key)
  26841. this.deleteKeyMappingFor(ele);
  26842. var entireKeyInvalidated = this.doesEleInvalidateKey(ele);
  26843. if (entireKeyInvalidated) {
  26844. // clear mapping for current key
  26845. this.invalidateKey(key);
  26846. }
  26847. return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;
  26848. }
  26849. }]);
  26850. }();
  26851. var minTxrH = 25; // the size of the texture cache for small height eles (special case)
  26852. var txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up
  26853. var minLvl$1 = -4; // when scaling smaller than that we don't need to re-render
  26854. var maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)
  26855. var maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used
  26856. var eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps
  26857. var defTxrWidth = 1024; // default/minimum texture width
  26858. var maxTxrW = 1024; // the maximum width of a texture
  26859. var maxTxrH = 1024; // the maximum height of a texture
  26860. var minUtility = 0.2; // if usage of texture is less than this, it is retired
  26861. var maxFullness = 0.8; // fullness of texture after which queue removal is checked
  26862. var maxFullnessChecks = 10; // dequeued after this many checks
  26863. var deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
  26864. var deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time
  26865. var deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
  26866. var deqFastCost$1 = 0.9; // % of frame time to be used when >60fps
  26867. var deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
  26868. var maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch
  26869. var getTxrReasons = {
  26870. dequeue: 'dequeue',
  26871. downscale: 'downscale',
  26872. highQuality: 'highQuality'
  26873. };
  26874. var initDefaults = defaults$g({
  26875. getKey: null,
  26876. doesEleInvalidateKey: falsify,
  26877. drawElement: null,
  26878. getBoundingBox: null,
  26879. getRotationPoint: null,
  26880. getRotationOffset: null,
  26881. isVisible: trueify,
  26882. allowEdgeTxrCaching: true,
  26883. allowParentTxrCaching: true
  26884. });
  26885. var ElementTextureCache = function ElementTextureCache(renderer, initOptions) {
  26886. var self = this;
  26887. self.renderer = renderer;
  26888. self.onDequeues = [];
  26889. var opts = initDefaults(initOptions);
  26890. extend(self, opts);
  26891. self.lookup = new ElementTextureCacheLookup(opts.getKey, opts.doesEleInvalidateKey);
  26892. self.setupDequeueing();
  26893. };
  26894. var ETCp = ElementTextureCache.prototype;
  26895. ETCp.reasons = getTxrReasons;
  26896. // the list of textures in which new subtextures for elements can be placed
  26897. ETCp.getTextureQueue = function (txrH) {
  26898. var self = this;
  26899. self.eleImgCaches = self.eleImgCaches || {};
  26900. return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];
  26901. };
  26902. // the list of usused textures which can be recycled (in use in texture queue)
  26903. ETCp.getRetiredTextureQueue = function (txrH) {
  26904. var self = this;
  26905. var rtxtrQs = self.eleImgCaches.retired = self.eleImgCaches.retired || {};
  26906. var rtxtrQ = rtxtrQs[txrH] = rtxtrQs[txrH] || [];
  26907. return rtxtrQ;
  26908. };
  26909. // queue of element draw requests at different scale levels
  26910. ETCp.getElementQueue = function () {
  26911. var self = this;
  26912. var q = self.eleCacheQueue = self.eleCacheQueue || new Heap(function (a, b) {
  26913. return b.reqs - a.reqs;
  26914. });
  26915. return q;
  26916. };
  26917. // queue of element draw requests at different scale levels (element id lookup)
  26918. ETCp.getElementKeyToQueue = function () {
  26919. var self = this;
  26920. var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};
  26921. return k2q;
  26922. };
  26923. ETCp.getElement = function (ele, bb, pxRatio, lvl, reason) {
  26924. var self = this;
  26925. var r = this.renderer;
  26926. var zoom = r.cy.zoom();
  26927. var lookup = this.lookup;
  26928. if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {
  26929. return null;
  26930. }
  26931. if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {
  26932. return null;
  26933. }
  26934. if (lvl == null) {
  26935. lvl = Math.ceil(log2(zoom * pxRatio));
  26936. }
  26937. if (lvl < minLvl$1) {
  26938. lvl = minLvl$1;
  26939. } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {
  26940. return null;
  26941. }
  26942. var scale = Math.pow(2, lvl);
  26943. var eleScaledH = bb.h * scale;
  26944. var eleScaledW = bb.w * scale;
  26945. var scaledLabelShown = r.eleTextBiggerThanMin(ele, scale);
  26946. if (!this.isVisible(ele, scaledLabelShown)) {
  26947. return null;
  26948. }
  26949. var eleCache = lookup.get(ele, lvl);
  26950. // if this get was on an unused/invalidated cache, then restore the texture usage metric
  26951. if (eleCache && eleCache.invalidated) {
  26952. eleCache.invalidated = false;
  26953. eleCache.texture.invalidatedWidth -= eleCache.width;
  26954. }
  26955. if (eleCache) {
  26956. return eleCache;
  26957. }
  26958. var txrH; // which texture height this ele belongs to
  26959. if (eleScaledH <= minTxrH) {
  26960. txrH = minTxrH;
  26961. } else if (eleScaledH <= txrStepH) {
  26962. txrH = txrStepH;
  26963. } else {
  26964. txrH = Math.ceil(eleScaledH / txrStepH) * txrStepH;
  26965. }
  26966. if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {
  26967. return null; // caching large elements is not efficient
  26968. }
  26969. var txrQ = self.getTextureQueue(txrH);
  26970. // first try the second last one in case it has space at the end
  26971. var txr = txrQ[txrQ.length - 2];
  26972. var addNewTxr = function addNewTxr() {
  26973. return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);
  26974. };
  26975. // try the last one if there is no second last one
  26976. if (!txr) {
  26977. txr = txrQ[txrQ.length - 1];
  26978. }
  26979. // if the last one doesn't exist, we need a first one
  26980. if (!txr) {
  26981. txr = addNewTxr();
  26982. }
  26983. // if there's no room in the current texture, we need a new one
  26984. if (txr.width - txr.usedWidth < eleScaledW) {
  26985. txr = addNewTxr();
  26986. }
  26987. var scalableFrom = function scalableFrom(otherCache) {
  26988. return otherCache && otherCache.scaledLabelShown === scaledLabelShown;
  26989. };
  26990. var deqing = reason && reason === getTxrReasons.dequeue;
  26991. var highQualityReq = reason && reason === getTxrReasons.highQuality;
  26992. var downscaleReq = reason && reason === getTxrReasons.downscale;
  26993. var higherCache; // the nearest cache with a higher level
  26994. for (var l = lvl + 1; l <= maxLvl$1; l++) {
  26995. var c = lookup.get(ele, l);
  26996. if (c) {
  26997. higherCache = c;
  26998. break;
  26999. }
  27000. }
  27001. var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;
  27002. var downscale = function downscale() {
  27003. txr.context.drawImage(oneUpCache.texture.canvas, oneUpCache.x, 0, oneUpCache.width, oneUpCache.height, txr.usedWidth, 0, eleScaledW, eleScaledH);
  27004. };
  27005. // reset ele area in texture
  27006. txr.context.setTransform(1, 0, 0, 1, 0, 0);
  27007. txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);
  27008. if (scalableFrom(oneUpCache)) {
  27009. // then we can relatively cheaply rescale the existing image w/o rerendering
  27010. downscale();
  27011. } else if (scalableFrom(higherCache)) {
  27012. // then use the higher cache for now and queue the next level down
  27013. // to cheaply scale towards the smaller level
  27014. if (highQualityReq) {
  27015. for (var _l = higherCache.level; _l > lvl; _l--) {
  27016. oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);
  27017. }
  27018. downscale();
  27019. } else {
  27020. self.queueElement(ele, higherCache.level - 1);
  27021. return higherCache;
  27022. }
  27023. } else {
  27024. var lowerCache; // the nearest cache with a lower level
  27025. if (!deqing && !highQualityReq && !downscaleReq) {
  27026. for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {
  27027. var _c = lookup.get(ele, _l2);
  27028. if (_c) {
  27029. lowerCache = _c;
  27030. break;
  27031. }
  27032. }
  27033. }
  27034. if (scalableFrom(lowerCache)) {
  27035. // then use the lower quality cache for now and queue the better one for later
  27036. self.queueElement(ele, lvl);
  27037. return lowerCache;
  27038. }
  27039. txr.context.translate(txr.usedWidth, 0);
  27040. txr.context.scale(scale, scale);
  27041. this.drawElement(txr.context, ele, bb, scaledLabelShown, false);
  27042. txr.context.scale(1 / scale, 1 / scale);
  27043. txr.context.translate(-txr.usedWidth, 0);
  27044. }
  27045. eleCache = {
  27046. x: txr.usedWidth,
  27047. texture: txr,
  27048. level: lvl,
  27049. scale: scale,
  27050. width: eleScaledW,
  27051. height: eleScaledH,
  27052. scaledLabelShown: scaledLabelShown
  27053. };
  27054. txr.usedWidth += Math.ceil(eleScaledW + eleTxrSpacing);
  27055. txr.eleCaches.push(eleCache);
  27056. lookup.set(ele, lvl, eleCache);
  27057. self.checkTextureFullness(txr);
  27058. return eleCache;
  27059. };
  27060. ETCp.invalidateElements = function (eles) {
  27061. for (var i = 0; i < eles.length; i++) {
  27062. this.invalidateElement(eles[i]);
  27063. }
  27064. };
  27065. ETCp.invalidateElement = function (ele) {
  27066. var self = this;
  27067. var lookup = self.lookup;
  27068. var caches = [];
  27069. var invalid = lookup.isInvalid(ele);
  27070. if (!invalid) {
  27071. return; // override the invalidation request if the element key has not changed
  27072. }
  27073. for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {
  27074. var cache = lookup.getForCachedKey(ele, lvl);
  27075. if (cache) {
  27076. caches.push(cache);
  27077. }
  27078. }
  27079. var noOtherElesUseCache = lookup.invalidate(ele);
  27080. if (noOtherElesUseCache) {
  27081. for (var i = 0; i < caches.length; i++) {
  27082. var _cache = caches[i];
  27083. var txr = _cache.texture;
  27084. // remove space from the texture it belongs to
  27085. txr.invalidatedWidth += _cache.width;
  27086. // mark the cache as invalidated
  27087. _cache.invalidated = true;
  27088. // retire the texture if its utility is low
  27089. self.checkTextureUtility(txr);
  27090. }
  27091. }
  27092. // remove from queue since the old req was for the old state
  27093. self.removeFromQueue(ele);
  27094. };
  27095. ETCp.checkTextureUtility = function (txr) {
  27096. // invalidate all entries in the cache if the cache size is small
  27097. if (txr.invalidatedWidth >= minUtility * txr.width) {
  27098. this.retireTexture(txr);
  27099. }
  27100. };
  27101. ETCp.checkTextureFullness = function (txr) {
  27102. // if texture has been mostly filled and passed over several times, remove
  27103. // it from the queue so we don't need to waste time looking at it to put new things
  27104. var self = this;
  27105. var txrQ = self.getTextureQueue(txr.height);
  27106. if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {
  27107. removeFromArray(txrQ, txr);
  27108. } else {
  27109. txr.fullnessChecks++;
  27110. }
  27111. };
  27112. ETCp.retireTexture = function (txr) {
  27113. var self = this;
  27114. var txrH = txr.height;
  27115. var txrQ = self.getTextureQueue(txrH);
  27116. var lookup = this.lookup;
  27117. // retire the texture from the active / searchable queue:
  27118. removeFromArray(txrQ, txr);
  27119. txr.retired = true;
  27120. // remove the refs from the eles to the caches:
  27121. var eleCaches = txr.eleCaches;
  27122. for (var i = 0; i < eleCaches.length; i++) {
  27123. var eleCache = eleCaches[i];
  27124. lookup.deleteCache(eleCache.key, eleCache.level);
  27125. }
  27126. clearArray(eleCaches);
  27127. // add the texture to a retired queue so it can be recycled in future:
  27128. var rtxtrQ = self.getRetiredTextureQueue(txrH);
  27129. rtxtrQ.push(txr);
  27130. };
  27131. ETCp.addTexture = function (txrH, minW) {
  27132. var self = this;
  27133. var txrQ = self.getTextureQueue(txrH);
  27134. var txr = {};
  27135. txrQ.push(txr);
  27136. txr.eleCaches = [];
  27137. txr.height = txrH;
  27138. txr.width = Math.max(defTxrWidth, minW);
  27139. txr.usedWidth = 0;
  27140. txr.invalidatedWidth = 0;
  27141. txr.fullnessChecks = 0;
  27142. txr.canvas = self.renderer.makeOffscreenCanvas(txr.width, txr.height);
  27143. txr.context = txr.canvas.getContext('2d');
  27144. return txr;
  27145. };
  27146. ETCp.recycleTexture = function (txrH, minW) {
  27147. var self = this;
  27148. var txrQ = self.getTextureQueue(txrH);
  27149. var rtxtrQ = self.getRetiredTextureQueue(txrH);
  27150. for (var i = 0; i < rtxtrQ.length; i++) {
  27151. var txr = rtxtrQ[i];
  27152. if (txr.width >= minW) {
  27153. txr.retired = false;
  27154. txr.usedWidth = 0;
  27155. txr.invalidatedWidth = 0;
  27156. txr.fullnessChecks = 0;
  27157. clearArray(txr.eleCaches);
  27158. txr.context.setTransform(1, 0, 0, 1, 0, 0);
  27159. txr.context.clearRect(0, 0, txr.width, txr.height);
  27160. removeFromArray(rtxtrQ, txr);
  27161. txrQ.push(txr);
  27162. return txr;
  27163. }
  27164. }
  27165. };
  27166. ETCp.queueElement = function (ele, lvl) {
  27167. var self = this;
  27168. var q = self.getElementQueue();
  27169. var k2q = self.getElementKeyToQueue();
  27170. var key = this.getKey(ele);
  27171. var existingReq = k2q[key];
  27172. if (existingReq) {
  27173. // use the max lvl b/c in between lvls are cheap to make
  27174. existingReq.level = Math.max(existingReq.level, lvl);
  27175. existingReq.eles.merge(ele);
  27176. existingReq.reqs++;
  27177. q.updateItem(existingReq);
  27178. } else {
  27179. var req = {
  27180. eles: ele.spawn().merge(ele),
  27181. level: lvl,
  27182. reqs: 1,
  27183. key: key
  27184. };
  27185. q.push(req);
  27186. k2q[key] = req;
  27187. }
  27188. };
  27189. ETCp.dequeue = function (pxRatio /*, extent*/) {
  27190. var self = this;
  27191. var q = self.getElementQueue();
  27192. var k2q = self.getElementKeyToQueue();
  27193. var dequeued = [];
  27194. var lookup = self.lookup;
  27195. for (var i = 0; i < maxDeqSize$1; i++) {
  27196. if (q.size() > 0) {
  27197. var req = q.pop();
  27198. var key = req.key;
  27199. var ele = req.eles[0]; // all eles have the same key
  27200. var cacheExists = lookup.hasCache(ele, req.level);
  27201. // clear out the key to req lookup
  27202. k2q[key] = null;
  27203. // dequeueing isn't necessary with an existing cache
  27204. if (cacheExists) {
  27205. continue;
  27206. }
  27207. dequeued.push(req);
  27208. var bb = self.getBoundingBox(ele);
  27209. self.getElement(ele, bb, pxRatio, req.level, getTxrReasons.dequeue);
  27210. } else {
  27211. break;
  27212. }
  27213. }
  27214. return dequeued;
  27215. };
  27216. ETCp.removeFromQueue = function (ele) {
  27217. var self = this;
  27218. var q = self.getElementQueue();
  27219. var k2q = self.getElementKeyToQueue();
  27220. var key = this.getKey(ele);
  27221. var req = k2q[key];
  27222. if (req != null) {
  27223. if (req.eles.length === 1) {
  27224. // remove if last ele in the req
  27225. // bring to front of queue
  27226. req.reqs = MAX_INT$1;
  27227. q.updateItem(req);
  27228. q.pop(); // remove from queue
  27229. k2q[key] = null; // remove from lookup map
  27230. } else {
  27231. // otherwise just remove ele from req
  27232. req.eles.unmerge(ele);
  27233. }
  27234. }
  27235. };
  27236. ETCp.onDequeue = function (fn) {
  27237. this.onDequeues.push(fn);
  27238. };
  27239. ETCp.offDequeue = function (fn) {
  27240. removeFromArray(this.onDequeues, fn);
  27241. };
  27242. ETCp.setupDequeueing = defs.setupDequeueing({
  27243. deqRedrawThreshold: deqRedrawThreshold$1,
  27244. deqCost: deqCost$1,
  27245. deqAvgCost: deqAvgCost$1,
  27246. deqNoDrawCost: deqNoDrawCost$1,
  27247. deqFastCost: deqFastCost$1,
  27248. deq: function deq(self, pxRatio, extent) {
  27249. return self.dequeue(pxRatio, extent);
  27250. },
  27251. onDeqd: function onDeqd(self, deqd) {
  27252. for (var i = 0; i < self.onDequeues.length; i++) {
  27253. var fn = self.onDequeues[i];
  27254. fn(deqd);
  27255. }
  27256. },
  27257. shouldRedraw: function shouldRedraw(self, deqd, pxRatio, extent) {
  27258. for (var i = 0; i < deqd.length; i++) {
  27259. var eles = deqd[i].eles;
  27260. for (var j = 0; j < eles.length; j++) {
  27261. var bb = eles[j].boundingBox();
  27262. if (boundingBoxesIntersect(bb, extent)) {
  27263. return true;
  27264. }
  27265. }
  27266. }
  27267. return false;
  27268. },
  27269. priority: function priority(self) {
  27270. return self.renderer.beforeRenderPriorities.eleTxrDeq;
  27271. }
  27272. });
  27273. var defNumLayers = 1; // default number of layers to use
  27274. var minLvl = -4; // when scaling smaller than that we don't need to re-render
  27275. var maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)
  27276. var maxZoom = 3.99; // beyond this zoom level, layered textures are not used
  27277. var deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
  27278. var refineEleDebounceTime = 50; // time to debounce sharper ele texture updates
  27279. var deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
  27280. var deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time
  27281. var deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
  27282. var deqFastCost = 0.9; // % of frame time to be used when >60fps
  27283. var maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch
  27284. var invalidThreshold = 250; // time threshold for disabling b/c of invalidations
  27285. var maxLayerArea = 4000 * 4000; // layers can't be bigger than this
  27286. var maxLayerDim = 32767; // maximum size for the width/height of layer canvases
  27287. var useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)
  27288. // var log = function(){ console.log.apply( console, arguments ); };
  27289. var LayeredTextureCache = function LayeredTextureCache(renderer) {
  27290. var self = this;
  27291. var r = self.renderer = renderer;
  27292. var cy = r.cy;
  27293. self.layersByLevel = {}; // e.g. 2 => [ layer1, layer2, ..., layerN ]
  27294. self.firstGet = true;
  27295. self.lastInvalidationTime = performanceNow() - 2 * invalidThreshold;
  27296. self.skipping = false;
  27297. self.eleTxrDeqs = cy.collection();
  27298. self.scheduleElementRefinement = debounce(function () {
  27299. self.refineElementTextures(self.eleTxrDeqs);
  27300. self.eleTxrDeqs.unmerge(self.eleTxrDeqs);
  27301. }, refineEleDebounceTime);
  27302. r.beforeRender(function (willDraw, now) {
  27303. if (now - self.lastInvalidationTime <= invalidThreshold) {
  27304. self.skipping = true;
  27305. } else {
  27306. self.skipping = false;
  27307. }
  27308. }, r.beforeRenderPriorities.lyrTxrSkip);
  27309. var qSort = function qSort(a, b) {
  27310. return b.reqs - a.reqs;
  27311. };
  27312. self.layersQueue = new Heap(qSort);
  27313. self.setupDequeueing();
  27314. };
  27315. var LTCp = LayeredTextureCache.prototype;
  27316. var layerIdPool = 0;
  27317. var MAX_INT = Math.pow(2, 53) - 1;
  27318. LTCp.makeLayer = function (bb, lvl) {
  27319. var scale = Math.pow(2, lvl);
  27320. var w = Math.ceil(bb.w * scale);
  27321. var h = Math.ceil(bb.h * scale);
  27322. var canvas = this.renderer.makeOffscreenCanvas(w, h);
  27323. var layer = {
  27324. id: layerIdPool = ++layerIdPool % MAX_INT,
  27325. bb: bb,
  27326. level: lvl,
  27327. width: w,
  27328. height: h,
  27329. canvas: canvas,
  27330. context: canvas.getContext('2d'),
  27331. eles: [],
  27332. elesQueue: [],
  27333. reqs: 0
  27334. };
  27335. // log('make layer %s with w %s and h %s and lvl %s', layer.id, layer.width, layer.height, layer.level);
  27336. var cxt = layer.context;
  27337. var dx = -layer.bb.x1;
  27338. var dy = -layer.bb.y1;
  27339. // do the transform on creation to save cycles (it's the same for all eles)
  27340. cxt.scale(scale, scale);
  27341. cxt.translate(dx, dy);
  27342. return layer;
  27343. };
  27344. LTCp.getLayers = function (eles, pxRatio, lvl) {
  27345. var self = this;
  27346. var r = self.renderer;
  27347. var cy = r.cy;
  27348. var zoom = cy.zoom();
  27349. var firstGet = self.firstGet;
  27350. self.firstGet = false;
  27351. // log('--\nget layers with %s eles', eles.length);
  27352. //log eles.map(function(ele){ return ele.id() }) );
  27353. if (lvl == null) {
  27354. lvl = Math.ceil(log2(zoom * pxRatio));
  27355. if (lvl < minLvl) {
  27356. lvl = minLvl;
  27357. } else if (zoom >= maxZoom || lvl > maxLvl) {
  27358. return null;
  27359. }
  27360. }
  27361. self.validateLayersElesOrdering(lvl, eles);
  27362. var layersByLvl = self.layersByLevel;
  27363. var scale = Math.pow(2, lvl);
  27364. var layers = layersByLvl[lvl] = layersByLvl[lvl] || [];
  27365. var bb;
  27366. var lvlComplete = self.levelIsComplete(lvl, eles);
  27367. var tmpLayers;
  27368. var checkTempLevels = function checkTempLevels() {
  27369. var canUseAsTmpLvl = function canUseAsTmpLvl(l) {
  27370. self.validateLayersElesOrdering(l, eles);
  27371. if (self.levelIsComplete(l, eles)) {
  27372. tmpLayers = layersByLvl[l];
  27373. return true;
  27374. }
  27375. };
  27376. var checkLvls = function checkLvls(dir) {
  27377. if (tmpLayers) {
  27378. return;
  27379. }
  27380. for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {
  27381. if (canUseAsTmpLvl(l)) {
  27382. break;
  27383. }
  27384. }
  27385. };
  27386. checkLvls(1);
  27387. checkLvls(-1);
  27388. // remove the invalid layers; they will be replaced as needed later in this function
  27389. for (var i = layers.length - 1; i >= 0; i--) {
  27390. var layer = layers[i];
  27391. if (layer.invalid) {
  27392. removeFromArray(layers, layer);
  27393. }
  27394. }
  27395. };
  27396. if (!lvlComplete) {
  27397. // if the current level is incomplete, then use the closest, best quality layerset temporarily
  27398. // and later queue the current layerset so we can get the proper quality level soon
  27399. checkTempLevels();
  27400. } else {
  27401. // log('level complete, using existing layers\n--');
  27402. return layers;
  27403. }
  27404. var getBb = function getBb() {
  27405. if (!bb) {
  27406. bb = makeBoundingBox();
  27407. for (var i = 0; i < eles.length; i++) {
  27408. updateBoundingBox(bb, eles[i].boundingBox());
  27409. }
  27410. }
  27411. return bb;
  27412. };
  27413. var makeLayer = function makeLayer(opts) {
  27414. opts = opts || {};
  27415. var after = opts.after;
  27416. getBb();
  27417. var w = Math.ceil(bb.w * scale);
  27418. var h = Math.ceil(bb.h * scale);
  27419. if (w > maxLayerDim || h > maxLayerDim) {
  27420. return null;
  27421. }
  27422. var area = w * h;
  27423. if (area > maxLayerArea) {
  27424. return null;
  27425. }
  27426. var layer = self.makeLayer(bb, lvl);
  27427. if (after != null) {
  27428. var index = layers.indexOf(after) + 1;
  27429. layers.splice(index, 0, layer);
  27430. } else if (opts.insert === undefined || opts.insert) {
  27431. // no after specified => first layer made so put at start
  27432. layers.unshift(layer);
  27433. }
  27434. // if( tmpLayers ){
  27435. //self.queueLayer( layer );
  27436. // }
  27437. return layer;
  27438. };
  27439. if (self.skipping && !firstGet) {
  27440. // log('skip layers');
  27441. return null;
  27442. }
  27443. // log('do layers');
  27444. var layer = null;
  27445. var maxElesPerLayer = eles.length / defNumLayers;
  27446. var allowLazyQueueing = !firstGet;
  27447. for (var i = 0; i < eles.length; i++) {
  27448. var ele = eles[i];
  27449. var rs = ele._private.rscratch;
  27450. var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
  27451. // log('look at ele', ele.id());
  27452. var existingLayer = caches[lvl];
  27453. if (existingLayer) {
  27454. // reuse layer for later eles
  27455. // log('reuse layer for', ele.id());
  27456. layer = existingLayer;
  27457. continue;
  27458. }
  27459. if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {
  27460. // log('make new layer for ele %s', ele.id());
  27461. layer = makeLayer({
  27462. insert: true,
  27463. after: layer
  27464. });
  27465. // if now layer can be built then we can't use layers at this level
  27466. if (!layer) {
  27467. return null;
  27468. }
  27469. // log('new layer with id %s', layer.id);
  27470. }
  27471. if (tmpLayers || allowLazyQueueing) {
  27472. // log('queue ele %s in layer %s', ele.id(), layer.id);
  27473. self.queueLayer(layer, ele);
  27474. } else {
  27475. // log('draw ele %s in layer %s', ele.id(), layer.id);
  27476. self.drawEleInLayer(layer, ele, lvl, pxRatio);
  27477. }
  27478. layer.eles.push(ele);
  27479. caches[lvl] = layer;
  27480. }
  27481. // log('--');
  27482. if (tmpLayers) {
  27483. // then we only queued the current layerset and can't draw it yet
  27484. return tmpLayers;
  27485. }
  27486. if (allowLazyQueueing) {
  27487. // log('lazy queue level', lvl);
  27488. return null;
  27489. }
  27490. return layers;
  27491. };
  27492. // a layer may want to use an ele cache of a higher level to avoid blurriness
  27493. // so the layer level might not equal the ele level
  27494. LTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {
  27495. return lvl;
  27496. };
  27497. LTCp.drawEleInLayer = function (layer, ele, lvl, pxRatio) {
  27498. var self = this;
  27499. var r = this.renderer;
  27500. var context = layer.context;
  27501. var bb = ele.boundingBox();
  27502. if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
  27503. return;
  27504. }
  27505. lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);
  27506. {
  27507. r.setImgSmoothing(context, false);
  27508. }
  27509. {
  27510. r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);
  27511. }
  27512. {
  27513. r.setImgSmoothing(context, true);
  27514. }
  27515. };
  27516. LTCp.levelIsComplete = function (lvl, eles) {
  27517. var self = this;
  27518. var layers = self.layersByLevel[lvl];
  27519. if (!layers || layers.length === 0) {
  27520. return false;
  27521. }
  27522. var numElesInLayers = 0;
  27523. for (var i = 0; i < layers.length; i++) {
  27524. var layer = layers[i];
  27525. // if there are any eles needed to be drawn yet, the level is not complete
  27526. if (layer.reqs > 0) {
  27527. return false;
  27528. }
  27529. // if the layer is invalid, the level is not complete
  27530. if (layer.invalid) {
  27531. return false;
  27532. }
  27533. numElesInLayers += layer.eles.length;
  27534. }
  27535. // we should have exactly the number of eles passed in to be complete
  27536. if (numElesInLayers !== eles.length) {
  27537. return false;
  27538. }
  27539. return true;
  27540. };
  27541. LTCp.validateLayersElesOrdering = function (lvl, eles) {
  27542. var layers = this.layersByLevel[lvl];
  27543. if (!layers) {
  27544. return;
  27545. }
  27546. // if in a layer the eles are not in the same order, then the layer is invalid
  27547. // (i.e. there is an ele in between the eles in the layer)
  27548. for (var i = 0; i < layers.length; i++) {
  27549. var layer = layers[i];
  27550. var offset = -1;
  27551. // find the offset
  27552. for (var j = 0; j < eles.length; j++) {
  27553. if (layer.eles[0] === eles[j]) {
  27554. offset = j;
  27555. break;
  27556. }
  27557. }
  27558. if (offset < 0) {
  27559. // then the layer has nonexistent elements and is invalid
  27560. this.invalidateLayer(layer);
  27561. continue;
  27562. }
  27563. // the eles in the layer must be in the same continuous order, else the layer is invalid
  27564. var o = offset;
  27565. for (var j = 0; j < layer.eles.length; j++) {
  27566. if (layer.eles[j] !== eles[o + j]) {
  27567. // log('invalidate based on ordering', layer.id);
  27568. this.invalidateLayer(layer);
  27569. break;
  27570. }
  27571. }
  27572. }
  27573. };
  27574. LTCp.updateElementsInLayers = function (eles, update) {
  27575. var self = this;
  27576. var isEles = element(eles[0]);
  27577. // collect udpated elements (cascaded from the layers) and update each
  27578. // layer itself along the way
  27579. for (var i = 0; i < eles.length; i++) {
  27580. var req = isEles ? null : eles[i];
  27581. var ele = isEles ? eles[i] : eles[i].ele;
  27582. var rs = ele._private.rscratch;
  27583. var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
  27584. for (var l = minLvl; l <= maxLvl; l++) {
  27585. var layer = caches[l];
  27586. if (!layer) {
  27587. continue;
  27588. }
  27589. // if update is a request from the ele cache, then it affects only
  27590. // the matching level
  27591. if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {
  27592. continue;
  27593. }
  27594. update(layer, ele, req);
  27595. }
  27596. }
  27597. };
  27598. LTCp.haveLayers = function () {
  27599. var self = this;
  27600. var haveLayers = false;
  27601. for (var l = minLvl; l <= maxLvl; l++) {
  27602. var layers = self.layersByLevel[l];
  27603. if (layers && layers.length > 0) {
  27604. haveLayers = true;
  27605. break;
  27606. }
  27607. }
  27608. return haveLayers;
  27609. };
  27610. LTCp.invalidateElements = function (eles) {
  27611. var self = this;
  27612. if (eles.length === 0) {
  27613. return;
  27614. }
  27615. self.lastInvalidationTime = performanceNow();
  27616. // log('update invalidate layer time from eles');
  27617. if (eles.length === 0 || !self.haveLayers()) {
  27618. return;
  27619. }
  27620. self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {
  27621. self.invalidateLayer(layer);
  27622. });
  27623. };
  27624. LTCp.invalidateLayer = function (layer) {
  27625. // log('update invalidate layer time');
  27626. this.lastInvalidationTime = performanceNow();
  27627. if (layer.invalid) {
  27628. return;
  27629. } // save cycles
  27630. var lvl = layer.level;
  27631. var eles = layer.eles;
  27632. var layers = this.layersByLevel[lvl];
  27633. // log('invalidate layer', layer.id );
  27634. removeFromArray(layers, layer);
  27635. // layer.eles = [];
  27636. layer.elesQueue = [];
  27637. layer.invalid = true;
  27638. if (layer.replacement) {
  27639. layer.replacement.invalid = true;
  27640. }
  27641. for (var i = 0; i < eles.length; i++) {
  27642. var caches = eles[i]._private.rscratch.imgLayerCaches;
  27643. if (caches) {
  27644. caches[lvl] = null;
  27645. }
  27646. }
  27647. };
  27648. LTCp.refineElementTextures = function (eles) {
  27649. var self = this;
  27650. // log('refine', eles.length);
  27651. self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {
  27652. var rLyr = layer.replacement;
  27653. if (!rLyr) {
  27654. rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);
  27655. rLyr.replaces = layer;
  27656. rLyr.eles = layer.eles;
  27657. // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);
  27658. }
  27659. if (!rLyr.reqs) {
  27660. for (var i = 0; i < rLyr.eles.length; i++) {
  27661. self.queueLayer(rLyr, rLyr.eles[i]);
  27662. }
  27663. // log('queue replacement layer refinement', rLyr.id);
  27664. }
  27665. });
  27666. };
  27667. LTCp.enqueueElementRefinement = function (ele) {
  27668. this.eleTxrDeqs.merge(ele);
  27669. this.scheduleElementRefinement();
  27670. };
  27671. LTCp.queueLayer = function (layer, ele) {
  27672. var self = this;
  27673. var q = self.layersQueue;
  27674. var elesQ = layer.elesQueue;
  27675. var hasId = elesQ.hasId = elesQ.hasId || {};
  27676. // if a layer is going to be replaced, queuing is a waste of time
  27677. if (layer.replacement) {
  27678. return;
  27679. }
  27680. if (ele) {
  27681. if (hasId[ele.id()]) {
  27682. return;
  27683. }
  27684. elesQ.push(ele);
  27685. hasId[ele.id()] = true;
  27686. }
  27687. if (layer.reqs) {
  27688. layer.reqs++;
  27689. q.updateItem(layer);
  27690. } else {
  27691. layer.reqs = 1;
  27692. q.push(layer);
  27693. }
  27694. };
  27695. LTCp.dequeue = function (pxRatio) {
  27696. var self = this;
  27697. var q = self.layersQueue;
  27698. var deqd = [];
  27699. var eleDeqs = 0;
  27700. while (eleDeqs < maxDeqSize) {
  27701. if (q.size() === 0) {
  27702. break;
  27703. }
  27704. var layer = q.peek();
  27705. // if a layer has been or will be replaced, then don't waste time with it
  27706. if (layer.replacement) {
  27707. // log('layer %s in queue skipped b/c it already has a replacement', layer.id);
  27708. q.pop();
  27709. continue;
  27710. }
  27711. // if this is a replacement layer that has been superceded, then forget it
  27712. if (layer.replaces && layer !== layer.replaces.replacement) {
  27713. // log('layer is no longer the most uptodate replacement; dequeued', layer.id)
  27714. q.pop();
  27715. continue;
  27716. }
  27717. if (layer.invalid) {
  27718. // log('replacement layer %s is invalid; dequeued', layer.id);
  27719. q.pop();
  27720. continue;
  27721. }
  27722. var ele = layer.elesQueue.shift();
  27723. if (ele) {
  27724. // log('dequeue layer %s', layer.id);
  27725. self.drawEleInLayer(layer, ele, layer.level, pxRatio);
  27726. eleDeqs++;
  27727. }
  27728. if (deqd.length === 0) {
  27729. // we need only one entry in deqd to queue redrawing etc
  27730. deqd.push(true);
  27731. }
  27732. // if the layer has all its eles done, then remove from the queue
  27733. if (layer.elesQueue.length === 0) {
  27734. q.pop();
  27735. layer.reqs = 0;
  27736. // log('dequeue of layer %s complete', layer.id);
  27737. // when a replacement layer is dequeued, it replaces the old layer in the level
  27738. if (layer.replaces) {
  27739. self.applyLayerReplacement(layer);
  27740. }
  27741. self.requestRedraw();
  27742. }
  27743. }
  27744. return deqd;
  27745. };
  27746. LTCp.applyLayerReplacement = function (layer) {
  27747. var self = this;
  27748. var layersInLevel = self.layersByLevel[layer.level];
  27749. var replaced = layer.replaces;
  27750. var index = layersInLevel.indexOf(replaced);
  27751. // if the replaced layer is not in the active list for the level, then replacing
  27752. // refs would be a mistake (i.e. overwriting the true active layer)
  27753. if (index < 0 || replaced.invalid) {
  27754. // log('replacement layer would have no effect', layer.id);
  27755. return;
  27756. }
  27757. layersInLevel[index] = layer; // replace level ref
  27758. // replace refs in eles
  27759. for (var i = 0; i < layer.eles.length; i++) {
  27760. var _p = layer.eles[i]._private;
  27761. var cache = _p.imgLayerCaches = _p.imgLayerCaches || {};
  27762. if (cache) {
  27763. cache[layer.level] = layer;
  27764. }
  27765. }
  27766. // log('apply replacement layer %s over %s', layer.id, replaced.id);
  27767. self.requestRedraw();
  27768. };
  27769. LTCp.requestRedraw = debounce(function () {
  27770. var r = this.renderer;
  27771. r.redrawHint('eles', true);
  27772. r.redrawHint('drag', true);
  27773. r.redraw();
  27774. }, 100);
  27775. LTCp.setupDequeueing = defs.setupDequeueing({
  27776. deqRedrawThreshold: deqRedrawThreshold,
  27777. deqCost: deqCost,
  27778. deqAvgCost: deqAvgCost,
  27779. deqNoDrawCost: deqNoDrawCost,
  27780. deqFastCost: deqFastCost,
  27781. deq: function deq(self, pxRatio) {
  27782. return self.dequeue(pxRatio);
  27783. },
  27784. onDeqd: noop$1,
  27785. shouldRedraw: trueify,
  27786. priority: function priority(self) {
  27787. return self.renderer.beforeRenderPriorities.lyrTxrDeq;
  27788. }
  27789. });
  27790. var CRp$b = {};
  27791. var impl;
  27792. function polygon(context, points) {
  27793. for (var i = 0; i < points.length; i++) {
  27794. var pt = points[i];
  27795. context.lineTo(pt.x, pt.y);
  27796. }
  27797. }
  27798. function triangleBackcurve(context, points, controlPoint) {
  27799. var firstPt;
  27800. for (var i = 0; i < points.length; i++) {
  27801. var pt = points[i];
  27802. if (i === 0) {
  27803. firstPt = pt;
  27804. }
  27805. context.lineTo(pt.x, pt.y);
  27806. }
  27807. context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);
  27808. }
  27809. function triangleTee(context, trianglePoints, teePoints) {
  27810. if (context.beginPath) {
  27811. context.beginPath();
  27812. }
  27813. var triPts = trianglePoints;
  27814. for (var i = 0; i < triPts.length; i++) {
  27815. var pt = triPts[i];
  27816. context.lineTo(pt.x, pt.y);
  27817. }
  27818. var teePts = teePoints;
  27819. var firstTeePt = teePoints[0];
  27820. context.moveTo(firstTeePt.x, firstTeePt.y);
  27821. for (var i = 1; i < teePts.length; i++) {
  27822. var pt = teePts[i];
  27823. context.lineTo(pt.x, pt.y);
  27824. }
  27825. if (context.closePath) {
  27826. context.closePath();
  27827. }
  27828. }
  27829. function circleTriangle(context, trianglePoints, rx, ry, r) {
  27830. if (context.beginPath) {
  27831. context.beginPath();
  27832. }
  27833. context.arc(rx, ry, r, 0, Math.PI * 2, false);
  27834. var triPts = trianglePoints;
  27835. var firstTrPt = triPts[0];
  27836. context.moveTo(firstTrPt.x, firstTrPt.y);
  27837. for (var i = 0; i < triPts.length; i++) {
  27838. var pt = triPts[i];
  27839. context.lineTo(pt.x, pt.y);
  27840. }
  27841. if (context.closePath) {
  27842. context.closePath();
  27843. }
  27844. }
  27845. function circle$1(context, rx, ry, r) {
  27846. context.arc(rx, ry, r, 0, Math.PI * 2, false);
  27847. }
  27848. CRp$b.arrowShapeImpl = function (name) {
  27849. return (impl || (impl = {
  27850. 'polygon': polygon,
  27851. 'triangle-backcurve': triangleBackcurve,
  27852. 'triangle-tee': triangleTee,
  27853. 'circle-triangle': circleTriangle,
  27854. 'triangle-cross': triangleTee,
  27855. 'circle': circle$1
  27856. }))[name];
  27857. };
  27858. var CRp$a = {};
  27859. CRp$a.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {
  27860. var r = this;
  27861. if (ele.isNode()) {
  27862. r.drawNode(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  27863. } else {
  27864. r.drawEdge(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  27865. }
  27866. };
  27867. CRp$a.drawElementOverlay = function (context, ele) {
  27868. var r = this;
  27869. if (ele.isNode()) {
  27870. r.drawNodeOverlay(context, ele);
  27871. } else {
  27872. r.drawEdgeOverlay(context, ele);
  27873. }
  27874. };
  27875. CRp$a.drawElementUnderlay = function (context, ele) {
  27876. var r = this;
  27877. if (ele.isNode()) {
  27878. r.drawNodeUnderlay(context, ele);
  27879. } else {
  27880. r.drawEdgeUnderlay(context, ele);
  27881. }
  27882. };
  27883. CRp$a.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {
  27884. var r = this;
  27885. var bb = eleTxrCache.getBoundingBox(ele);
  27886. if (bb.w === 0 || bb.h === 0) {
  27887. return;
  27888. } // ignore zero size case
  27889. var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);
  27890. if (eleCache != null) {
  27891. var opacity = getOpacity(r, ele);
  27892. if (opacity === 0) {
  27893. return;
  27894. }
  27895. var theta = getRotation(r, ele);
  27896. var x1 = bb.x1,
  27897. y1 = bb.y1,
  27898. w = bb.w,
  27899. h = bb.h;
  27900. var x, y, sx, sy, smooth;
  27901. if (theta !== 0) {
  27902. var rotPt = eleTxrCache.getRotationPoint(ele);
  27903. sx = rotPt.x;
  27904. sy = rotPt.y;
  27905. context.translate(sx, sy);
  27906. context.rotate(theta);
  27907. smooth = r.getImgSmoothing(context);
  27908. if (!smooth) {
  27909. r.setImgSmoothing(context, true);
  27910. }
  27911. var off = eleTxrCache.getRotationOffset(ele);
  27912. x = off.x;
  27913. y = off.y;
  27914. } else {
  27915. x = x1;
  27916. y = y1;
  27917. }
  27918. var oldGlobalAlpha;
  27919. if (opacity !== 1) {
  27920. oldGlobalAlpha = context.globalAlpha;
  27921. context.globalAlpha = oldGlobalAlpha * opacity;
  27922. }
  27923. context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);
  27924. if (opacity !== 1) {
  27925. context.globalAlpha = oldGlobalAlpha;
  27926. }
  27927. if (theta !== 0) {
  27928. context.rotate(-theta);
  27929. context.translate(-sx, -sy);
  27930. if (!smooth) {
  27931. r.setImgSmoothing(context, false);
  27932. }
  27933. }
  27934. } else {
  27935. eleTxrCache.drawElement(context, ele); // direct draw fallback
  27936. }
  27937. };
  27938. var getZeroRotation = function getZeroRotation() {
  27939. return 0;
  27940. };
  27941. var getLabelRotation = function getLabelRotation(r, ele) {
  27942. return r.getTextAngle(ele, null);
  27943. };
  27944. var getSourceLabelRotation = function getSourceLabelRotation(r, ele) {
  27945. return r.getTextAngle(ele, 'source');
  27946. };
  27947. var getTargetLabelRotation = function getTargetLabelRotation(r, ele) {
  27948. return r.getTextAngle(ele, 'target');
  27949. };
  27950. var getOpacity = function getOpacity(r, ele) {
  27951. return ele.effectiveOpacity();
  27952. };
  27953. var getTextOpacity = function getTextOpacity(e, ele) {
  27954. return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();
  27955. };
  27956. CRp$a.drawCachedElement = function (context, ele, pxRatio, extent, lvl, requestHighQuality) {
  27957. var r = this;
  27958. var _r$data = r.data,
  27959. eleTxrCache = _r$data.eleTxrCache,
  27960. lblTxrCache = _r$data.lblTxrCache,
  27961. slbTxrCache = _r$data.slbTxrCache,
  27962. tlbTxrCache = _r$data.tlbTxrCache;
  27963. var bb = ele.boundingBox();
  27964. var reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;
  27965. if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
  27966. return;
  27967. }
  27968. if (!extent || boundingBoxesIntersect(bb, extent)) {
  27969. var isEdge = ele.isEdge();
  27970. var badLine = ele.element()._private.rscratch.badLine;
  27971. r.drawElementUnderlay(context, ele);
  27972. r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);
  27973. if (!isEdge || !badLine) {
  27974. r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);
  27975. }
  27976. if (isEdge && !badLine) {
  27977. r.drawCachedElementPortion(context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation, getTextOpacity);
  27978. r.drawCachedElementPortion(context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation, getTextOpacity);
  27979. }
  27980. r.drawElementOverlay(context, ele);
  27981. }
  27982. };
  27983. CRp$a.drawElements = function (context, eles) {
  27984. var r = this;
  27985. for (var i = 0; i < eles.length; i++) {
  27986. var ele = eles[i];
  27987. r.drawElement(context, ele);
  27988. }
  27989. };
  27990. CRp$a.drawCachedElements = function (context, eles, pxRatio, extent) {
  27991. var r = this;
  27992. for (var i = 0; i < eles.length; i++) {
  27993. var ele = eles[i];
  27994. r.drawCachedElement(context, ele, pxRatio, extent);
  27995. }
  27996. };
  27997. CRp$a.drawCachedNodes = function (context, eles, pxRatio, extent) {
  27998. var r = this;
  27999. for (var i = 0; i < eles.length; i++) {
  28000. var ele = eles[i];
  28001. if (!ele.isNode()) {
  28002. continue;
  28003. }
  28004. r.drawCachedElement(context, ele, pxRatio, extent);
  28005. }
  28006. };
  28007. CRp$a.drawLayeredElements = function (context, eles, pxRatio, extent) {
  28008. var r = this;
  28009. var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);
  28010. if (layers) {
  28011. for (var i = 0; i < layers.length; i++) {
  28012. var layer = layers[i];
  28013. var bb = layer.bb;
  28014. if (bb.w === 0 || bb.h === 0) {
  28015. continue;
  28016. }
  28017. context.drawImage(layer.canvas, bb.x1, bb.y1, bb.w, bb.h);
  28018. }
  28019. } else {
  28020. // fall back on plain caching if no layers
  28021. r.drawCachedElements(context, eles, pxRatio, extent);
  28022. }
  28023. };
  28024. var CRp$9 = {};
  28025. CRp$9.drawEdge = function (context, edge, shiftToOriginWithBb) {
  28026. var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28027. var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28028. var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28029. var r = this;
  28030. var rs = edge._private.rscratch;
  28031. if (shouldDrawOpacity && !edge.visible()) {
  28032. return;
  28033. }
  28034. // if bezier ctrl pts can not be calculated, then die
  28035. if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
  28036. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  28037. return;
  28038. }
  28039. var bb;
  28040. if (shiftToOriginWithBb) {
  28041. bb = shiftToOriginWithBb;
  28042. context.translate(-bb.x1, -bb.y1);
  28043. }
  28044. var opacity = shouldDrawOpacity ? edge.pstyle('opacity').value : 1;
  28045. var lineOpacity = shouldDrawOpacity ? edge.pstyle('line-opacity').value : 1;
  28046. var curveStyle = edge.pstyle('curve-style').value;
  28047. var lineStyle = edge.pstyle('line-style').value;
  28048. var edgeWidth = edge.pstyle('width').pfValue;
  28049. var lineCap = edge.pstyle('line-cap').value;
  28050. var lineOutlineWidth = edge.pstyle('line-outline-width').value;
  28051. var lineOutlineColor = edge.pstyle('line-outline-color').value;
  28052. var effectiveLineOpacity = opacity * lineOpacity;
  28053. // separate arrow opacity would require arrow-opacity property
  28054. var effectiveArrowOpacity = opacity * lineOpacity;
  28055. var drawLine = function drawLine() {
  28056. var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
  28057. if (curveStyle === 'straight-triangle') {
  28058. r.eleStrokeStyle(context, edge, strokeOpacity);
  28059. r.drawEdgeTrianglePath(edge, context, rs.allpts);
  28060. } else {
  28061. context.lineWidth = edgeWidth;
  28062. context.lineCap = lineCap;
  28063. r.eleStrokeStyle(context, edge, strokeOpacity);
  28064. r.drawEdgePath(edge, context, rs.allpts, lineStyle);
  28065. context.lineCap = 'butt'; // reset for other drawing functions
  28066. }
  28067. };
  28068. var drawLineOutline = function drawLineOutline() {
  28069. var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
  28070. context.lineWidth = edgeWidth + lineOutlineWidth;
  28071. context.lineCap = lineCap;
  28072. if (lineOutlineWidth > 0) {
  28073. r.colorStrokeStyle(context, lineOutlineColor[0], lineOutlineColor[1], lineOutlineColor[2], strokeOpacity);
  28074. } else {
  28075. // do not draw any lineOutline
  28076. context.lineCap = 'butt'; // reset for other drawing functions
  28077. return;
  28078. }
  28079. if (curveStyle === 'straight-triangle') {
  28080. r.drawEdgeTrianglePath(edge, context, rs.allpts);
  28081. } else {
  28082. r.drawEdgePath(edge, context, rs.allpts, lineStyle);
  28083. context.lineCap = 'butt'; // reset for other drawing functions
  28084. }
  28085. };
  28086. var drawOverlay = function drawOverlay() {
  28087. if (!shouldDrawOverlay) {
  28088. return;
  28089. }
  28090. r.drawEdgeOverlay(context, edge);
  28091. };
  28092. var drawUnderlay = function drawUnderlay() {
  28093. if (!shouldDrawOverlay) {
  28094. return;
  28095. }
  28096. r.drawEdgeUnderlay(context, edge);
  28097. };
  28098. var drawArrows = function drawArrows() {
  28099. var arrowOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveArrowOpacity;
  28100. r.drawArrowheads(context, edge, arrowOpacity);
  28101. };
  28102. var drawText = function drawText() {
  28103. r.drawElementText(context, edge, null, drawLabel);
  28104. };
  28105. context.lineJoin = 'round';
  28106. var ghost = edge.pstyle('ghost').value === 'yes';
  28107. if (ghost) {
  28108. var gx = edge.pstyle('ghost-offset-x').pfValue;
  28109. var gy = edge.pstyle('ghost-offset-y').pfValue;
  28110. var ghostOpacity = edge.pstyle('ghost-opacity').value;
  28111. var effectiveGhostOpacity = effectiveLineOpacity * ghostOpacity;
  28112. context.translate(gx, gy);
  28113. drawLine(effectiveGhostOpacity);
  28114. drawArrows(effectiveGhostOpacity);
  28115. context.translate(-gx, -gy);
  28116. } else {
  28117. drawLineOutline();
  28118. }
  28119. drawUnderlay();
  28120. drawLine();
  28121. drawArrows();
  28122. drawOverlay();
  28123. drawText();
  28124. if (shiftToOriginWithBb) {
  28125. context.translate(bb.x1, bb.y1);
  28126. }
  28127. };
  28128. var drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {
  28129. if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
  28130. throw new Error('Invalid state');
  28131. }
  28132. return function (context, edge) {
  28133. if (!edge.visible()) {
  28134. return;
  28135. }
  28136. var opacity = edge.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
  28137. if (opacity === 0) {
  28138. return;
  28139. }
  28140. var r = this;
  28141. var usePaths = r.usePaths();
  28142. var rs = edge._private.rscratch;
  28143. var padding = edge.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
  28144. var width = 2 * padding;
  28145. var color = edge.pstyle("".concat(overlayOrUnderlay, "-color")).value;
  28146. context.lineWidth = width;
  28147. if (rs.edgeType === 'self' && !usePaths) {
  28148. context.lineCap = 'butt';
  28149. } else {
  28150. context.lineCap = 'round';
  28151. }
  28152. r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  28153. r.drawEdgePath(edge, context, rs.allpts, 'solid');
  28154. };
  28155. };
  28156. CRp$9.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');
  28157. CRp$9.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');
  28158. CRp$9.drawEdgePath = function (edge, context, pts, type) {
  28159. var rs = edge._private.rscratch;
  28160. var canvasCxt = context;
  28161. var path;
  28162. var pathCacheHit = false;
  28163. var usePaths = this.usePaths();
  28164. var lineDashPattern = edge.pstyle('line-dash-pattern').pfValue;
  28165. var lineDashOffset = edge.pstyle('line-dash-offset').pfValue;
  28166. if (usePaths) {
  28167. var pathCacheKey = pts.join('$');
  28168. var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;
  28169. if (keyMatches) {
  28170. path = context = rs.pathCache;
  28171. pathCacheHit = true;
  28172. } else {
  28173. path = context = new Path2D();
  28174. rs.pathCacheKey = pathCacheKey;
  28175. rs.pathCache = path;
  28176. }
  28177. }
  28178. if (canvasCxt.setLineDash) {
  28179. // for very outofdate browsers
  28180. switch (type) {
  28181. case 'dotted':
  28182. canvasCxt.setLineDash([1, 1]);
  28183. break;
  28184. case 'dashed':
  28185. canvasCxt.setLineDash(lineDashPattern);
  28186. canvasCxt.lineDashOffset = lineDashOffset;
  28187. break;
  28188. case 'solid':
  28189. canvasCxt.setLineDash([]);
  28190. break;
  28191. }
  28192. }
  28193. if (!pathCacheHit && !rs.badLine) {
  28194. if (context.beginPath) {
  28195. context.beginPath();
  28196. }
  28197. context.moveTo(pts[0], pts[1]);
  28198. switch (rs.edgeType) {
  28199. case 'bezier':
  28200. case 'self':
  28201. case 'compound':
  28202. case 'multibezier':
  28203. for (var i = 2; i + 3 < pts.length; i += 4) {
  28204. context.quadraticCurveTo(pts[i], pts[i + 1], pts[i + 2], pts[i + 3]);
  28205. }
  28206. break;
  28207. case 'straight':
  28208. case 'haystack':
  28209. for (var _i = 2; _i + 1 < pts.length; _i += 2) {
  28210. context.lineTo(pts[_i], pts[_i + 1]);
  28211. }
  28212. break;
  28213. case 'segments':
  28214. if (rs.isRound) {
  28215. var _iterator = _createForOfIteratorHelper(rs.roundCorners),
  28216. _step;
  28217. try {
  28218. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  28219. var corner = _step.value;
  28220. drawPreparedRoundCorner(context, corner);
  28221. }
  28222. } catch (err) {
  28223. _iterator.e(err);
  28224. } finally {
  28225. _iterator.f();
  28226. }
  28227. context.lineTo(pts[pts.length - 2], pts[pts.length - 1]);
  28228. } else {
  28229. for (var _i2 = 2; _i2 + 1 < pts.length; _i2 += 2) {
  28230. context.lineTo(pts[_i2], pts[_i2 + 1]);
  28231. }
  28232. }
  28233. break;
  28234. }
  28235. }
  28236. context = canvasCxt;
  28237. if (usePaths) {
  28238. context.stroke(path);
  28239. } else {
  28240. context.stroke();
  28241. }
  28242. // reset any line dashes
  28243. if (context.setLineDash) {
  28244. // for very outofdate browsers
  28245. context.setLineDash([]);
  28246. }
  28247. };
  28248. CRp$9.drawEdgeTrianglePath = function (edge, context, pts) {
  28249. // use line stroke style for triangle fill style
  28250. context.fillStyle = context.strokeStyle;
  28251. var edgeWidth = edge.pstyle('width').pfValue;
  28252. for (var i = 0; i + 1 < pts.length; i += 2) {
  28253. var vector = [pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]];
  28254. var length = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);
  28255. var normal = [vector[1] / length, -vector[0] / length];
  28256. var triangleHead = [normal[0] * edgeWidth / 2, normal[1] * edgeWidth / 2];
  28257. context.beginPath();
  28258. context.moveTo(pts[i] - triangleHead[0], pts[i + 1] - triangleHead[1]);
  28259. context.lineTo(pts[i] + triangleHead[0], pts[i + 1] + triangleHead[1]);
  28260. context.lineTo(pts[i + 2], pts[i + 3]);
  28261. context.closePath();
  28262. context.fill();
  28263. }
  28264. };
  28265. CRp$9.drawArrowheads = function (context, edge, opacity) {
  28266. var rs = edge._private.rscratch;
  28267. var isHaystack = rs.edgeType === 'haystack';
  28268. if (!isHaystack) {
  28269. this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);
  28270. }
  28271. this.drawArrowhead(context, edge, 'mid-target', rs.midX, rs.midY, rs.midtgtArrowAngle, opacity);
  28272. this.drawArrowhead(context, edge, 'mid-source', rs.midX, rs.midY, rs.midsrcArrowAngle, opacity);
  28273. if (!isHaystack) {
  28274. this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);
  28275. }
  28276. };
  28277. CRp$9.drawArrowhead = function (context, edge, prefix, x, y, angle, opacity) {
  28278. if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
  28279. return;
  28280. }
  28281. var self = this;
  28282. var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  28283. if (arrowShape === 'none') {
  28284. return;
  28285. }
  28286. var arrowClearFill = edge.pstyle(prefix + '-arrow-fill').value === 'hollow' ? 'both' : 'filled';
  28287. var arrowFill = edge.pstyle(prefix + '-arrow-fill').value;
  28288. var edgeWidth = edge.pstyle('width').pfValue;
  28289. var pArrowWidth = edge.pstyle(prefix + '-arrow-width');
  28290. var arrowWidth = pArrowWidth.value === 'match-line' ? edgeWidth : pArrowWidth.pfValue;
  28291. if (pArrowWidth.units === '%') arrowWidth *= edgeWidth;
  28292. var edgeOpacity = edge.pstyle('opacity').value;
  28293. if (opacity === undefined) {
  28294. opacity = edgeOpacity;
  28295. }
  28296. var gco = context.globalCompositeOperation;
  28297. if (opacity !== 1 || arrowFill === 'hollow') {
  28298. // then extra clear is needed
  28299. context.globalCompositeOperation = 'destination-out';
  28300. self.colorFillStyle(context, 255, 255, 255, 1);
  28301. self.colorStrokeStyle(context, 255, 255, 255, 1);
  28302. self.drawArrowShape(edge, context, arrowClearFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
  28303. context.globalCompositeOperation = gco;
  28304. } // otherwise, the opaque arrow clears it for free :)
  28305. var color = edge.pstyle(prefix + '-arrow-color').value;
  28306. self.colorFillStyle(context, color[0], color[1], color[2], opacity);
  28307. self.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  28308. self.drawArrowShape(edge, context, arrowFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
  28309. };
  28310. CRp$9.drawArrowShape = function (edge, context, fill, edgeWidth, shape, shapeWidth, x, y, angle) {
  28311. var r = this;
  28312. var usePaths = this.usePaths() && shape !== 'triangle-cross';
  28313. var pathCacheHit = false;
  28314. var path;
  28315. var canvasContext = context;
  28316. var translation = {
  28317. x: x,
  28318. y: y
  28319. };
  28320. var scale = edge.pstyle('arrow-scale').value;
  28321. var size = this.getArrowWidth(edgeWidth, scale);
  28322. var shapeImpl = r.arrowShapes[shape];
  28323. if (usePaths) {
  28324. var cache = r.arrowPathCache = r.arrowPathCache || [];
  28325. var key = hashString(shape);
  28326. var cachedPath = cache[key];
  28327. if (cachedPath != null) {
  28328. path = context = cachedPath;
  28329. pathCacheHit = true;
  28330. } else {
  28331. path = context = new Path2D();
  28332. cache[key] = path;
  28333. }
  28334. }
  28335. if (!pathCacheHit) {
  28336. if (context.beginPath) {
  28337. context.beginPath();
  28338. }
  28339. if (usePaths) {
  28340. // store in the path cache with values easily manipulated later
  28341. shapeImpl.draw(context, 1, 0, {
  28342. x: 0,
  28343. y: 0
  28344. }, 1);
  28345. } else {
  28346. shapeImpl.draw(context, size, angle, translation, edgeWidth);
  28347. }
  28348. if (context.closePath) {
  28349. context.closePath();
  28350. }
  28351. }
  28352. context = canvasContext;
  28353. if (usePaths) {
  28354. // set transform to arrow position/orientation
  28355. context.translate(x, y);
  28356. context.rotate(angle);
  28357. context.scale(size, size);
  28358. }
  28359. if (fill === 'filled' || fill === 'both') {
  28360. if (usePaths) {
  28361. context.fill(path);
  28362. } else {
  28363. context.fill();
  28364. }
  28365. }
  28366. if (fill === 'hollow' || fill === 'both') {
  28367. context.lineWidth = shapeWidth / (usePaths ? size : 1);
  28368. context.lineJoin = 'miter';
  28369. if (usePaths) {
  28370. context.stroke(path);
  28371. } else {
  28372. context.stroke();
  28373. }
  28374. }
  28375. if (usePaths) {
  28376. // reset transform by applying inverse
  28377. context.scale(1 / size, 1 / size);
  28378. context.rotate(-angle);
  28379. context.translate(-x, -y);
  28380. }
  28381. };
  28382. var CRp$8 = {};
  28383. CRp$8.safeDrawImage = function (context, img, ix, iy, iw, ih, x, y, w, h) {
  28384. // detect problematic cases for old browsers with bad images (cheaper than try-catch)
  28385. if (iw <= 0 || ih <= 0 || w <= 0 || h <= 0) {
  28386. return;
  28387. }
  28388. try {
  28389. context.drawImage(img, ix, iy, iw, ih, x, y, w, h);
  28390. } catch (e) {
  28391. warn(e);
  28392. }
  28393. };
  28394. CRp$8.drawInscribedImage = function (context, img, node, index, nodeOpacity) {
  28395. var r = this;
  28396. var pos = node.position();
  28397. var nodeX = pos.x;
  28398. var nodeY = pos.y;
  28399. var styleObj = node.cy().style();
  28400. var getIndexedStyle = styleObj.getIndexedStyle.bind(styleObj);
  28401. var fit = getIndexedStyle(node, 'background-fit', 'value', index);
  28402. var repeat = getIndexedStyle(node, 'background-repeat', 'value', index);
  28403. var nodeW = node.width();
  28404. var nodeH = node.height();
  28405. var paddingX2 = node.padding() * 2;
  28406. var nodeTW = nodeW + (getIndexedStyle(node, 'background-width-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  28407. var nodeTH = nodeH + (getIndexedStyle(node, 'background-height-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  28408. var rs = node._private.rscratch;
  28409. var clip = getIndexedStyle(node, 'background-clip', 'value', index);
  28410. var shouldClip = clip === 'node';
  28411. var imgOpacity = getIndexedStyle(node, 'background-image-opacity', 'value', index) * nodeOpacity;
  28412. var smooth = getIndexedStyle(node, 'background-image-smoothing', 'value', index);
  28413. var cornerRadius = node.pstyle('corner-radius').value;
  28414. if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  28415. var imgW = img.width || img.cachedW;
  28416. var imgH = img.height || img.cachedH;
  28417. // workaround for broken browsers like ie
  28418. if (null == imgW || null == imgH) {
  28419. document.body.appendChild(img); // eslint-disable-line no-undef
  28420. imgW = img.cachedW = img.width || img.offsetWidth;
  28421. imgH = img.cachedH = img.height || img.offsetHeight;
  28422. document.body.removeChild(img); // eslint-disable-line no-undef
  28423. }
  28424. var w = imgW;
  28425. var h = imgH;
  28426. if (getIndexedStyle(node, 'background-width', 'value', index) !== 'auto') {
  28427. if (getIndexedStyle(node, 'background-width', 'units', index) === '%') {
  28428. w = getIndexedStyle(node, 'background-width', 'pfValue', index) * nodeTW;
  28429. } else {
  28430. w = getIndexedStyle(node, 'background-width', 'pfValue', index);
  28431. }
  28432. }
  28433. if (getIndexedStyle(node, 'background-height', 'value', index) !== 'auto') {
  28434. if (getIndexedStyle(node, 'background-height', 'units', index) === '%') {
  28435. h = getIndexedStyle(node, 'background-height', 'pfValue', index) * nodeTH;
  28436. } else {
  28437. h = getIndexedStyle(node, 'background-height', 'pfValue', index);
  28438. }
  28439. }
  28440. if (w === 0 || h === 0) {
  28441. return; // no point in drawing empty image (and chrome is broken in this case)
  28442. }
  28443. if (fit === 'contain') {
  28444. var scale = Math.min(nodeTW / w, nodeTH / h);
  28445. w *= scale;
  28446. h *= scale;
  28447. } else if (fit === 'cover') {
  28448. var scale = Math.max(nodeTW / w, nodeTH / h);
  28449. w *= scale;
  28450. h *= scale;
  28451. }
  28452. var x = nodeX - nodeTW / 2; // left
  28453. var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);
  28454. var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);
  28455. if (posXUnits === '%') {
  28456. x += (nodeTW - w) * posXPfVal;
  28457. } else {
  28458. x += posXPfVal;
  28459. }
  28460. var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);
  28461. var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);
  28462. if (offXUnits === '%') {
  28463. x += (nodeTW - w) * offXPfVal;
  28464. } else {
  28465. x += offXPfVal;
  28466. }
  28467. var y = nodeY - nodeTH / 2; // top
  28468. var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);
  28469. var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);
  28470. if (posYUnits === '%') {
  28471. y += (nodeTH - h) * posYPfVal;
  28472. } else {
  28473. y += posYPfVal;
  28474. }
  28475. var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);
  28476. var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);
  28477. if (offYUnits === '%') {
  28478. y += (nodeTH - h) * offYPfVal;
  28479. } else {
  28480. y += offYPfVal;
  28481. }
  28482. if (rs.pathCache) {
  28483. x -= nodeX;
  28484. y -= nodeY;
  28485. nodeX = 0;
  28486. nodeY = 0;
  28487. }
  28488. var gAlpha = context.globalAlpha;
  28489. context.globalAlpha = imgOpacity;
  28490. var smoothingEnabled = r.getImgSmoothing(context);
  28491. var isSmoothingSwitched = false;
  28492. if (smooth === 'no' && smoothingEnabled) {
  28493. r.setImgSmoothing(context, false);
  28494. isSmoothingSwitched = true;
  28495. } else if (smooth === 'yes' && !smoothingEnabled) {
  28496. r.setImgSmoothing(context, true);
  28497. isSmoothingSwitched = true;
  28498. }
  28499. if (repeat === 'no-repeat') {
  28500. if (shouldClip) {
  28501. context.save();
  28502. if (rs.pathCache) {
  28503. context.clip(rs.pathCache);
  28504. } else {
  28505. r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
  28506. context.clip();
  28507. }
  28508. }
  28509. r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);
  28510. if (shouldClip) {
  28511. context.restore();
  28512. }
  28513. } else {
  28514. var pattern = context.createPattern(img, repeat);
  28515. context.fillStyle = pattern;
  28516. r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
  28517. context.translate(x, y);
  28518. context.fill();
  28519. context.translate(-x, -y);
  28520. }
  28521. context.globalAlpha = gAlpha;
  28522. if (isSmoothingSwitched) {
  28523. r.setImgSmoothing(context, smoothingEnabled);
  28524. }
  28525. };
  28526. var CRp$7 = {};
  28527. CRp$7.eleTextBiggerThanMin = function (ele, scale) {
  28528. if (!scale) {
  28529. var zoom = ele.cy().zoom();
  28530. var pxRatio = this.getPixelRatio();
  28531. var lvl = Math.ceil(log2(zoom * pxRatio)); // the effective texture level
  28532. scale = Math.pow(2, lvl);
  28533. }
  28534. var computedSize = ele.pstyle('font-size').pfValue * scale;
  28535. var minSize = ele.pstyle('min-zoomed-font-size').pfValue;
  28536. if (computedSize < minSize) {
  28537. return false;
  28538. }
  28539. return true;
  28540. };
  28541. CRp$7.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {
  28542. var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28543. var r = this;
  28544. if (force == null) {
  28545. if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {
  28546. return;
  28547. }
  28548. } else if (force === false) {
  28549. return;
  28550. }
  28551. if (ele.isNode()) {
  28552. var label = ele.pstyle('label');
  28553. if (!label || !label.value) {
  28554. return;
  28555. }
  28556. var justification = r.getLabelJustification(ele);
  28557. context.textAlign = justification;
  28558. context.textBaseline = 'bottom';
  28559. } else {
  28560. var badLine = ele.element()._private.rscratch.badLine;
  28561. var _label = ele.pstyle('label');
  28562. var srcLabel = ele.pstyle('source-label');
  28563. var tgtLabel = ele.pstyle('target-label');
  28564. if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {
  28565. return;
  28566. }
  28567. context.textAlign = 'center';
  28568. context.textBaseline = 'bottom';
  28569. }
  28570. var applyRotation = !shiftToOriginWithBb;
  28571. var bb;
  28572. if (shiftToOriginWithBb) {
  28573. bb = shiftToOriginWithBb;
  28574. context.translate(-bb.x1, -bb.y1);
  28575. }
  28576. if (prefix == null) {
  28577. r.drawText(context, ele, null, applyRotation, useEleOpacity);
  28578. if (ele.isEdge()) {
  28579. r.drawText(context, ele, 'source', applyRotation, useEleOpacity);
  28580. r.drawText(context, ele, 'target', applyRotation, useEleOpacity);
  28581. }
  28582. } else {
  28583. r.drawText(context, ele, prefix, applyRotation, useEleOpacity);
  28584. }
  28585. if (shiftToOriginWithBb) {
  28586. context.translate(bb.x1, bb.y1);
  28587. }
  28588. };
  28589. CRp$7.getFontCache = function (context) {
  28590. var cache;
  28591. this.fontCaches = this.fontCaches || [];
  28592. for (var i = 0; i < this.fontCaches.length; i++) {
  28593. cache = this.fontCaches[i];
  28594. if (cache.context === context) {
  28595. return cache;
  28596. }
  28597. }
  28598. cache = {
  28599. context: context
  28600. };
  28601. this.fontCaches.push(cache);
  28602. return cache;
  28603. };
  28604. // set up canvas context with font
  28605. // returns transformed text string
  28606. CRp$7.setupTextStyle = function (context, ele) {
  28607. var useEleOpacity = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  28608. // Font style
  28609. var labelStyle = ele.pstyle('font-style').strValue;
  28610. var labelSize = ele.pstyle('font-size').pfValue + 'px';
  28611. var labelFamily = ele.pstyle('font-family').strValue;
  28612. var labelWeight = ele.pstyle('font-weight').strValue;
  28613. var opacity = useEleOpacity ? ele.effectiveOpacity() * ele.pstyle('text-opacity').value : 1;
  28614. var outlineOpacity = ele.pstyle('text-outline-opacity').value * opacity;
  28615. var color = ele.pstyle('color').value;
  28616. var outlineColor = ele.pstyle('text-outline-color').value;
  28617. context.font = labelStyle + ' ' + labelWeight + ' ' + labelSize + ' ' + labelFamily;
  28618. context.lineJoin = 'round'; // so text outlines aren't jagged
  28619. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  28620. this.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], outlineOpacity);
  28621. };
  28622. function circle(ctx, x, y, width, height) {
  28623. var diameter = Math.min(width, height);
  28624. var radius = diameter / 2;
  28625. var centerX = x + width / 2;
  28626. var centerY = y + height / 2;
  28627. ctx.beginPath();
  28628. ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  28629. ctx.closePath();
  28630. }
  28631. function roundRect(ctx, x, y, width, height) {
  28632. var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;
  28633. var r = Math.min(radius, width / 2, height / 2); // prevent overflow
  28634. ctx.beginPath();
  28635. ctx.moveTo(x + r, y);
  28636. ctx.lineTo(x + width - r, y);
  28637. ctx.quadraticCurveTo(x + width, y, x + width, y + r);
  28638. ctx.lineTo(x + width, y + height - r);
  28639. ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
  28640. ctx.lineTo(x + r, y + height);
  28641. ctx.quadraticCurveTo(x, y + height, x, y + height - r);
  28642. ctx.lineTo(x, y + r);
  28643. ctx.quadraticCurveTo(x, y, x + r, y);
  28644. ctx.closePath();
  28645. }
  28646. CRp$7.getTextAngle = function (ele, prefix) {
  28647. var theta;
  28648. var _p = ele._private;
  28649. var rscratch = _p.rscratch;
  28650. var pdash = prefix ? prefix + '-' : '';
  28651. var rotation = ele.pstyle(pdash + 'text-rotation');
  28652. if (rotation.strValue === 'autorotate') {
  28653. var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);
  28654. theta = ele.isEdge() ? textAngle : 0;
  28655. } else if (rotation.strValue === 'none') {
  28656. theta = 0;
  28657. } else {
  28658. theta = rotation.pfValue;
  28659. }
  28660. return theta;
  28661. };
  28662. CRp$7.drawText = function (context, ele, prefix) {
  28663. var applyRotation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28664. var useEleOpacity = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28665. var _p = ele._private;
  28666. var rscratch = _p.rscratch;
  28667. var parentOpacity = useEleOpacity ? ele.effectiveOpacity() : 1;
  28668. if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {
  28669. return;
  28670. }
  28671. // use 'main' as an alias for the main label (i.e. null prefix)
  28672. if (prefix === 'main') {
  28673. prefix = null;
  28674. }
  28675. var textX = getPrefixedProperty(rscratch, 'labelX', prefix);
  28676. var textY = getPrefixedProperty(rscratch, 'labelY', prefix);
  28677. var orgTextX, orgTextY; // used for rotation
  28678. var text = this.getLabelText(ele, prefix);
  28679. if (text != null && text !== '' && !isNaN(textX) && !isNaN(textY)) {
  28680. this.setupTextStyle(context, ele, useEleOpacity);
  28681. var pdash = prefix ? prefix + '-' : '';
  28682. var textW = getPrefixedProperty(rscratch, 'labelWidth', prefix);
  28683. var textH = getPrefixedProperty(rscratch, 'labelHeight', prefix);
  28684. var marginX = ele.pstyle(pdash + 'text-margin-x').pfValue;
  28685. var marginY = ele.pstyle(pdash + 'text-margin-y').pfValue;
  28686. var isEdge = ele.isEdge();
  28687. var halign = ele.pstyle('text-halign').value;
  28688. var valign = ele.pstyle('text-valign').value;
  28689. if (isEdge) {
  28690. halign = 'center';
  28691. valign = 'center';
  28692. }
  28693. textX += marginX;
  28694. textY += marginY;
  28695. var theta;
  28696. if (!applyRotation) {
  28697. theta = 0;
  28698. } else {
  28699. theta = this.getTextAngle(ele, prefix);
  28700. }
  28701. if (theta !== 0) {
  28702. orgTextX = textX;
  28703. orgTextY = textY;
  28704. context.translate(orgTextX, orgTextY);
  28705. context.rotate(theta);
  28706. textX = 0;
  28707. textY = 0;
  28708. }
  28709. switch (valign) {
  28710. case 'top':
  28711. break;
  28712. case 'center':
  28713. textY += textH / 2;
  28714. break;
  28715. case 'bottom':
  28716. textY += textH;
  28717. break;
  28718. }
  28719. var backgroundOpacity = ele.pstyle('text-background-opacity').value;
  28720. var borderOpacity = ele.pstyle('text-border-opacity').value;
  28721. var textBorderWidth = ele.pstyle('text-border-width').pfValue;
  28722. var backgroundPadding = ele.pstyle('text-background-padding').pfValue;
  28723. var styleShape = ele.pstyle('text-background-shape').strValue;
  28724. var rounded = styleShape === 'round-rectangle' || styleShape === 'roundrectangle';
  28725. var circled = styleShape === 'circle';
  28726. var roundRadius = 2;
  28727. if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {
  28728. var textFill = context.fillStyle;
  28729. var textStroke = context.strokeStyle;
  28730. var textLineWidth = context.lineWidth;
  28731. var textBackgroundColor = ele.pstyle('text-background-color').value;
  28732. var textBorderColor = ele.pstyle('text-border-color').value;
  28733. var textBorderStyle = ele.pstyle('text-border-style').value;
  28734. var doFill = backgroundOpacity > 0;
  28735. var doStroke = textBorderWidth > 0 && borderOpacity > 0;
  28736. var bgX = textX - backgroundPadding;
  28737. switch (halign) {
  28738. case 'left':
  28739. bgX -= textW;
  28740. break;
  28741. case 'center':
  28742. bgX -= textW / 2;
  28743. break;
  28744. }
  28745. var bgY = textY - textH - backgroundPadding;
  28746. var bgW = textW + 2 * backgroundPadding;
  28747. var bgH = textH + 2 * backgroundPadding;
  28748. if (doFill) {
  28749. context.fillStyle = "rgba(".concat(textBackgroundColor[0], ",").concat(textBackgroundColor[1], ",").concat(textBackgroundColor[2], ",").concat(backgroundOpacity * parentOpacity, ")");
  28750. }
  28751. if (doStroke) {
  28752. context.strokeStyle = "rgba(".concat(textBorderColor[0], ",").concat(textBorderColor[1], ",").concat(textBorderColor[2], ",").concat(borderOpacity * parentOpacity, ")");
  28753. context.lineWidth = textBorderWidth;
  28754. if (context.setLineDash) {
  28755. switch (textBorderStyle) {
  28756. case 'dotted':
  28757. context.setLineDash([1, 1]);
  28758. break;
  28759. case 'dashed':
  28760. context.setLineDash([4, 2]);
  28761. break;
  28762. case 'double':
  28763. context.lineWidth = textBorderWidth / 4;
  28764. context.setLineDash([]);
  28765. break;
  28766. case 'solid':
  28767. default:
  28768. context.setLineDash([]);
  28769. break;
  28770. }
  28771. }
  28772. }
  28773. if (rounded) {
  28774. context.beginPath();
  28775. roundRect(context, bgX, bgY, bgW, bgH, roundRadius);
  28776. } else if (circled) {
  28777. context.beginPath();
  28778. circle(context, bgX, bgY, bgW, bgH);
  28779. } else {
  28780. context.beginPath();
  28781. context.rect(bgX, bgY, bgW, bgH);
  28782. }
  28783. if (doFill) context.fill();
  28784. if (doStroke) context.stroke();
  28785. // Double border pass for 'double' style
  28786. if (doStroke && textBorderStyle === 'double') {
  28787. var whiteWidth = textBorderWidth / 2;
  28788. context.beginPath();
  28789. if (rounded) {
  28790. roundRect(context, bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth, roundRadius);
  28791. } else {
  28792. context.rect(bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth);
  28793. }
  28794. context.stroke();
  28795. }
  28796. context.fillStyle = textFill;
  28797. context.strokeStyle = textStroke;
  28798. context.lineWidth = textLineWidth;
  28799. if (context.setLineDash) context.setLineDash([]);
  28800. }
  28801. var lineWidth = 2 * ele.pstyle('text-outline-width').pfValue; // *2 b/c the stroke is drawn centred on the middle
  28802. if (lineWidth > 0) {
  28803. context.lineWidth = lineWidth;
  28804. }
  28805. if (ele.pstyle('text-wrap').value === 'wrap') {
  28806. var lines = getPrefixedProperty(rscratch, 'labelWrapCachedLines', prefix);
  28807. var lineHeight = getPrefixedProperty(rscratch, 'labelLineHeight', prefix);
  28808. var halfTextW = textW / 2;
  28809. var justification = this.getLabelJustification(ele);
  28810. if (justification === 'auto') ; else if (halign === 'left') {
  28811. // auto justification : right
  28812. if (justification === 'left') {
  28813. textX += -textW;
  28814. } else if (justification === 'center') {
  28815. textX += -halfTextW;
  28816. } // else same as auto
  28817. } else if (halign === 'center') {
  28818. // auto justfication : center
  28819. if (justification === 'left') {
  28820. textX += -halfTextW;
  28821. } else if (justification === 'right') {
  28822. textX += halfTextW;
  28823. } // else same as auto
  28824. } else if (halign === 'right') {
  28825. // auto justification : left
  28826. if (justification === 'center') {
  28827. textX += halfTextW;
  28828. } else if (justification === 'right') {
  28829. textX += textW;
  28830. } // else same as auto
  28831. }
  28832. switch (valign) {
  28833. case 'top':
  28834. textY -= (lines.length - 1) * lineHeight;
  28835. break;
  28836. case 'center':
  28837. case 'bottom':
  28838. textY -= (lines.length - 1) * lineHeight;
  28839. break;
  28840. }
  28841. for (var l = 0; l < lines.length; l++) {
  28842. if (lineWidth > 0) {
  28843. context.strokeText(lines[l], textX, textY);
  28844. }
  28845. context.fillText(lines[l], textX, textY);
  28846. textY += lineHeight;
  28847. }
  28848. } else {
  28849. if (lineWidth > 0) {
  28850. context.strokeText(text, textX, textY);
  28851. }
  28852. context.fillText(text, textX, textY);
  28853. }
  28854. if (theta !== 0) {
  28855. context.rotate(-theta);
  28856. context.translate(-orgTextX, -orgTextY);
  28857. }
  28858. }
  28859. };
  28860. /* global Path2D */
  28861. var CRp$6 = {};
  28862. CRp$6.drawNode = function (context, node, shiftToOriginWithBb) {
  28863. var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28864. var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28865. var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28866. var r = this;
  28867. var nodeWidth, nodeHeight;
  28868. var _p = node._private;
  28869. var rs = _p.rscratch;
  28870. var pos = node.position();
  28871. if (!number$1(pos.x) || !number$1(pos.y)) {
  28872. return; // can't draw node with undefined position
  28873. }
  28874. if (shouldDrawOpacity && !node.visible()) {
  28875. return;
  28876. }
  28877. var eleOpacity = shouldDrawOpacity ? node.effectiveOpacity() : 1;
  28878. var usePaths = r.usePaths();
  28879. var path;
  28880. var pathCacheHit = false;
  28881. var padding = node.padding();
  28882. nodeWidth = node.width() + 2 * padding;
  28883. nodeHeight = node.height() + 2 * padding;
  28884. //
  28885. // setup shift
  28886. var bb;
  28887. if (shiftToOriginWithBb) {
  28888. bb = shiftToOriginWithBb;
  28889. context.translate(-bb.x1, -bb.y1);
  28890. }
  28891. //
  28892. // load bg image
  28893. var bgImgProp = node.pstyle('background-image');
  28894. var urls = bgImgProp.value;
  28895. var urlDefined = new Array(urls.length);
  28896. var image = new Array(urls.length);
  28897. var numImages = 0;
  28898. for (var i = 0; i < urls.length; i++) {
  28899. var url = urls[i];
  28900. var defd = urlDefined[i] = url != null && url !== 'none';
  28901. if (defd) {
  28902. var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);
  28903. numImages++;
  28904. // get image, and if not loaded then ask to redraw when later loaded
  28905. image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {
  28906. _p.backgroundTimestamp = Date.now();
  28907. node.emitAndNotify('background');
  28908. });
  28909. }
  28910. }
  28911. //
  28912. // setup styles
  28913. var darkness = node.pstyle('background-blacken').value;
  28914. var borderWidth = node.pstyle('border-width').pfValue;
  28915. var bgOpacity = node.pstyle('background-opacity').value * eleOpacity;
  28916. var borderColor = node.pstyle('border-color').value;
  28917. var borderStyle = node.pstyle('border-style').value;
  28918. var borderJoin = node.pstyle('border-join').value;
  28919. var borderCap = node.pstyle('border-cap').value;
  28920. var borderPosition = node.pstyle('border-position').value;
  28921. var borderPattern = node.pstyle('border-dash-pattern').pfValue;
  28922. var borderOffset = node.pstyle('border-dash-offset').pfValue;
  28923. var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;
  28924. var outlineWidth = node.pstyle('outline-width').pfValue;
  28925. var outlineColor = node.pstyle('outline-color').value;
  28926. var outlineStyle = node.pstyle('outline-style').value;
  28927. var outlineOpacity = node.pstyle('outline-opacity').value * eleOpacity;
  28928. var outlineOffset = node.pstyle('outline-offset').value;
  28929. var cornerRadius = node.pstyle('corner-radius').value;
  28930. if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  28931. var setupShapeColor = function setupShapeColor() {
  28932. var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
  28933. r.eleFillStyle(context, node, bgOpy);
  28934. };
  28935. var setupBorderColor = function setupBorderColor() {
  28936. var bdrOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : borderOpacity;
  28937. r.colorStrokeStyle(context, borderColor[0], borderColor[1], borderColor[2], bdrOpy);
  28938. };
  28939. var setupOutlineColor = function setupOutlineColor() {
  28940. var otlnOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : outlineOpacity;
  28941. r.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], otlnOpy);
  28942. };
  28943. //
  28944. // setup shape
  28945. var getPath = function getPath(width, height, shape, points) {
  28946. var pathCache = r.nodePathCache = r.nodePathCache || [];
  28947. var key = hashStrings(shape === 'polygon' ? shape + ',' + points.join(',') : shape, '' + height, '' + width, '' + cornerRadius);
  28948. var cachedPath = pathCache[key];
  28949. var path;
  28950. var cacheHit = false;
  28951. if (cachedPath != null) {
  28952. path = cachedPath;
  28953. cacheHit = true;
  28954. rs.pathCache = path;
  28955. } else {
  28956. path = new Path2D();
  28957. pathCache[key] = rs.pathCache = path;
  28958. }
  28959. return {
  28960. path: path,
  28961. cacheHit: cacheHit
  28962. };
  28963. };
  28964. var styleShape = node.pstyle('shape').strValue;
  28965. var shapePts = node.pstyle('shape-polygon-points').pfValue;
  28966. if (usePaths) {
  28967. context.translate(pos.x, pos.y);
  28968. var shapePath = getPath(nodeWidth, nodeHeight, styleShape, shapePts);
  28969. path = shapePath.path;
  28970. pathCacheHit = shapePath.cacheHit;
  28971. }
  28972. var drawShape = function drawShape() {
  28973. if (!pathCacheHit) {
  28974. var npos = pos;
  28975. if (usePaths) {
  28976. npos = {
  28977. x: 0,
  28978. y: 0
  28979. };
  28980. }
  28981. r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  28982. }
  28983. if (usePaths) {
  28984. context.fill(path);
  28985. } else {
  28986. context.fill();
  28987. }
  28988. };
  28989. var drawImages = function drawImages() {
  28990. var nodeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
  28991. var inside = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  28992. var prevBging = _p.backgrounding;
  28993. var totalCompleted = 0;
  28994. for (var _i = 0; _i < image.length; _i++) {
  28995. var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);
  28996. if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {
  28997. totalCompleted++;
  28998. continue;
  28999. }
  29000. if (urlDefined[_i] && image[_i].complete && !image[_i].error) {
  29001. totalCompleted++;
  29002. r.drawInscribedImage(context, image[_i], node, _i, nodeOpacity);
  29003. }
  29004. }
  29005. _p.backgrounding = !(totalCompleted === numImages);
  29006. if (prevBging !== _p.backgrounding) {
  29007. // update style b/c :backgrounding state changed
  29008. node.updateStyle(false);
  29009. }
  29010. };
  29011. var drawPie = function drawPie() {
  29012. var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  29013. var pieOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
  29014. if (r.hasPie(node)) {
  29015. r.drawPie(context, node, pieOpacity);
  29016. // redraw/restore path if steps after pie need it
  29017. if (redrawShape) {
  29018. if (!usePaths) {
  29019. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29020. }
  29021. }
  29022. }
  29023. };
  29024. var drawStripe = function drawStripe() {
  29025. var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  29026. var stripeOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
  29027. if (r.hasStripe(node)) {
  29028. context.save();
  29029. if (usePaths) {
  29030. context.clip(rs.pathCache);
  29031. } else {
  29032. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29033. context.clip();
  29034. }
  29035. r.drawStripe(context, node, stripeOpacity);
  29036. context.restore();
  29037. // redraw/restore path if steps after stripes need it
  29038. if (redrawShape) {
  29039. if (!usePaths) {
  29040. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29041. }
  29042. }
  29043. }
  29044. };
  29045. var darken = function darken() {
  29046. var darkenOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
  29047. var opacity = (darkness > 0 ? darkness : -darkness) * darkenOpacity;
  29048. var c = darkness > 0 ? 0 : 255;
  29049. if (darkness !== 0) {
  29050. r.colorFillStyle(context, c, c, c, opacity);
  29051. if (usePaths) {
  29052. context.fill(path);
  29053. } else {
  29054. context.fill();
  29055. }
  29056. }
  29057. };
  29058. var drawBorder = function drawBorder() {
  29059. if (borderWidth > 0) {
  29060. context.lineWidth = borderWidth;
  29061. context.lineCap = borderCap;
  29062. context.lineJoin = borderJoin;
  29063. if (context.setLineDash) {
  29064. // for very outofdate browsers
  29065. switch (borderStyle) {
  29066. case 'dotted':
  29067. context.setLineDash([1, 1]);
  29068. break;
  29069. case 'dashed':
  29070. context.setLineDash(borderPattern);
  29071. context.lineDashOffset = borderOffset;
  29072. break;
  29073. case 'solid':
  29074. case 'double':
  29075. context.setLineDash([]);
  29076. break;
  29077. }
  29078. }
  29079. if (borderPosition !== 'center') {
  29080. context.save();
  29081. context.lineWidth *= 2;
  29082. if (borderPosition === 'inside') {
  29083. usePaths ? context.clip(path) : context.clip();
  29084. } else {
  29085. var region = new Path2D();
  29086. region.rect(-nodeWidth / 2 - borderWidth, -nodeHeight / 2 - borderWidth, nodeWidth + 2 * borderWidth, nodeHeight + 2 * borderWidth);
  29087. region.addPath(path);
  29088. context.clip(region, 'evenodd');
  29089. }
  29090. usePaths ? context.stroke(path) : context.stroke();
  29091. context.restore();
  29092. } else {
  29093. usePaths ? context.stroke(path) : context.stroke();
  29094. }
  29095. if (borderStyle === 'double') {
  29096. context.lineWidth = borderWidth / 3;
  29097. var gco = context.globalCompositeOperation;
  29098. context.globalCompositeOperation = 'destination-out';
  29099. if (usePaths) {
  29100. context.stroke(path);
  29101. } else {
  29102. context.stroke();
  29103. }
  29104. context.globalCompositeOperation = gco;
  29105. }
  29106. // reset in case we changed the border style
  29107. if (context.setLineDash) {
  29108. // for very outofdate browsers
  29109. context.setLineDash([]);
  29110. }
  29111. }
  29112. };
  29113. var drawOutline = function drawOutline() {
  29114. if (outlineWidth > 0) {
  29115. context.lineWidth = outlineWidth;
  29116. context.lineCap = 'butt';
  29117. if (context.setLineDash) {
  29118. // for very outofdate browsers
  29119. switch (outlineStyle) {
  29120. case 'dotted':
  29121. context.setLineDash([1, 1]);
  29122. break;
  29123. case 'dashed':
  29124. context.setLineDash([4, 2]);
  29125. break;
  29126. case 'solid':
  29127. case 'double':
  29128. context.setLineDash([]);
  29129. break;
  29130. }
  29131. }
  29132. var npos = pos;
  29133. if (usePaths) {
  29134. npos = {
  29135. x: 0,
  29136. y: 0
  29137. };
  29138. }
  29139. var shape = r.getNodeShape(node);
  29140. var bWidth = borderWidth;
  29141. if (borderPosition === 'inside') bWidth = 0;
  29142. if (borderPosition === 'outside') bWidth *= 2;
  29143. var scaleX = (nodeWidth + bWidth + (outlineWidth + outlineOffset)) / nodeWidth;
  29144. var scaleY = (nodeHeight + bWidth + (outlineWidth + outlineOffset)) / nodeHeight;
  29145. var sWidth = nodeWidth * scaleX;
  29146. var sHeight = nodeHeight * scaleY;
  29147. var points = r.nodeShapes[shape].points;
  29148. var _path;
  29149. if (usePaths) {
  29150. var outlinePath = getPath(sWidth, sHeight, shape, points);
  29151. _path = outlinePath.path;
  29152. }
  29153. // draw the outline path, either by using expanded points or by scaling
  29154. // the dimensions, depending on shape
  29155. if (shape === "ellipse") {
  29156. r.drawEllipsePath(_path || context, npos.x, npos.y, sWidth, sHeight);
  29157. } else if (['round-diamond', 'round-heptagon', 'round-hexagon', 'round-octagon', 'round-pentagon', 'round-polygon', 'round-triangle', 'round-tag'].includes(shape)) {
  29158. var sMult = 0;
  29159. var offsetX = 0;
  29160. var offsetY = 0;
  29161. if (shape === 'round-diamond') {
  29162. sMult = (bWidth + outlineOffset + outlineWidth) * 1.4;
  29163. } else if (shape === 'round-heptagon') {
  29164. sMult = (bWidth + outlineOffset + outlineWidth) * 1.075;
  29165. offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 35;
  29166. } else if (shape === 'round-hexagon') {
  29167. sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
  29168. } else if (shape === 'round-pentagon') {
  29169. sMult = (bWidth + outlineOffset + outlineWidth) * 1.13;
  29170. offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 15;
  29171. } else if (shape === 'round-tag') {
  29172. sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
  29173. offsetX = (bWidth / 2 + outlineWidth + outlineOffset) * .07;
  29174. } else if (shape === 'round-triangle') {
  29175. sMult = (bWidth + outlineOffset + outlineWidth) * (Math.PI / 2);
  29176. offsetY = -(bWidth + outlineOffset / 2 + outlineWidth) / Math.PI;
  29177. }
  29178. if (sMult !== 0) {
  29179. scaleX = (nodeWidth + sMult) / nodeWidth;
  29180. sWidth = nodeWidth * scaleX;
  29181. if (!['round-hexagon', 'round-tag'].includes(shape)) {
  29182. scaleY = (nodeHeight + sMult) / nodeHeight;
  29183. sHeight = nodeHeight * scaleY;
  29184. }
  29185. }
  29186. cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(sWidth, sHeight) : cornerRadius;
  29187. var halfW = sWidth / 2;
  29188. var halfH = sHeight / 2;
  29189. var radius = cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2;
  29190. var p = new Array(points.length / 2);
  29191. var corners = new Array(points.length / 2);
  29192. for (var _i2 = 0; _i2 < points.length / 2; _i2++) {
  29193. p[_i2] = {
  29194. x: npos.x + offsetX + halfW * points[_i2 * 2],
  29195. y: npos.y + offsetY + halfH * points[_i2 * 2 + 1]
  29196. };
  29197. }
  29198. var _i3,
  29199. p1,
  29200. p2,
  29201. p3,
  29202. len = p.length;
  29203. p1 = p[len - 1];
  29204. // for each point
  29205. for (_i3 = 0; _i3 < len; _i3++) {
  29206. p2 = p[_i3 % len];
  29207. p3 = p[(_i3 + 1) % len];
  29208. corners[_i3] = getRoundCorner(p1, p2, p3, radius);
  29209. p1 = p2;
  29210. p2 = p3;
  29211. }
  29212. r.drawRoundPolygonPath(_path || context, npos.x + offsetX, npos.y + offsetY, nodeWidth * scaleX, nodeHeight * scaleY, points, corners);
  29213. } else if (['roundrectangle', 'round-rectangle'].includes(shape)) {
  29214. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
  29215. r.drawRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
  29216. } else if (['cutrectangle', 'cut-rectangle'].includes(shape)) {
  29217. cornerRadius = cornerRadius === 'auto' ? getCutRectangleCornerLength() : cornerRadius;
  29218. r.drawCutRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, null, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 4);
  29219. } else if (['bottomroundrectangle', 'bottom-round-rectangle'].includes(shape)) {
  29220. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
  29221. r.drawBottomRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
  29222. } else if (shape === "barrel") {
  29223. r.drawBarrelPath(_path || context, npos.x, npos.y, sWidth, sHeight);
  29224. } else if (shape.startsWith("polygon") || ['rhomboid', 'right-rhomboid', 'round-tag', 'tag', 'vee'].includes(shape)) {
  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. } else {
  29229. var _pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
  29230. points = joinLines(expandPolygon(points, -_pad));
  29231. r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
  29232. }
  29233. if (usePaths) {
  29234. context.stroke(_path);
  29235. } else {
  29236. context.stroke();
  29237. }
  29238. if (outlineStyle === 'double') {
  29239. context.lineWidth = bWidth / 3;
  29240. var gco = context.globalCompositeOperation;
  29241. context.globalCompositeOperation = 'destination-out';
  29242. if (usePaths) {
  29243. context.stroke(_path);
  29244. } else {
  29245. context.stroke();
  29246. }
  29247. context.globalCompositeOperation = gco;
  29248. }
  29249. // reset in case we changed the border style
  29250. if (context.setLineDash) {
  29251. // for very outofdate browsers
  29252. context.setLineDash([]);
  29253. }
  29254. }
  29255. };
  29256. var drawOverlay = function drawOverlay() {
  29257. if (shouldDrawOverlay) {
  29258. r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);
  29259. }
  29260. };
  29261. var drawUnderlay = function drawUnderlay() {
  29262. if (shouldDrawOverlay) {
  29263. r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);
  29264. }
  29265. };
  29266. var drawText = function drawText() {
  29267. r.drawElementText(context, node, null, drawLabel);
  29268. };
  29269. var ghost = node.pstyle('ghost').value === 'yes';
  29270. if (ghost) {
  29271. var gx = node.pstyle('ghost-offset-x').pfValue;
  29272. var gy = node.pstyle('ghost-offset-y').pfValue;
  29273. var ghostOpacity = node.pstyle('ghost-opacity').value;
  29274. var effGhostOpacity = ghostOpacity * eleOpacity;
  29275. context.translate(gx, gy);
  29276. setupOutlineColor();
  29277. drawOutline();
  29278. setupShapeColor(ghostOpacity * bgOpacity);
  29279. drawShape();
  29280. drawImages(effGhostOpacity, true);
  29281. setupBorderColor(ghostOpacity * borderOpacity);
  29282. drawBorder();
  29283. drawPie(darkness !== 0 || borderWidth !== 0);
  29284. drawStripe(darkness !== 0 || borderWidth !== 0);
  29285. drawImages(effGhostOpacity, false);
  29286. darken(effGhostOpacity);
  29287. context.translate(-gx, -gy);
  29288. }
  29289. if (usePaths) {
  29290. context.translate(-pos.x, -pos.y);
  29291. }
  29292. drawUnderlay();
  29293. if (usePaths) {
  29294. context.translate(pos.x, pos.y);
  29295. }
  29296. setupOutlineColor();
  29297. drawOutline();
  29298. setupShapeColor();
  29299. drawShape();
  29300. drawImages(eleOpacity, true);
  29301. setupBorderColor();
  29302. drawBorder();
  29303. drawPie(darkness !== 0 || borderWidth !== 0);
  29304. drawStripe(darkness !== 0 || borderWidth !== 0);
  29305. drawImages(eleOpacity, false);
  29306. darken();
  29307. if (usePaths) {
  29308. context.translate(-pos.x, -pos.y);
  29309. }
  29310. drawText();
  29311. drawOverlay();
  29312. //
  29313. // clean up shift
  29314. if (shiftToOriginWithBb) {
  29315. context.translate(bb.x1, bb.y1);
  29316. }
  29317. };
  29318. var drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {
  29319. if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
  29320. throw new Error('Invalid state');
  29321. }
  29322. return function (context, node, pos, nodeWidth, nodeHeight) {
  29323. var r = this;
  29324. if (!node.visible()) {
  29325. return;
  29326. }
  29327. var padding = node.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
  29328. var opacity = node.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
  29329. var color = node.pstyle("".concat(overlayOrUnderlay, "-color")).value;
  29330. var shape = node.pstyle("".concat(overlayOrUnderlay, "-shape")).value;
  29331. var radius = node.pstyle("".concat(overlayOrUnderlay, "-corner-radius")).value;
  29332. if (opacity > 0) {
  29333. pos = pos || node.position();
  29334. if (nodeWidth == null || nodeHeight == null) {
  29335. var _padding = node.padding();
  29336. nodeWidth = node.width() + 2 * _padding;
  29337. nodeHeight = node.height() + 2 * _padding;
  29338. }
  29339. r.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29340. r.nodeShapes[shape].draw(context, pos.x, pos.y, nodeWidth + padding * 2, nodeHeight + padding * 2, radius);
  29341. context.fill();
  29342. }
  29343. };
  29344. };
  29345. CRp$6.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');
  29346. CRp$6.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay');
  29347. // does the node have at least one pie piece?
  29348. CRp$6.hasPie = function (node) {
  29349. node = node[0]; // ensure ele ref
  29350. return node._private.hasPie;
  29351. };
  29352. CRp$6.hasStripe = function (node) {
  29353. node = node[0]; // ensure ele ref
  29354. return node._private.hasStripe;
  29355. };
  29356. CRp$6.drawPie = function (context, node, nodeOpacity, pos) {
  29357. node = node[0]; // ensure ele ref
  29358. pos = pos || node.position();
  29359. var cyStyle = node.cy().style();
  29360. var pieSize = node.pstyle('pie-size');
  29361. var hole = node.pstyle('pie-hole');
  29362. var overallStartAngle = node.pstyle('pie-start-angle').pfValue;
  29363. var x = pos.x;
  29364. var y = pos.y;
  29365. var nodeW = node.width();
  29366. var nodeH = node.height();
  29367. var radius = Math.min(nodeW, nodeH) / 2; // must fit in node
  29368. var holeRadius;
  29369. var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  29370. var usePaths = this.usePaths();
  29371. if (usePaths) {
  29372. x = 0;
  29373. y = 0;
  29374. }
  29375. if (pieSize.units === '%') {
  29376. radius = radius * pieSize.pfValue;
  29377. } else if (pieSize.pfValue !== undefined) {
  29378. radius = pieSize.pfValue / 2; // diameter in pixels => radius
  29379. }
  29380. if (hole.units === '%') {
  29381. holeRadius = radius * hole.pfValue;
  29382. } else if (hole.pfValue !== undefined) {
  29383. holeRadius = hole.pfValue / 2; // diameter in pixels => radius
  29384. }
  29385. if (holeRadius >= radius) {
  29386. return; // the pie would be invisible anyway
  29387. }
  29388. for (var i = 1; i <= cyStyle.pieBackgroundN; i++) {
  29389. // 1..N
  29390. var size = node.pstyle('pie-' + i + '-background-size').value;
  29391. var color = node.pstyle('pie-' + i + '-background-color').value;
  29392. var opacity = node.pstyle('pie-' + i + '-background-opacity').value * nodeOpacity;
  29393. var percent = size / 100; // map integer range [0, 100] to [0, 1]
  29394. // percent can't push beyond 1
  29395. if (percent + lastPercent > 1) {
  29396. percent = 1 - lastPercent;
  29397. }
  29398. var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise
  29399. angleStart += overallStartAngle; // shift by the overall pie start angle
  29400. var angleDelta = 2 * Math.PI * percent;
  29401. var angleEnd = angleStart + angleDelta;
  29402. // ignore if
  29403. // - zero size
  29404. // - we're already beyond the full circle
  29405. // - adding the current slice would go beyond the full circle
  29406. if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
  29407. continue;
  29408. }
  29409. if (holeRadius === 0) {
  29410. // make a pie slice
  29411. context.beginPath();
  29412. context.moveTo(x, y);
  29413. context.arc(x, y, radius, angleStart, angleEnd);
  29414. context.closePath();
  29415. } else {
  29416. // make a pie slice that's like the above but with a hole in the middle
  29417. context.beginPath();
  29418. context.arc(x, y, radius, angleStart, angleEnd);
  29419. context.arc(x, y, holeRadius, angleEnd, angleStart, true); // true for anticlockwise
  29420. context.closePath();
  29421. }
  29422. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29423. context.fill();
  29424. lastPercent += percent;
  29425. }
  29426. };
  29427. CRp$6.drawStripe = function (context, node, nodeOpacity, pos) {
  29428. node = node[0]; // ensure ele ref
  29429. pos = pos || node.position();
  29430. var cyStyle = node.cy().style();
  29431. var x = pos.x;
  29432. var y = pos.y;
  29433. var nodeW = node.width();
  29434. var nodeH = node.height();
  29435. var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  29436. var usePaths = this.usePaths();
  29437. context.save();
  29438. var direction = node.pstyle('stripe-direction').value;
  29439. var stripeSize = node.pstyle('stripe-size');
  29440. switch (direction) {
  29441. case 'vertical':
  29442. break;
  29443. // default
  29444. case 'righward':
  29445. context.rotate(-Math.PI / 2);
  29446. break;
  29447. }
  29448. var stripeW = nodeW;
  29449. var stripeH = nodeH;
  29450. if (stripeSize.units === '%') {
  29451. stripeW = stripeW * stripeSize.pfValue;
  29452. stripeH = stripeH * stripeSize.pfValue;
  29453. } else if (stripeSize.pfValue !== undefined) {
  29454. stripeW = stripeSize.pfValue;
  29455. stripeH = stripeSize.pfValue;
  29456. }
  29457. if (usePaths) {
  29458. x = 0;
  29459. y = 0;
  29460. }
  29461. // shift up from the centre of the node to the top-left corner
  29462. y -= stripeW / 2;
  29463. x -= stripeH / 2;
  29464. for (var i = 1; i <= cyStyle.stripeBackgroundN; i++) {
  29465. // 1..N
  29466. var size = node.pstyle('stripe-' + i + '-background-size').value;
  29467. var color = node.pstyle('stripe-' + i + '-background-color').value;
  29468. var opacity = node.pstyle('stripe-' + i + '-background-opacity').value * nodeOpacity;
  29469. var percent = size / 100; // map integer range [0, 100] to [0, 1]
  29470. // percent can't push beyond 1
  29471. if (percent + lastPercent > 1) {
  29472. percent = 1 - lastPercent;
  29473. }
  29474. // ignore if
  29475. // - zero size
  29476. // - we're already beyond the full chart
  29477. // - adding the current slice would go beyond the full chart
  29478. if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
  29479. continue;
  29480. }
  29481. // draw rect for the current stripe
  29482. context.beginPath();
  29483. context.rect(x, y + stripeH * lastPercent, stripeW, stripeH * percent);
  29484. context.closePath();
  29485. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29486. context.fill();
  29487. lastPercent += percent;
  29488. }
  29489. context.restore();
  29490. };
  29491. var CRp$5 = {};
  29492. var motionBlurDelay = 100;
  29493. // var isFirefox = typeof InstallTrigger !== 'undefined';
  29494. CRp$5.getPixelRatio = function () {
  29495. var context = this.data.contexts[0];
  29496. if (this.forcedPixelRatio != null) {
  29497. return this.forcedPixelRatio;
  29498. }
  29499. var containerWindow = this.cy.window();
  29500. var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29501. return (containerWindow.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef
  29502. };
  29503. CRp$5.paintCache = function (context) {
  29504. var caches = this.paintCaches = this.paintCaches || [];
  29505. var needToCreateCache = true;
  29506. var cache;
  29507. for (var i = 0; i < caches.length; i++) {
  29508. cache = caches[i];
  29509. if (cache.context === context) {
  29510. needToCreateCache = false;
  29511. break;
  29512. }
  29513. }
  29514. if (needToCreateCache) {
  29515. cache = {
  29516. context: context
  29517. };
  29518. caches.push(cache);
  29519. }
  29520. return cache;
  29521. };
  29522. CRp$5.createGradientStyleFor = function (context, shapeStyleName, ele, fill, opacity) {
  29523. var gradientStyle;
  29524. var usePaths = this.usePaths();
  29525. var colors = ele.pstyle(shapeStyleName + '-gradient-stop-colors').value,
  29526. positions = ele.pstyle(shapeStyleName + '-gradient-stop-positions').pfValue;
  29527. if (fill === 'radial-gradient') {
  29528. if (ele.isEdge()) {
  29529. var start = ele.sourceEndpoint(),
  29530. end = ele.targetEndpoint(),
  29531. mid = ele.midpoint();
  29532. var d1 = dist(start, mid);
  29533. var d2 = dist(end, mid);
  29534. gradientStyle = context.createRadialGradient(mid.x, mid.y, 0, mid.x, mid.y, Math.max(d1, d2));
  29535. } else {
  29536. var pos = usePaths ? {
  29537. x: 0,
  29538. y: 0
  29539. } : ele.position(),
  29540. width = ele.paddedWidth(),
  29541. height = ele.paddedHeight();
  29542. gradientStyle = context.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, Math.max(width, height));
  29543. }
  29544. } else {
  29545. if (ele.isEdge()) {
  29546. var _start = ele.sourceEndpoint(),
  29547. _end = ele.targetEndpoint();
  29548. gradientStyle = context.createLinearGradient(_start.x, _start.y, _end.x, _end.y);
  29549. } else {
  29550. var _pos = usePaths ? {
  29551. x: 0,
  29552. y: 0
  29553. } : ele.position(),
  29554. _width = ele.paddedWidth(),
  29555. _height = ele.paddedHeight(),
  29556. halfWidth = _width / 2,
  29557. halfHeight = _height / 2;
  29558. var direction = ele.pstyle('background-gradient-direction').value;
  29559. switch (direction) {
  29560. case 'to-bottom':
  29561. gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);
  29562. break;
  29563. case 'to-top':
  29564. gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);
  29565. break;
  29566. case 'to-left':
  29567. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);
  29568. break;
  29569. case 'to-right':
  29570. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);
  29571. break;
  29572. case 'to-bottom-right':
  29573. case 'to-right-bottom':
  29574. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y - halfHeight, _pos.x + halfWidth, _pos.y + halfHeight);
  29575. break;
  29576. case 'to-top-right':
  29577. case 'to-right-top':
  29578. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y + halfHeight, _pos.x + halfWidth, _pos.y - halfHeight);
  29579. break;
  29580. case 'to-bottom-left':
  29581. case 'to-left-bottom':
  29582. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y - halfHeight, _pos.x - halfWidth, _pos.y + halfHeight);
  29583. break;
  29584. case 'to-top-left':
  29585. case 'to-left-top':
  29586. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y + halfHeight, _pos.x - halfWidth, _pos.y - halfHeight);
  29587. break;
  29588. }
  29589. }
  29590. }
  29591. if (!gradientStyle) return null; // invalid gradient style
  29592. var hasPositions = positions.length === colors.length;
  29593. var length = colors.length;
  29594. for (var i = 0; i < length; i++) {
  29595. gradientStyle.addColorStop(hasPositions ? positions[i] : i / (length - 1), 'rgba(' + colors[i][0] + ',' + colors[i][1] + ',' + colors[i][2] + ',' + opacity + ')');
  29596. }
  29597. return gradientStyle;
  29598. };
  29599. CRp$5.gradientFillStyle = function (context, ele, fill, opacity) {
  29600. var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);
  29601. if (!gradientStyle) return null; // error
  29602. context.fillStyle = gradientStyle;
  29603. };
  29604. CRp$5.colorFillStyle = function (context, r, g, b, a) {
  29605. context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29606. // turn off for now, seems context does its own caching
  29607. // var cache = this.paintCache(context);
  29608. // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29609. // if( cache.fillStyle !== fillStyle ){
  29610. // context.fillStyle = cache.fillStyle = fillStyle;
  29611. // }
  29612. };
  29613. CRp$5.eleFillStyle = function (context, ele, opacity) {
  29614. var backgroundFill = ele.pstyle('background-fill').value;
  29615. if (backgroundFill === 'linear-gradient' || backgroundFill === 'radial-gradient') {
  29616. this.gradientFillStyle(context, ele, backgroundFill, opacity);
  29617. } else {
  29618. var backgroundColor = ele.pstyle('background-color').value;
  29619. this.colorFillStyle(context, backgroundColor[0], backgroundColor[1], backgroundColor[2], opacity);
  29620. }
  29621. };
  29622. CRp$5.gradientStrokeStyle = function (context, ele, fill, opacity) {
  29623. var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);
  29624. if (!gradientStyle) return null; // error
  29625. context.strokeStyle = gradientStyle;
  29626. };
  29627. CRp$5.colorStrokeStyle = function (context, r, g, b, a) {
  29628. context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29629. // turn off for now, seems context does its own caching
  29630. // var cache = this.paintCache(context);
  29631. // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29632. // if( cache.strokeStyle !== strokeStyle ){
  29633. // context.strokeStyle = cache.strokeStyle = strokeStyle;
  29634. // }
  29635. };
  29636. CRp$5.eleStrokeStyle = function (context, ele, opacity) {
  29637. var lineFill = ele.pstyle('line-fill').value;
  29638. if (lineFill === 'linear-gradient' || lineFill === 'radial-gradient') {
  29639. this.gradientStrokeStyle(context, ele, lineFill, opacity);
  29640. } else {
  29641. var lineColor = ele.pstyle('line-color').value;
  29642. this.colorStrokeStyle(context, lineColor[0], lineColor[1], lineColor[2], opacity);
  29643. }
  29644. };
  29645. // Resize canvas
  29646. CRp$5.matchCanvasSize = function (container) {
  29647. var r = this;
  29648. var data = r.data;
  29649. var bb = r.findContainerClientCoords();
  29650. var width = bb[2];
  29651. var height = bb[3];
  29652. var pixelRatio = r.getPixelRatio();
  29653. var mbPxRatio = r.motionBlurPxRatio;
  29654. if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {
  29655. pixelRatio = mbPxRatio;
  29656. }
  29657. var canvasWidth = width * pixelRatio;
  29658. var canvasHeight = height * pixelRatio;
  29659. var canvas;
  29660. if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {
  29661. return; // save cycles if same
  29662. }
  29663. r.fontCaches = null; // resizing resets the style
  29664. var canvasContainer = data.canvasContainer;
  29665. canvasContainer.style.width = width + 'px';
  29666. canvasContainer.style.height = height + 'px';
  29667. for (var i = 0; i < r.CANVAS_LAYERS; i++) {
  29668. canvas = data.canvases[i];
  29669. canvas.width = canvasWidth;
  29670. canvas.height = canvasHeight;
  29671. canvas.style.width = width + 'px';
  29672. canvas.style.height = height + 'px';
  29673. }
  29674. for (var i = 0; i < r.BUFFER_COUNT; i++) {
  29675. canvas = data.bufferCanvases[i];
  29676. canvas.width = canvasWidth;
  29677. canvas.height = canvasHeight;
  29678. canvas.style.width = width + 'px';
  29679. canvas.style.height = height + 'px';
  29680. }
  29681. r.textureMult = 1;
  29682. if (pixelRatio <= 1) {
  29683. canvas = data.bufferCanvases[r.TEXTURE_BUFFER];
  29684. r.textureMult = 2;
  29685. canvas.width = canvasWidth * r.textureMult;
  29686. canvas.height = canvasHeight * r.textureMult;
  29687. }
  29688. r.canvasWidth = canvasWidth;
  29689. r.canvasHeight = canvasHeight;
  29690. r.pixelRatio = pixelRatio;
  29691. };
  29692. CRp$5.renderTo = function (cxt, zoom, pan, pxRatio) {
  29693. this.render({
  29694. forcedContext: cxt,
  29695. forcedZoom: zoom,
  29696. forcedPan: pan,
  29697. drawAllLayers: true,
  29698. forcedPxRatio: pxRatio
  29699. });
  29700. };
  29701. CRp$5.clearCanvas = function () {
  29702. var r = this;
  29703. var data = r.data;
  29704. function clear(context) {
  29705. context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  29706. }
  29707. clear(data.contexts[r.NODE]);
  29708. clear(data.contexts[r.DRAG]);
  29709. };
  29710. CRp$5.render = function (options) {
  29711. var r = this;
  29712. options = options || staticEmptyObject();
  29713. var cy = r.cy;
  29714. var forcedContext = options.forcedContext;
  29715. var drawAllLayers = options.drawAllLayers;
  29716. var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  29717. var forcedZoom = options.forcedZoom;
  29718. var forcedPan = options.forcedPan;
  29719. var pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;
  29720. var data = r.data;
  29721. var needDraw = data.canvasNeedsRedraw;
  29722. var textureDraw = r.textureOnViewport && !forcedContext && (r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming);
  29723. var motionBlur = options.motionBlur !== undefined ? options.motionBlur : r.motionBlur;
  29724. var mbPxRatio = r.motionBlurPxRatio;
  29725. var hasCompoundNodes = cy.hasCompoundNodes();
  29726. var inNodeDragGesture = r.hoverData.draggingEles;
  29727. var inBoxSelection = r.hoverData.selecting || r.touchData.selecting ? true : false;
  29728. motionBlur = motionBlur && !forcedContext && r.motionBlurEnabled && !inBoxSelection;
  29729. var motionBlurFadeEffect = motionBlur;
  29730. if (!forcedContext) {
  29731. if (r.prevPxRatio !== pixelRatio) {
  29732. r.invalidateContainerClientCoordsCache();
  29733. r.matchCanvasSize(r.container);
  29734. r.redrawHint('eles', true);
  29735. r.redrawHint('drag', true);
  29736. }
  29737. r.prevPxRatio = pixelRatio;
  29738. }
  29739. if (!forcedContext && r.motionBlurTimeout) {
  29740. clearTimeout(r.motionBlurTimeout);
  29741. }
  29742. if (motionBlur) {
  29743. if (r.mbFrames == null) {
  29744. r.mbFrames = 0;
  29745. }
  29746. r.mbFrames++;
  29747. if (r.mbFrames < 3) {
  29748. // need several frames before even high quality motionblur
  29749. motionBlurFadeEffect = false;
  29750. }
  29751. // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)
  29752. if (r.mbFrames > r.minMbLowQualFrames) {
  29753. //r.fullQualityMb = false;
  29754. r.motionBlurPxRatio = r.mbPxRBlurry;
  29755. }
  29756. }
  29757. if (r.clearingMotionBlur) {
  29758. r.motionBlurPxRatio = 1;
  29759. }
  29760. // b/c drawToContext() may be async w.r.t. redraw(), keep track of last texture frame
  29761. // because a rogue async texture frame would clear needDraw
  29762. if (r.textureDrawLastFrame && !textureDraw) {
  29763. needDraw[r.NODE] = true;
  29764. needDraw[r.SELECT_BOX] = true;
  29765. }
  29766. var style = cy.style();
  29767. var zoom = cy.zoom();
  29768. var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;
  29769. var pan = cy.pan();
  29770. var effectivePan = {
  29771. x: pan.x,
  29772. y: pan.y
  29773. };
  29774. var vp = {
  29775. zoom: zoom,
  29776. pan: {
  29777. x: pan.x,
  29778. y: pan.y
  29779. }
  29780. };
  29781. var prevVp = r.prevViewport;
  29782. var viewportIsDiff = prevVp === undefined || vp.zoom !== prevVp.zoom || vp.pan.x !== prevVp.pan.x || vp.pan.y !== prevVp.pan.y;
  29783. // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)
  29784. if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {
  29785. r.motionBlurPxRatio = 1;
  29786. }
  29787. if (forcedPan) {
  29788. effectivePan = forcedPan;
  29789. }
  29790. // apply pixel ratio
  29791. effectiveZoom *= pixelRatio;
  29792. effectivePan.x *= pixelRatio;
  29793. effectivePan.y *= pixelRatio;
  29794. var eles = r.getCachedZSortedEles();
  29795. function mbclear(context, x, y, w, h) {
  29796. var gco = context.globalCompositeOperation;
  29797. context.globalCompositeOperation = 'destination-out';
  29798. r.colorFillStyle(context, 255, 255, 255, r.motionBlurTransparency);
  29799. context.fillRect(x, y, w, h);
  29800. context.globalCompositeOperation = gco;
  29801. }
  29802. function setContextTransform(context, clear) {
  29803. var ePan, eZoom, w, h;
  29804. if (!r.clearingMotionBlur && (context === data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] || context === data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG])) {
  29805. ePan = {
  29806. x: pan.x * mbPxRatio,
  29807. y: pan.y * mbPxRatio
  29808. };
  29809. eZoom = zoom * mbPxRatio;
  29810. w = r.canvasWidth * mbPxRatio;
  29811. h = r.canvasHeight * mbPxRatio;
  29812. } else {
  29813. ePan = effectivePan;
  29814. eZoom = effectiveZoom;
  29815. w = r.canvasWidth;
  29816. h = r.canvasHeight;
  29817. }
  29818. context.setTransform(1, 0, 0, 1, 0, 0);
  29819. if (clear === 'motionBlur') {
  29820. mbclear(context, 0, 0, w, h);
  29821. } else if (!forcedContext && (clear === undefined || clear)) {
  29822. context.clearRect(0, 0, w, h);
  29823. }
  29824. if (!drawAllLayers) {
  29825. context.translate(ePan.x, ePan.y);
  29826. context.scale(eZoom, eZoom);
  29827. }
  29828. if (forcedPan) {
  29829. context.translate(forcedPan.x, forcedPan.y);
  29830. }
  29831. if (forcedZoom) {
  29832. context.scale(forcedZoom, forcedZoom);
  29833. }
  29834. }
  29835. if (!textureDraw) {
  29836. r.textureDrawLastFrame = false;
  29837. }
  29838. if (textureDraw) {
  29839. r.textureDrawLastFrame = true;
  29840. if (!r.textureCache) {
  29841. r.textureCache = {};
  29842. r.textureCache.bb = cy.mutableElements().boundingBox();
  29843. r.textureCache.texture = r.data.bufferCanvases[r.TEXTURE_BUFFER];
  29844. var cxt = r.data.bufferContexts[r.TEXTURE_BUFFER];
  29845. cxt.setTransform(1, 0, 0, 1, 0, 0);
  29846. cxt.clearRect(0, 0, r.canvasWidth * r.textureMult, r.canvasHeight * r.textureMult);
  29847. r.render({
  29848. forcedContext: cxt,
  29849. drawOnlyNodeLayer: true,
  29850. forcedPxRatio: pixelRatio * r.textureMult
  29851. });
  29852. var vp = r.textureCache.viewport = {
  29853. zoom: cy.zoom(),
  29854. pan: cy.pan(),
  29855. width: r.canvasWidth,
  29856. height: r.canvasHeight
  29857. };
  29858. vp.mpan = {
  29859. x: (0 - vp.pan.x) / vp.zoom,
  29860. y: (0 - vp.pan.y) / vp.zoom
  29861. };
  29862. }
  29863. needDraw[r.DRAG] = false;
  29864. needDraw[r.NODE] = false;
  29865. var context = data.contexts[r.NODE];
  29866. var texture = r.textureCache.texture;
  29867. var vp = r.textureCache.viewport;
  29868. context.setTransform(1, 0, 0, 1, 0, 0);
  29869. if (motionBlur) {
  29870. mbclear(context, 0, 0, vp.width, vp.height);
  29871. } else {
  29872. context.clearRect(0, 0, vp.width, vp.height);
  29873. }
  29874. var outsideBgColor = style.core('outside-texture-bg-color').value;
  29875. var outsideBgOpacity = style.core('outside-texture-bg-opacity').value;
  29876. r.colorFillStyle(context, outsideBgColor[0], outsideBgColor[1], outsideBgColor[2], outsideBgOpacity);
  29877. context.fillRect(0, 0, vp.width, vp.height);
  29878. var zoom = cy.zoom();
  29879. setContextTransform(context, false);
  29880. context.clearRect(vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  29881. context.drawImage(texture, vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  29882. } else if (r.textureOnViewport && !forcedContext) {
  29883. // clear the cache since we don't need it
  29884. r.textureCache = null;
  29885. }
  29886. var extent = cy.extent();
  29887. var vpManip = r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming || r.hoverData.draggingEles || r.cy.animated();
  29888. var hideEdges = r.hideEdgesOnViewport && vpManip;
  29889. var needMbClear = [];
  29890. needMbClear[r.NODE] = !needDraw[r.NODE] && motionBlur && !r.clearedForMotionBlur[r.NODE] || r.clearingMotionBlur;
  29891. if (needMbClear[r.NODE]) {
  29892. r.clearedForMotionBlur[r.NODE] = true;
  29893. }
  29894. needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;
  29895. if (needMbClear[r.DRAG]) {
  29896. r.clearedForMotionBlur[r.DRAG] = true;
  29897. }
  29898. if (needDraw[r.NODE] || drawAllLayers || drawOnlyNodeLayer || needMbClear[r.NODE]) {
  29899. var useBuffer = motionBlur && !needMbClear[r.NODE] && mbPxRatio !== 1;
  29900. var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] : data.contexts[r.NODE]);
  29901. var clear = motionBlur && !useBuffer ? 'motionBlur' : undefined;
  29902. setContextTransform(context, clear);
  29903. if (hideEdges) {
  29904. r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);
  29905. } else {
  29906. r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);
  29907. }
  29908. if (r.debug) {
  29909. r.drawDebugPoints(context, eles.nondrag);
  29910. }
  29911. if (!drawAllLayers && !motionBlur) {
  29912. needDraw[r.NODE] = false;
  29913. }
  29914. }
  29915. if (!drawOnlyNodeLayer && (needDraw[r.DRAG] || drawAllLayers || needMbClear[r.DRAG])) {
  29916. var useBuffer = motionBlur && !needMbClear[r.DRAG] && mbPxRatio !== 1;
  29917. var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG] : data.contexts[r.DRAG]);
  29918. setContextTransform(context, motionBlur && !useBuffer ? 'motionBlur' : undefined);
  29919. if (hideEdges) {
  29920. r.drawCachedNodes(context, eles.drag, pixelRatio, extent);
  29921. } else {
  29922. r.drawCachedElements(context, eles.drag, pixelRatio, extent);
  29923. }
  29924. if (r.debug) {
  29925. r.drawDebugPoints(context, eles.drag);
  29926. }
  29927. if (!drawAllLayers && !motionBlur) {
  29928. needDraw[r.DRAG] = false;
  29929. }
  29930. }
  29931. this.drawSelectionRectangle(options, setContextTransform);
  29932. // motionblur: blit rendered blurry frames
  29933. if (motionBlur && mbPxRatio !== 1) {
  29934. var cxtNode = data.contexts[r.NODE];
  29935. var txtNode = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE];
  29936. var cxtDrag = data.contexts[r.DRAG];
  29937. var txtDrag = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG];
  29938. var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {
  29939. cxt.setTransform(1, 0, 0, 1, 0, 0);
  29940. if (needClear || !motionBlurFadeEffect) {
  29941. cxt.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  29942. } else {
  29943. mbclear(cxt, 0, 0, r.canvasWidth, r.canvasHeight);
  29944. }
  29945. var pxr = mbPxRatio;
  29946. cxt.drawImage(txt,
  29947. // img
  29948. 0, 0,
  29949. // sx, sy
  29950. r.canvasWidth * pxr, r.canvasHeight * pxr,
  29951. // sw, sh
  29952. 0, 0,
  29953. // x, y
  29954. r.canvasWidth, r.canvasHeight // w, h
  29955. );
  29956. };
  29957. if (needDraw[r.NODE] || needMbClear[r.NODE]) {
  29958. drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);
  29959. needDraw[r.NODE] = false;
  29960. }
  29961. if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {
  29962. drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);
  29963. needDraw[r.DRAG] = false;
  29964. }
  29965. }
  29966. r.prevViewport = vp;
  29967. if (r.clearingMotionBlur) {
  29968. r.clearingMotionBlur = false;
  29969. r.motionBlurCleared = true;
  29970. r.motionBlur = true;
  29971. }
  29972. if (motionBlur) {
  29973. r.motionBlurTimeout = setTimeout(function () {
  29974. r.motionBlurTimeout = null;
  29975. r.clearedForMotionBlur[r.NODE] = false;
  29976. r.clearedForMotionBlur[r.DRAG] = false;
  29977. r.motionBlur = false;
  29978. r.clearingMotionBlur = !textureDraw;
  29979. r.mbFrames = 0;
  29980. needDraw[r.NODE] = true;
  29981. needDraw[r.DRAG] = true;
  29982. r.redraw();
  29983. }, motionBlurDelay);
  29984. }
  29985. if (!forcedContext) {
  29986. cy.emit('render');
  29987. }
  29988. };
  29989. var fpsHeight;
  29990. CRp$5.drawSelectionRectangle = function (options, setContextTransform) {
  29991. var r = this;
  29992. var cy = r.cy;
  29993. var data = r.data;
  29994. var style = cy.style();
  29995. var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  29996. var drawAllLayers = options.drawAllLayers;
  29997. var needDraw = data.canvasNeedsRedraw;
  29998. var forcedContext = options.forcedContext;
  29999. if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {
  30000. var context = forcedContext || data.contexts[r.SELECT_BOX];
  30001. setContextTransform(context);
  30002. if (r.selection[4] == 1 && (r.hoverData.selecting || r.touchData.selecting)) {
  30003. var zoom = r.cy.zoom();
  30004. var borderWidth = style.core('selection-box-border-width').value / zoom;
  30005. context.lineWidth = borderWidth;
  30006. 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 + ')';
  30007. context.fillRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
  30008. if (borderWidth > 0) {
  30009. 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 + ')';
  30010. context.strokeRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
  30011. }
  30012. }
  30013. if (data.bgActivePosistion && !r.hoverData.selecting) {
  30014. var zoom = r.cy.zoom();
  30015. var pos = data.bgActivePosistion;
  30016. 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 + ')';
  30017. context.beginPath();
  30018. context.arc(pos.x, pos.y, style.core('active-bg-size').pfValue / zoom, 0, 2 * Math.PI);
  30019. context.fill();
  30020. }
  30021. var timeToRender = r.lastRedrawTime;
  30022. if (r.showFps && timeToRender) {
  30023. timeToRender = Math.round(timeToRender);
  30024. var fps = Math.round(1000 / timeToRender);
  30025. var text = '1 frame = ' + timeToRender + ' ms = ' + fps + ' fps';
  30026. context.setTransform(1, 0, 0, 1, 0, 0);
  30027. context.fillStyle = 'rgba(255, 0, 0, 0.75)';
  30028. context.strokeStyle = 'rgba(255, 0, 0, 0.75)';
  30029. // context.lineWidth = 1;
  30030. context.font = '30px Arial';
  30031. if (!fpsHeight) {
  30032. var dims = context.measureText(text);
  30033. fpsHeight = dims.actualBoundingBoxAscent;
  30034. }
  30035. context.fillText(text, 0, fpsHeight);
  30036. var maxFps = 60;
  30037. context.strokeRect(0, fpsHeight + 10, 250, 20);
  30038. context.fillRect(0, fpsHeight + 10, 250 * Math.min(fps / maxFps, 1), 20);
  30039. }
  30040. if (!drawAllLayers) {
  30041. needDraw[r.SELECT_BOX] = false;
  30042. }
  30043. }
  30044. };
  30045. /**
  30046. * Notes:
  30047. * - All colors have premultiplied alpha. Very important for textues and
  30048. * blending to work correctly.
  30049. */
  30050. function compileShader(gl, type, source) {
  30051. var shader = gl.createShader(type);
  30052. gl.shaderSource(shader, source);
  30053. gl.compileShader(shader);
  30054. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  30055. throw new Error(gl.getShaderInfoLog(shader));
  30056. }
  30057. // console.log(gl.getShaderInfoLog(shader));
  30058. return shader;
  30059. }
  30060. function createProgram(gl, vertexSource, fragementSource) {
  30061. var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);
  30062. var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragementSource);
  30063. var program = gl.createProgram();
  30064. gl.attachShader(program, vertexShader);
  30065. gl.attachShader(program, fragmentShader);
  30066. gl.linkProgram(program);
  30067. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  30068. throw new Error('Could not initialize shaders');
  30069. }
  30070. return program;
  30071. }
  30072. /**
  30073. * Creates an offscren canvas with a 2D context, for the
  30074. * canvas renderer to use for drawing textures.
  30075. */
  30076. function createTextureCanvas(r, width, height) {
  30077. if (height === undefined) {
  30078. height = width;
  30079. }
  30080. var canvas = r.makeOffscreenCanvas(width, height);
  30081. var ctx = canvas.context = canvas.getContext('2d');
  30082. canvas.clear = function () {
  30083. return ctx.clearRect(0, 0, canvas.width, canvas.height);
  30084. };
  30085. canvas.clear();
  30086. return canvas;
  30087. }
  30088. /**
  30089. * Returns the current pan & zoom values, scaled by the pixel ratio.
  30090. */
  30091. function getEffectivePanZoom(r) {
  30092. var pixelRatio = r.pixelRatio;
  30093. var zoom = r.cy.zoom();
  30094. var pan = r.cy.pan();
  30095. return {
  30096. zoom: zoom * pixelRatio,
  30097. pan: {
  30098. x: pan.x * pixelRatio,
  30099. y: pan.y * pixelRatio
  30100. }
  30101. };
  30102. }
  30103. /**
  30104. * Returns the zoom value, scaled by the pixel ratio.
  30105. */
  30106. function getEffectiveZoom(r) {
  30107. var pixelRatio = r.pixelRatio;
  30108. var zoom = r.cy.zoom();
  30109. return zoom * pixelRatio;
  30110. }
  30111. function modelToRenderedPosition(r, pan, zoom, x, y) {
  30112. var rx = x * zoom + pan.x;
  30113. var ry = y * zoom + pan.y;
  30114. ry = Math.round(r.canvasHeight - ry); // adjust for webgl
  30115. return [rx, ry];
  30116. }
  30117. function isSimpleShape(node, renderTarget) {
  30118. // the actual shape is checked in ElementDrawingWebGL._getVertTypeForShape()
  30119. // no need to check it twice, this just checks other visual properties
  30120. if (renderTarget.picking) {
  30121. // We don't care about the border or background style for picking
  30122. return true;
  30123. } else {
  30124. if (node.pstyle('background-fill').value !== 'solid') return false;
  30125. if (node.pstyle('background-image').strValue !== 'none') return false;
  30126. if (node.pstyle('border-width').value === 0) return true;
  30127. if (node.pstyle('border-opacity').value === 0) return true;
  30128. // we have a border but it must be simple
  30129. if (node.pstyle('border-style').value !== 'solid') return false;
  30130. // TODO ignoring 'border-cap', 'border-join' and 'border-position' for now
  30131. return true;
  30132. }
  30133. }
  30134. function arrayEqual(a1, a2) {
  30135. if (a1.length !== a2.length) {
  30136. return false;
  30137. }
  30138. for (var i = 0; i < a1.length; i++) {
  30139. if (a1[i] !== a2[i]) {
  30140. return false;
  30141. }
  30142. }
  30143. return true;
  30144. }
  30145. /**
  30146. * Takes color & opacity style values and converts them to WebGL format.
  30147. * Alpha is premultiplied.
  30148. */
  30149. function toWebGLColor(color, opacity, outArray) {
  30150. var r = color[0] / 255;
  30151. var g = color[1] / 255;
  30152. var b = color[2] / 255;
  30153. var a = opacity;
  30154. var arr = outArray || new Array(4);
  30155. arr[0] = r * a;
  30156. arr[1] = g * a;
  30157. arr[2] = b * a;
  30158. arr[3] = a;
  30159. return arr;
  30160. }
  30161. function indexToVec4(index, outArray) {
  30162. var arr = outArray || new Array(4);
  30163. arr[0] = (index >> 0 & 0xFF) / 0xFF;
  30164. arr[1] = (index >> 8 & 0xFF) / 0xFF;
  30165. arr[2] = (index >> 16 & 0xFF) / 0xFF;
  30166. arr[3] = (index >> 24 & 0xFF) / 0xFF;
  30167. return arr;
  30168. }
  30169. function vec4ToIndex(vec4) {
  30170. return vec4[0] + (vec4[1] << 8) + (vec4[2] << 16) + (vec4[3] << 24);
  30171. }
  30172. function createTexture(gl, debugID) {
  30173. var texture = gl.createTexture();
  30174. texture.buffer = function (offscreenCanvas) {
  30175. gl.bindTexture(gl.TEXTURE_2D, texture);
  30176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  30177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  30178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  30179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  30180. // very important, this tells webgl to premultiply colors by the alpha channel
  30181. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
  30182. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offscreenCanvas);
  30183. gl.generateMipmap(gl.TEXTURE_2D);
  30184. gl.bindTexture(gl.TEXTURE_2D, null);
  30185. };
  30186. texture.deleteTexture = function () {
  30187. gl.deleteTexture(texture);
  30188. };
  30189. return texture;
  30190. }
  30191. function getTypeInfo(gl, glslType) {
  30192. switch (glslType) {
  30193. case 'float':
  30194. return [1, gl.FLOAT, 4];
  30195. case 'vec2':
  30196. return [2, gl.FLOAT, 4];
  30197. case 'vec3':
  30198. return [3, gl.FLOAT, 4];
  30199. case 'vec4':
  30200. return [4, gl.FLOAT, 4];
  30201. case 'int':
  30202. return [1, gl.INT, 4];
  30203. case 'ivec2':
  30204. return [2, gl.INT, 4];
  30205. }
  30206. }
  30207. function createTypedArray(gl, glType, dataOrSize) {
  30208. switch (glType) {
  30209. case gl.FLOAT:
  30210. return new Float32Array(dataOrSize);
  30211. case gl.INT:
  30212. return new Int32Array(dataOrSize);
  30213. }
  30214. }
  30215. function createTypedArrayView(gl, glType, array, stride, size, i) {
  30216. switch (glType) {
  30217. case gl.FLOAT:
  30218. return new Float32Array(array.buffer, i * stride, size);
  30219. case gl.INT:
  30220. return new Int32Array(array.buffer, i * stride, size);
  30221. }
  30222. }
  30223. /** @param {WebGLRenderingContext} gl */
  30224. function createBufferStaticDraw(gl, type, attributeLoc, dataArray) {
  30225. var _getTypeInfo = getTypeInfo(gl, type),
  30226. _getTypeInfo2 = _slicedToArray(_getTypeInfo, 2),
  30227. size = _getTypeInfo2[0],
  30228. glType = _getTypeInfo2[1];
  30229. var data = createTypedArray(gl, glType, dataArray);
  30230. var buffer = gl.createBuffer();
  30231. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30232. gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
  30233. if (glType === gl.FLOAT) {
  30234. gl.vertexAttribPointer(attributeLoc, size, glType, false, 0, 0);
  30235. } else if (glType === gl.INT) {
  30236. gl.vertexAttribIPointer(attributeLoc, size, glType, 0, 0);
  30237. }
  30238. gl.enableVertexAttribArray(attributeLoc);
  30239. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30240. return buffer;
  30241. }
  30242. /**
  30243. * Creates a float buffer with gl.DYNAMIC_DRAW.
  30244. * The returned buffer object contains functions to easily set instance data and buffer the data before a draw call.
  30245. * @param {WebGLRenderingContext} gl
  30246. */
  30247. function createBufferDynamicDraw(gl, instances, type, attributeLoc) {
  30248. var _getTypeInfo3 = getTypeInfo(gl, type),
  30249. _getTypeInfo4 = _slicedToArray(_getTypeInfo3, 3),
  30250. size = _getTypeInfo4[0],
  30251. glType = _getTypeInfo4[1],
  30252. bytes = _getTypeInfo4[2];
  30253. var dataArray = createTypedArray(gl, glType, instances * size);
  30254. var stride = size * bytes;
  30255. var buffer = gl.createBuffer();
  30256. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30257. gl.bufferData(gl.ARRAY_BUFFER, instances * stride, gl.DYNAMIC_DRAW);
  30258. gl.enableVertexAttribArray(attributeLoc);
  30259. if (glType === gl.FLOAT) {
  30260. gl.vertexAttribPointer(attributeLoc, size, glType, false, stride, 0);
  30261. } else if (glType === gl.INT) {
  30262. gl.vertexAttribIPointer(attributeLoc, size, glType, stride, 0);
  30263. }
  30264. gl.vertexAttribDivisor(attributeLoc, 1);
  30265. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30266. // use array views to set values directly into the buffer array
  30267. var views = new Array(instances);
  30268. for (var i = 0; i < instances; i++) {
  30269. views[i] = createTypedArrayView(gl, glType, dataArray, stride, size, i);
  30270. }
  30271. buffer.dataArray = dataArray;
  30272. buffer.stride = stride;
  30273. buffer.size = size;
  30274. buffer.getView = function (i) {
  30275. return views[i];
  30276. };
  30277. buffer.setPoint = function (i, x, y) {
  30278. var view = views[i];
  30279. view[0] = x;
  30280. view[1] = y;
  30281. };
  30282. buffer.bufferSubData = function (count) {
  30283. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30284. if (count) {
  30285. gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray, 0, count * size);
  30286. } else {
  30287. gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray);
  30288. }
  30289. };
  30290. return buffer;
  30291. }
  30292. /**
  30293. * Creates a buffer of 3x3 matrix data for use as attribute data.
  30294. * @param {WebGLRenderingContext} gl
  30295. */
  30296. function create3x3MatrixBufferDynamicDraw(gl, instances, attributeLoc) {
  30297. var matrixSize = 9; // 3x3 matrix
  30298. var matrixData = new Float32Array(instances * matrixSize);
  30299. // use matrix views to set values directly into the matrixData array
  30300. var matrixViews = new Array(instances);
  30301. for (var i = 0; i < instances; i++) {
  30302. var byteOffset = i * matrixSize * 4; // 4 bytes per float
  30303. matrixViews[i] = new Float32Array(matrixData.buffer, byteOffset, matrixSize); // array view
  30304. }
  30305. var buffer = gl.createBuffer();
  30306. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30307. gl.bufferData(gl.ARRAY_BUFFER, matrixData.byteLength, gl.DYNAMIC_DRAW);
  30308. // each row of the matrix needs to be a separate attribute
  30309. for (var _i = 0; _i < 3; _i++) {
  30310. var loc = attributeLoc + _i;
  30311. gl.enableVertexAttribArray(loc);
  30312. gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 3 * 12, _i * 12);
  30313. gl.vertexAttribDivisor(loc, 1);
  30314. }
  30315. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30316. buffer.getMatrixView = function (i) {
  30317. return matrixViews[i];
  30318. };
  30319. // TODO this is too slow, use getMatrixView and pass the view directly to the glmatrix library
  30320. buffer.setData = function (matrix, i) {
  30321. matrixViews[i].set(matrix, 0);
  30322. };
  30323. buffer.bufferSubData = function () {
  30324. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30325. gl.bufferSubData(gl.ARRAY_BUFFER, 0, matrixData);
  30326. };
  30327. return buffer;
  30328. }
  30329. /**
  30330. * Creates a Frame Buffer to use for offscreen rendering.
  30331. * @param {WebGLRenderingContext} gl
  30332. */
  30333. function createPickingFrameBuffer(gl) {
  30334. // Create and bind the framebuffer
  30335. var fb = gl.createFramebuffer();
  30336. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  30337. // Create a texture to render to
  30338. var targetTexture = gl.createTexture();
  30339. gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  30340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  30341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  30342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  30343. // attach the texture as the first color attachment
  30344. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);
  30345. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  30346. fb.setFramebufferAttachmentSizes = function (width, height) {
  30347. gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  30348. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  30349. };
  30350. return fb;
  30351. }
  30352. /**
  30353. * Common utilities
  30354. * @module glMatrix
  30355. */
  30356. // Configuration Constants
  30357. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  30358. if (!Math.hypot) Math.hypot = function () {
  30359. var y = 0,
  30360. i = arguments.length;
  30361. while (i--) {
  30362. y += arguments[i] * arguments[i];
  30363. }
  30364. return Math.sqrt(y);
  30365. };
  30366. /**
  30367. * 3x3 Matrix
  30368. * @module mat3
  30369. */
  30370. /**
  30371. * Creates a new identity mat3
  30372. *
  30373. * @returns {mat3} a new 3x3 matrix
  30374. */
  30375. function create() {
  30376. var out = new ARRAY_TYPE(9);
  30377. if (ARRAY_TYPE != Float32Array) {
  30378. out[1] = 0;
  30379. out[2] = 0;
  30380. out[3] = 0;
  30381. out[5] = 0;
  30382. out[6] = 0;
  30383. out[7] = 0;
  30384. }
  30385. out[0] = 1;
  30386. out[4] = 1;
  30387. out[8] = 1;
  30388. return out;
  30389. }
  30390. /**
  30391. * Set a mat3 to the identity matrix
  30392. *
  30393. * @param {mat3} out the receiving matrix
  30394. * @returns {mat3} out
  30395. */
  30396. function identity(out) {
  30397. out[0] = 1;
  30398. out[1] = 0;
  30399. out[2] = 0;
  30400. out[3] = 0;
  30401. out[4] = 1;
  30402. out[5] = 0;
  30403. out[6] = 0;
  30404. out[7] = 0;
  30405. out[8] = 1;
  30406. return out;
  30407. }
  30408. /**
  30409. * Multiplies two mat3's
  30410. *
  30411. * @param {mat3} out the receiving matrix
  30412. * @param {ReadonlyMat3} a the first operand
  30413. * @param {ReadonlyMat3} b the second operand
  30414. * @returns {mat3} out
  30415. */
  30416. function multiply(out, a, b) {
  30417. var a00 = a[0],
  30418. a01 = a[1],
  30419. a02 = a[2];
  30420. var a10 = a[3],
  30421. a11 = a[4],
  30422. a12 = a[5];
  30423. var a20 = a[6],
  30424. a21 = a[7],
  30425. a22 = a[8];
  30426. var b00 = b[0],
  30427. b01 = b[1],
  30428. b02 = b[2];
  30429. var b10 = b[3],
  30430. b11 = b[4],
  30431. b12 = b[5];
  30432. var b20 = b[6],
  30433. b21 = b[7],
  30434. b22 = b[8];
  30435. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  30436. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  30437. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  30438. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  30439. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  30440. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  30441. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  30442. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  30443. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  30444. return out;
  30445. }
  30446. /**
  30447. * Translate a mat3 by the given vector
  30448. *
  30449. * @param {mat3} out the receiving matrix
  30450. * @param {ReadonlyMat3} a the matrix to translate
  30451. * @param {ReadonlyVec2} v vector to translate by
  30452. * @returns {mat3} out
  30453. */
  30454. function translate(out, a, v) {
  30455. var a00 = a[0],
  30456. a01 = a[1],
  30457. a02 = a[2],
  30458. a10 = a[3],
  30459. a11 = a[4],
  30460. a12 = a[5],
  30461. a20 = a[6],
  30462. a21 = a[7],
  30463. a22 = a[8],
  30464. x = v[0],
  30465. y = v[1];
  30466. out[0] = a00;
  30467. out[1] = a01;
  30468. out[2] = a02;
  30469. out[3] = a10;
  30470. out[4] = a11;
  30471. out[5] = a12;
  30472. out[6] = x * a00 + y * a10 + a20;
  30473. out[7] = x * a01 + y * a11 + a21;
  30474. out[8] = x * a02 + y * a12 + a22;
  30475. return out;
  30476. }
  30477. /**
  30478. * Rotates a mat3 by the given angle
  30479. *
  30480. * @param {mat3} out the receiving matrix
  30481. * @param {ReadonlyMat3} a the matrix to rotate
  30482. * @param {Number} rad the angle to rotate the matrix by
  30483. * @returns {mat3} out
  30484. */
  30485. function rotate(out, a, rad) {
  30486. var a00 = a[0],
  30487. a01 = a[1],
  30488. a02 = a[2],
  30489. a10 = a[3],
  30490. a11 = a[4],
  30491. a12 = a[5],
  30492. a20 = a[6],
  30493. a21 = a[7],
  30494. a22 = a[8],
  30495. s = Math.sin(rad),
  30496. c = Math.cos(rad);
  30497. out[0] = c * a00 + s * a10;
  30498. out[1] = c * a01 + s * a11;
  30499. out[2] = c * a02 + s * a12;
  30500. out[3] = c * a10 - s * a00;
  30501. out[4] = c * a11 - s * a01;
  30502. out[5] = c * a12 - s * a02;
  30503. out[6] = a20;
  30504. out[7] = a21;
  30505. out[8] = a22;
  30506. return out;
  30507. }
  30508. /**
  30509. * Scales the mat3 by the dimensions in the given vec2
  30510. *
  30511. * @param {mat3} out the receiving matrix
  30512. * @param {ReadonlyMat3} a the matrix to rotate
  30513. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  30514. * @returns {mat3} out
  30515. **/
  30516. function scale(out, a, v) {
  30517. var x = v[0],
  30518. y = v[1];
  30519. out[0] = x * a[0];
  30520. out[1] = x * a[1];
  30521. out[2] = x * a[2];
  30522. out[3] = y * a[3];
  30523. out[4] = y * a[4];
  30524. out[5] = y * a[5];
  30525. out[6] = a[6];
  30526. out[7] = a[7];
  30527. out[8] = a[8];
  30528. return out;
  30529. }
  30530. /**
  30531. * Generates a 2D projection matrix with the given bounds
  30532. *
  30533. * @param {mat3} out mat3 frustum matrix will be written into
  30534. * @param {number} width Width of your gl context
  30535. * @param {number} height Height of gl context
  30536. * @returns {mat3} out
  30537. */
  30538. function projection(out, width, height) {
  30539. out[0] = 2 / width;
  30540. out[1] = 0;
  30541. out[2] = 0;
  30542. out[3] = 0;
  30543. out[4] = -2 / height;
  30544. out[5] = 0;
  30545. out[6] = -1;
  30546. out[7] = 1;
  30547. out[8] = 1;
  30548. return out;
  30549. }
  30550. // A "texture atlas" is a big canvas, and sections of it are used as textures for nodes/labels.
  30551. /**
  30552. * A single square texture atlas (also known as a "sprite sheet").
  30553. */
  30554. var Atlas = /*#__PURE__*/function () {
  30555. function Atlas(r, texSize, texRows, createTextureCanvas) {
  30556. _classCallCheck(this, Atlas);
  30557. this.debugID = Math.floor(Math.random() * 10000);
  30558. this.r = r;
  30559. this.texSize = texSize;
  30560. this.texRows = texRows;
  30561. this.texHeight = Math.floor(texSize / texRows);
  30562. this.enableWrapping = true; // hardcoded for now, can be made an option
  30563. this.locked = false; // once an atlas is locked it can no longer be drawn to
  30564. this.texture = null; // WebGLTexture object
  30565. this.needsBuffer = true;
  30566. // a "location" is an pointer into the atlas with a 'row' and 'x' fields
  30567. this.freePointer = {
  30568. x: 0,
  30569. row: 0
  30570. };
  30571. // map from the style key to the row/x where the texture starts
  30572. // if the texture wraps then there's a second location
  30573. this.keyToLocation = new Map(); // styleKey -> [ location, location ]
  30574. this.canvas = createTextureCanvas(r, texSize, texSize);
  30575. this.scratch = createTextureCanvas(r, texSize, this.texHeight, 'scratch');
  30576. }
  30577. return _createClass(Atlas, [{
  30578. key: "lock",
  30579. value: function lock() {
  30580. this.locked = true;
  30581. }
  30582. }, {
  30583. key: "getKeys",
  30584. value: function getKeys() {
  30585. return new Set(this.keyToLocation.keys());
  30586. }
  30587. }, {
  30588. key: "getScale",
  30589. value: function getScale(_ref) {
  30590. var w = _ref.w,
  30591. h = _ref.h;
  30592. var texHeight = this.texHeight,
  30593. maxTexWidth = this.texSize;
  30594. // try to fit to the height of a row
  30595. var scale = texHeight / h; // TODO what about pixelRatio?
  30596. var texW = w * scale;
  30597. var texH = h * scale;
  30598. // if the scaled width is too wide then scale to fit max width instead
  30599. if (texW > maxTexWidth) {
  30600. scale = maxTexWidth / w;
  30601. texW = w * scale;
  30602. texH = h * scale;
  30603. }
  30604. return {
  30605. scale: scale,
  30606. texW: texW,
  30607. texH: texH
  30608. };
  30609. }
  30610. }, {
  30611. key: "draw",
  30612. value: function draw(key, bb, doDrawing) {
  30613. var _this = this;
  30614. if (this.locked) throw new Error('can\'t draw, atlas is locked');
  30615. var texSize = this.texSize,
  30616. texRows = this.texRows,
  30617. texHeight = this.texHeight;
  30618. var _this$getScale = this.getScale(bb),
  30619. scale = _this$getScale.scale,
  30620. texW = _this$getScale.texW,
  30621. texH = _this$getScale.texH;
  30622. var drawAt = function drawAt(location, canvas) {
  30623. if (doDrawing && canvas) {
  30624. var context = canvas.context;
  30625. var x = location.x,
  30626. row = location.row;
  30627. var xOffset = x;
  30628. var yOffset = texHeight * row;
  30629. context.save();
  30630. context.translate(xOffset, yOffset);
  30631. context.scale(scale, scale);
  30632. doDrawing(context, bb);
  30633. context.restore();
  30634. }
  30635. };
  30636. var locations = [null, null];
  30637. var drawNormal = function drawNormal() {
  30638. // don't need to wrap, draw directly on the canvas
  30639. drawAt(_this.freePointer, _this.canvas);
  30640. locations[0] = {
  30641. x: _this.freePointer.x,
  30642. y: _this.freePointer.row * texHeight,
  30643. w: texW,
  30644. h: texH
  30645. };
  30646. locations[1] = {
  30647. // create a second location with a width of 0, for convenience
  30648. x: _this.freePointer.x + texW,
  30649. y: _this.freePointer.row * texHeight,
  30650. w: 0,
  30651. h: texH
  30652. };
  30653. // move the pointer to the end of the texture
  30654. _this.freePointer.x += texW;
  30655. if (_this.freePointer.x == texSize) {
  30656. _this.freePointer.x = 0;
  30657. _this.freePointer.row++;
  30658. }
  30659. };
  30660. var drawWrapped = function drawWrapped() {
  30661. var scratch = _this.scratch,
  30662. canvas = _this.canvas;
  30663. // Draw to the scratch canvas
  30664. scratch.clear();
  30665. drawAt({
  30666. x: 0,
  30667. row: 0
  30668. }, scratch);
  30669. var firstTexW = texSize - _this.freePointer.x;
  30670. var secondTexW = texW - firstTexW;
  30671. var h = texHeight;
  30672. {
  30673. // copy first part of scratch to the first texture
  30674. var dx = _this.freePointer.x;
  30675. var dy = _this.freePointer.row * texHeight;
  30676. var w = firstTexW;
  30677. canvas.context.drawImage(scratch, 0, 0, w, h, dx, dy, w, h);
  30678. locations[0] = {
  30679. x: dx,
  30680. y: dy,
  30681. w: w,
  30682. h: texH
  30683. };
  30684. }
  30685. {
  30686. // copy second part of scratch to the second texture
  30687. var sx = firstTexW;
  30688. var _dy = (_this.freePointer.row + 1) * texHeight;
  30689. var _w = secondTexW;
  30690. if (canvas) {
  30691. canvas.context.drawImage(scratch, sx, 0, _w, h, 0, _dy, _w, h);
  30692. }
  30693. locations[1] = {
  30694. x: 0,
  30695. y: _dy,
  30696. w: _w,
  30697. h: texH
  30698. };
  30699. }
  30700. _this.freePointer.x = secondTexW;
  30701. _this.freePointer.row++;
  30702. };
  30703. var moveToStartOfNextRow = function moveToStartOfNextRow() {
  30704. _this.freePointer.x = 0;
  30705. _this.freePointer.row++;
  30706. };
  30707. if (this.freePointer.x + texW <= texSize) {
  30708. // There's enough space in the current row
  30709. drawNormal();
  30710. } else if (this.freePointer.row >= texRows - 1) {
  30711. // Need to move to the next row, but there are no more rows, atlas is full.
  30712. return false;
  30713. } else if (this.freePointer.x === texSize) {
  30714. // happen to be right at end of current row
  30715. moveToStartOfNextRow();
  30716. drawNormal();
  30717. } else if (this.enableWrapping) {
  30718. // draw part of the texture to the end of the curent row, then wrap to the next row
  30719. drawWrapped();
  30720. } else {
  30721. // move to the start of the next row, then draw normally
  30722. moveToStartOfNextRow();
  30723. drawNormal();
  30724. }
  30725. this.keyToLocation.set(key, locations);
  30726. this.needsBuffer = true;
  30727. return locations;
  30728. }
  30729. }, {
  30730. key: "getOffsets",
  30731. value: function getOffsets(key) {
  30732. return this.keyToLocation.get(key);
  30733. }
  30734. }, {
  30735. key: "isEmpty",
  30736. value: function isEmpty() {
  30737. return this.freePointer.x === 0 && this.freePointer.row === 0;
  30738. }
  30739. }, {
  30740. key: "canFit",
  30741. value: function canFit(bb) {
  30742. if (this.locked) return false;
  30743. var texSize = this.texSize,
  30744. texRows = this.texRows;
  30745. var _this$getScale2 = this.getScale(bb),
  30746. texW = _this$getScale2.texW;
  30747. if (this.freePointer.x + texW > texSize) {
  30748. // need to wrap
  30749. return this.freePointer.row < texRows - 1; // return true if there's a row to wrap to
  30750. }
  30751. return true;
  30752. }
  30753. // called on every frame
  30754. }, {
  30755. key: "bufferIfNeeded",
  30756. value: function bufferIfNeeded(gl) {
  30757. if (!this.texture) {
  30758. this.texture = createTexture(gl, this.debugID);
  30759. }
  30760. if (this.needsBuffer) {
  30761. this.texture.buffer(this.canvas);
  30762. this.needsBuffer = false;
  30763. if (this.locked) {
  30764. this.canvas = null;
  30765. this.scratch = null;
  30766. }
  30767. }
  30768. }
  30769. }, {
  30770. key: "dispose",
  30771. value: function dispose() {
  30772. if (this.texture) {
  30773. this.texture.deleteTexture();
  30774. this.texture = null;
  30775. }
  30776. this.canvas = null;
  30777. this.scratch = null;
  30778. this.locked = true;
  30779. }
  30780. }]);
  30781. }();
  30782. /**
  30783. * A collection of texture atlases, all of the same "render type".
  30784. * ('node-body' is an example of a render type.)
  30785. * An AtlasCollection can also be notified when a texture is no longer needed,
  30786. * and it can garbage collect the unused textures.
  30787. */
  30788. var AtlasCollection = /*#__PURE__*/function () {
  30789. function AtlasCollection(r, texSize, texRows, createTextureCanvas) {
  30790. _classCallCheck(this, AtlasCollection);
  30791. this.r = r;
  30792. this.texSize = texSize;
  30793. this.texRows = texRows;
  30794. this.createTextureCanvas = createTextureCanvas;
  30795. this.atlases = [];
  30796. this.styleKeyToAtlas = new Map();
  30797. this.markedKeys = new Set(); // marked for garbage collection
  30798. }
  30799. return _createClass(AtlasCollection, [{
  30800. key: "getKeys",
  30801. value: function getKeys() {
  30802. return new Set(this.styleKeyToAtlas.keys());
  30803. }
  30804. }, {
  30805. key: "_createAtlas",
  30806. value: function _createAtlas() {
  30807. var r = this.r,
  30808. texSize = this.texSize,
  30809. texRows = this.texRows,
  30810. createTextureCanvas = this.createTextureCanvas;
  30811. return new Atlas(r, texSize, texRows, createTextureCanvas);
  30812. }
  30813. }, {
  30814. key: "_getScratchCanvas",
  30815. value: function _getScratchCanvas() {
  30816. if (!this.scratch) {
  30817. var r = this.r,
  30818. texSize = this.texSize,
  30819. texRows = this.texRows,
  30820. createTextureCanvas = this.createTextureCanvas;
  30821. var texHeight = Math.floor(texSize / texRows);
  30822. this.scratch = createTextureCanvas(r, texSize, texHeight, 'scratch');
  30823. }
  30824. return this.scratch;
  30825. }
  30826. }, {
  30827. key: "draw",
  30828. value: function draw(key, bb, doDrawing) {
  30829. var atlas = this.styleKeyToAtlas.get(key);
  30830. if (!atlas) {
  30831. // check for space at the end of the last atlas
  30832. atlas = this.atlases[this.atlases.length - 1];
  30833. if (!atlas || !atlas.canFit(bb)) {
  30834. if (atlas) atlas.lock();
  30835. // create a new atlas
  30836. atlas = this._createAtlas();
  30837. this.atlases.push(atlas);
  30838. }
  30839. atlas.draw(key, bb, doDrawing);
  30840. this.styleKeyToAtlas.set(key, atlas);
  30841. }
  30842. return atlas;
  30843. }
  30844. }, {
  30845. key: "getAtlas",
  30846. value: function getAtlas(key) {
  30847. return this.styleKeyToAtlas.get(key);
  30848. }
  30849. }, {
  30850. key: "hasAtlas",
  30851. value: function hasAtlas(key) {
  30852. return this.styleKeyToAtlas.has(key);
  30853. }
  30854. }, {
  30855. key: "markKeyForGC",
  30856. value: function markKeyForGC(key) {
  30857. this.markedKeys.add(key);
  30858. }
  30859. }, {
  30860. key: "gc",
  30861. value: function gc() {
  30862. var _this2 = this;
  30863. var markedKeys = this.markedKeys;
  30864. if (markedKeys.size === 0) {
  30865. console.log('nothing to garbage collect');
  30866. return;
  30867. }
  30868. var newAtlases = [];
  30869. var newStyleKeyToAtlas = new Map();
  30870. var newAtlas = null;
  30871. var _iterator = _createForOfIteratorHelper(this.atlases),
  30872. _step;
  30873. try {
  30874. var _loop = function _loop() {
  30875. var atlas = _step.value;
  30876. var keys = atlas.getKeys();
  30877. var keysToCollect = intersection(markedKeys, keys);
  30878. if (keysToCollect.size === 0) {
  30879. // this atlas can still be used
  30880. newAtlases.push(atlas);
  30881. keys.forEach(function (k) {
  30882. return newStyleKeyToAtlas.set(k, atlas);
  30883. });
  30884. return 1; // continue
  30885. }
  30886. if (!newAtlas) {
  30887. newAtlas = _this2._createAtlas();
  30888. newAtlases.push(newAtlas);
  30889. }
  30890. var _iterator2 = _createForOfIteratorHelper(keys),
  30891. _step2;
  30892. try {
  30893. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  30894. var key = _step2.value;
  30895. if (!keysToCollect.has(key)) {
  30896. var _atlas$getOffsets = atlas.getOffsets(key),
  30897. _atlas$getOffsets2 = _slicedToArray(_atlas$getOffsets, 2),
  30898. s1 = _atlas$getOffsets2[0],
  30899. s2 = _atlas$getOffsets2[1];
  30900. if (!newAtlas.canFit({
  30901. w: s1.w + s2.w,
  30902. h: s1.h
  30903. })) {
  30904. newAtlas.lock();
  30905. newAtlas = _this2._createAtlas();
  30906. newAtlases.push(newAtlas);
  30907. }
  30908. if (atlas.canvas) {
  30909. // if the texture can't be copied then it will have to be redrawn on the next frame
  30910. _this2._copyTextureToNewAtlas(key, atlas, newAtlas);
  30911. newStyleKeyToAtlas.set(key, newAtlas);
  30912. }
  30913. }
  30914. }
  30915. } catch (err) {
  30916. _iterator2.e(err);
  30917. } finally {
  30918. _iterator2.f();
  30919. }
  30920. atlas.dispose();
  30921. };
  30922. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  30923. if (_loop()) continue;
  30924. }
  30925. } catch (err) {
  30926. _iterator.e(err);
  30927. } finally {
  30928. _iterator.f();
  30929. }
  30930. this.atlases = newAtlases;
  30931. this.styleKeyToAtlas = newStyleKeyToAtlas;
  30932. this.markedKeys = new Set();
  30933. }
  30934. }, {
  30935. key: "_copyTextureToNewAtlas",
  30936. value: function _copyTextureToNewAtlas(key, oldAtlas, newAtlas) {
  30937. var _oldAtlas$getOffsets = oldAtlas.getOffsets(key),
  30938. _oldAtlas$getOffsets2 = _slicedToArray(_oldAtlas$getOffsets, 2),
  30939. s1 = _oldAtlas$getOffsets2[0],
  30940. s2 = _oldAtlas$getOffsets2[1];
  30941. if (s2.w === 0) {
  30942. // the texture does not wrap, draw directly to new atlas
  30943. newAtlas.draw(key, s1, function (context) {
  30944. context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
  30945. });
  30946. } else {
  30947. // the texture wraps, first draw both parts to a scratch canvas
  30948. var scratch = this._getScratchCanvas();
  30949. scratch.clear();
  30950. scratch.context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
  30951. scratch.context.drawImage(oldAtlas.canvas, s2.x, s2.y, s2.w, s2.h, s1.w, 0, s2.w, s2.h);
  30952. // now draw the scratch to the new atlas
  30953. var w = s1.w + s2.w;
  30954. var h = s1.h;
  30955. newAtlas.draw(key, {
  30956. w: w,
  30957. h: h
  30958. }, function (context) {
  30959. context.drawImage(scratch, 0, 0, w, h, 0, 0, w, h // the destination context has already been translated to the correct position
  30960. );
  30961. });
  30962. }
  30963. }
  30964. }, {
  30965. key: "getCounts",
  30966. value: function getCounts() {
  30967. return {
  30968. keyCount: this.styleKeyToAtlas.size,
  30969. atlasCount: new Set(this.styleKeyToAtlas.values()).size
  30970. };
  30971. }
  30972. }]);
  30973. }();
  30974. function intersection(set1, set2) {
  30975. // TODO why no Set.intersection in node 16???
  30976. if (set1.intersection) return set1.intersection(set2);else return new Set(_toConsumableArray(set1).filter(function (x) {
  30977. return set2.has(x);
  30978. }));
  30979. }
  30980. /**
  30981. * Used to manage batches of Atlases for drawing nodes and labels.
  30982. * Supports different types of AtlasCollections for different render types,
  30983. * for example 'node-body' and 'node-label' would be different render types.
  30984. * Render types are kept separate because they will likely need to be garbage collected
  30985. * separately and its not entierly guaranteed that their style keys won't collide.
  30986. */
  30987. var AtlasManager = /*#__PURE__*/function () {
  30988. function AtlasManager(r, globalOptions) {
  30989. _classCallCheck(this, AtlasManager);
  30990. this.r = r;
  30991. this.globalOptions = globalOptions;
  30992. this.atlasSize = globalOptions.webglTexSize;
  30993. this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
  30994. this.renderTypes = new Map(); // renderType:string -> renderTypeOptions
  30995. this.collections = new Map(); // collectionName:string -> AtlasCollection
  30996. this.typeAndIdToKey = new Map(); // [renderType,id] => Array<style key>
  30997. }
  30998. return _createClass(AtlasManager, [{
  30999. key: "getAtlasSize",
  31000. value: function getAtlasSize() {
  31001. return this.atlasSize;
  31002. }
  31003. }, {
  31004. key: "addAtlasCollection",
  31005. value: function addAtlasCollection(collectionName, atlasCollectionOptions) {
  31006. var _this$globalOptions = this.globalOptions,
  31007. webglTexSize = _this$globalOptions.webglTexSize,
  31008. createTextureCanvas = _this$globalOptions.createTextureCanvas;
  31009. var texRows = atlasCollectionOptions.texRows;
  31010. var cachedCreateTextureCanvas = this._cacheScratchCanvas(createTextureCanvas);
  31011. var atlasCollection = new AtlasCollection(this.r, webglTexSize, texRows, cachedCreateTextureCanvas);
  31012. this.collections.set(collectionName, atlasCollection);
  31013. }
  31014. }, {
  31015. key: "addRenderType",
  31016. value: function addRenderType(type, renderTypeOptions) {
  31017. var collection = renderTypeOptions.collection;
  31018. if (!this.collections.has(collection)) throw new Error("invalid atlas collection name '".concat(collection, "'"));
  31019. var atlasCollection = this.collections.get(collection);
  31020. var opts = extend({
  31021. type: type,
  31022. atlasCollection: atlasCollection
  31023. }, renderTypeOptions);
  31024. this.renderTypes.set(type, opts);
  31025. }
  31026. }, {
  31027. key: "getRenderTypeOpts",
  31028. value: function getRenderTypeOpts(type) {
  31029. return this.renderTypes.get(type);
  31030. }
  31031. }, {
  31032. key: "getAtlasCollection",
  31033. value: function getAtlasCollection(name) {
  31034. return this.collections.get(name);
  31035. }
  31036. }, {
  31037. key: "_cacheScratchCanvas",
  31038. value: function _cacheScratchCanvas(createTextureCanvas) {
  31039. // all scratch canvases for the same render type will have the same width and height (ie webglTexRows option)
  31040. // but we'll keep track of the width and height just to be safe
  31041. var prevW = -1;
  31042. var prevH = -1;
  31043. var scratchCanvas = null;
  31044. return function (r, w, h, scratch) {
  31045. if (scratch) {
  31046. if (!scratchCanvas || w != prevW || h != prevH) {
  31047. prevW = w;
  31048. prevH = h;
  31049. scratchCanvas = createTextureCanvas(r, w, h);
  31050. }
  31051. return scratchCanvas;
  31052. } else {
  31053. return createTextureCanvas(r, w, h);
  31054. }
  31055. };
  31056. }
  31057. }, {
  31058. key: "_key",
  31059. value: function _key(renderType, id) {
  31060. return "".concat(renderType, "-").concat(id); // TODO not very efficient
  31061. }
  31062. /** Marks textues associated with the element for garbage collection. */
  31063. }, {
  31064. key: "invalidate",
  31065. value: function invalidate(eles) {
  31066. var _this3 = this;
  31067. var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  31068. _ref2$forceRedraw = _ref2.forceRedraw,
  31069. forceRedraw = _ref2$forceRedraw === undefined ? false : _ref2$forceRedraw,
  31070. _ref2$filterEle = _ref2.filterEle,
  31071. filterEle = _ref2$filterEle === undefined ? function () {
  31072. return true;
  31073. } : _ref2$filterEle,
  31074. _ref2$filterType = _ref2.filterType,
  31075. filterType = _ref2$filterType === undefined ? function () {
  31076. return true;
  31077. } : _ref2$filterType;
  31078. var needGC = false;
  31079. var runGCNow = false;
  31080. var _iterator3 = _createForOfIteratorHelper(eles),
  31081. _step3;
  31082. try {
  31083. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  31084. var ele = _step3.value;
  31085. if (filterEle(ele)) {
  31086. var _iterator4 = _createForOfIteratorHelper(this.renderTypes.values()),
  31087. _step4;
  31088. try {
  31089. var _loop2 = function _loop2() {
  31090. var opts = _step4.value;
  31091. var renderType = opts.type;
  31092. if (filterType(renderType)) {
  31093. var atlasCollection = _this3.collections.get(opts.collection);
  31094. var key = opts.getKey(ele);
  31095. var keyArray = Array.isArray(key) ? key : [key];
  31096. // when a node's background image finishes loading, the style key doesn't change but still needs to be redrawn
  31097. if (forceRedraw) {
  31098. keyArray.forEach(function (key) {
  31099. return atlasCollection.markKeyForGC(key);
  31100. });
  31101. runGCNow = true; // run GC to remove the old texture right now, that way we don't need to remember for the next gc
  31102. } else {
  31103. var id = opts.getID ? opts.getID(ele) : ele.id();
  31104. var mapKey = _this3._key(renderType, id);
  31105. var oldKeyArray = _this3.typeAndIdToKey.get(mapKey);
  31106. if (oldKeyArray !== undefined && !arrayEqual(keyArray, oldKeyArray)) {
  31107. // conservative approach, if any of the keys don't match then throw them all away
  31108. needGC = true;
  31109. _this3.typeAndIdToKey["delete"](mapKey);
  31110. oldKeyArray.forEach(function (oldKey) {
  31111. return atlasCollection.markKeyForGC(oldKey);
  31112. });
  31113. }
  31114. }
  31115. }
  31116. };
  31117. for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
  31118. _loop2();
  31119. }
  31120. } catch (err) {
  31121. _iterator4.e(err);
  31122. } finally {
  31123. _iterator4.f();
  31124. }
  31125. }
  31126. }
  31127. } catch (err) {
  31128. _iterator3.e(err);
  31129. } finally {
  31130. _iterator3.f();
  31131. }
  31132. if (runGCNow) {
  31133. this.gc();
  31134. needGC = false;
  31135. }
  31136. return needGC;
  31137. }
  31138. /** Garbage collect */
  31139. }, {
  31140. key: "gc",
  31141. value: function gc() {
  31142. var _iterator5 = _createForOfIteratorHelper(this.collections.values()),
  31143. _step5;
  31144. try {
  31145. for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
  31146. var collection = _step5.value;
  31147. collection.gc();
  31148. }
  31149. } catch (err) {
  31150. _iterator5.e(err);
  31151. } finally {
  31152. _iterator5.f();
  31153. }
  31154. }
  31155. }, {
  31156. key: "getOrCreateAtlas",
  31157. value: function getOrCreateAtlas(ele, type, bb, styleKey) {
  31158. // styleKey is not an array here
  31159. var opts = this.renderTypes.get(type);
  31160. var atlasCollection = this.collections.get(opts.collection);
  31161. // draws the texture only if needed
  31162. var drawn = false;
  31163. var atlas = atlasCollection.draw(styleKey, bb, function (context) {
  31164. if (opts.drawClipped) {
  31165. context.save();
  31166. context.beginPath();
  31167. context.rect(0, 0, bb.w, bb.h);
  31168. context.clip();
  31169. opts.drawElement(context, ele, bb, true, true);
  31170. context.restore();
  31171. } else {
  31172. opts.drawElement(context, ele, bb, true, true);
  31173. }
  31174. drawn = true;
  31175. });
  31176. if (drawn) {
  31177. var id = opts.getID ? opts.getID(ele) : ele.id(); // for testing
  31178. var mapKey = this._key(type, id);
  31179. if (this.typeAndIdToKey.has(mapKey)) {
  31180. this.typeAndIdToKey.get(mapKey).push(styleKey);
  31181. } else {
  31182. this.typeAndIdToKey.set(mapKey, [styleKey]);
  31183. }
  31184. }
  31185. return atlas;
  31186. }
  31187. }, {
  31188. key: "getAtlasInfo",
  31189. value: function getAtlasInfo(ele, type) {
  31190. var _this4 = this;
  31191. var opts = this.renderTypes.get(type);
  31192. var key = opts.getKey(ele);
  31193. var keyArray = Array.isArray(key) ? key : [key];
  31194. return keyArray.map(function (styleKey) {
  31195. var bb = opts.getBoundingBox(ele, styleKey); // pass the key back to the getBoundingBox method
  31196. var atlas = _this4.getOrCreateAtlas(ele, type, bb, styleKey);
  31197. var _atlas$getOffsets3 = atlas.getOffsets(styleKey),
  31198. _atlas$getOffsets4 = _slicedToArray(_atlas$getOffsets3, 2),
  31199. tex1 = _atlas$getOffsets4[0],
  31200. tex2 = _atlas$getOffsets4[1];
  31201. return {
  31202. atlas: atlas,
  31203. tex: tex1,
  31204. tex1: tex1,
  31205. tex2: tex2,
  31206. bb: bb
  31207. };
  31208. });
  31209. }
  31210. }, {
  31211. key: "getDebugInfo",
  31212. value: function getDebugInfo() {
  31213. var debugInfo = [];
  31214. var _iterator6 = _createForOfIteratorHelper(this.collections),
  31215. _step6;
  31216. try {
  31217. for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
  31218. var _step6$value = _slicedToArray(_step6.value, 2),
  31219. name = _step6$value[0],
  31220. collection = _step6$value[1];
  31221. var _collection$getCounts = collection.getCounts(),
  31222. keyCount = _collection$getCounts.keyCount,
  31223. atlasCount = _collection$getCounts.atlasCount;
  31224. debugInfo.push({
  31225. type: name,
  31226. keyCount: keyCount,
  31227. atlasCount: atlasCount
  31228. });
  31229. }
  31230. } catch (err) {
  31231. _iterator6.e(err);
  31232. } finally {
  31233. _iterator6.f();
  31234. }
  31235. return debugInfo;
  31236. }
  31237. }]);
  31238. }();
  31239. var AtlasBatchManager = /*#__PURE__*/function () {
  31240. function AtlasBatchManager(globalOptions) {
  31241. _classCallCheck(this, AtlasBatchManager);
  31242. this.globalOptions = globalOptions;
  31243. this.atlasSize = globalOptions.webglTexSize;
  31244. this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
  31245. this.batchAtlases = [];
  31246. }
  31247. return _createClass(AtlasBatchManager, [{
  31248. key: "getMaxAtlasesPerBatch",
  31249. value: function getMaxAtlasesPerBatch() {
  31250. return this.maxAtlasesPerBatch;
  31251. }
  31252. }, {
  31253. key: "getAtlasSize",
  31254. value: function getAtlasSize() {
  31255. return this.atlasSize;
  31256. }
  31257. }, {
  31258. key: "getIndexArray",
  31259. value: function getIndexArray() {
  31260. return Array.from({
  31261. length: this.maxAtlasesPerBatch
  31262. }, function (v, i) {
  31263. return i;
  31264. });
  31265. }
  31266. }, {
  31267. key: "startBatch",
  31268. value: function startBatch() {
  31269. this.batchAtlases = [];
  31270. }
  31271. }, {
  31272. key: "getAtlasCount",
  31273. value: function getAtlasCount() {
  31274. return this.batchAtlases.length;
  31275. }
  31276. }, {
  31277. key: "getAtlases",
  31278. value: function getAtlases() {
  31279. return this.batchAtlases;
  31280. }
  31281. }, {
  31282. key: "canAddToCurrentBatch",
  31283. value: function canAddToCurrentBatch(atlas) {
  31284. if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
  31285. return this.batchAtlases.includes(atlas);
  31286. }
  31287. return true; // not full
  31288. }
  31289. }, {
  31290. key: "getAtlasIndexForBatch",
  31291. value: function getAtlasIndexForBatch(atlas) {
  31292. var atlasID = this.batchAtlases.indexOf(atlas);
  31293. if (atlasID < 0) {
  31294. if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
  31295. throw new Error('cannot add more atlases to batch');
  31296. }
  31297. this.batchAtlases.push(atlas);
  31298. atlasID = this.batchAtlases.length - 1;
  31299. }
  31300. return atlasID;
  31301. }
  31302. }]);
  31303. }();
  31304. // Fragment shader functions to calculate signed distance
  31305. // https://iquilezles.org/articles/distfunctions2d/
  31306. // ellipse: https://www.shadertoy.com/view/4lsXDN
  31307. /**
  31308. * param p - point
  31309. * float r - circle radius, eg 0.5 for unit circle
  31310. */
  31311. var circleSD = "\n float circleSD(vec2 p, float r) {\n return distance(vec2(0), p) - r; // signed distance\n }\n";
  31312. /**
  31313. * param p - point
  31314. * param b - b.x = half width, b.y = half height
  31315. */
  31316. 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";
  31317. /**
  31318. * param p - point
  31319. * param b - b.x = half width, b.y = half height
  31320. * param cr - vector of corner radiuses
  31321. */
  31322. 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";
  31323. /**
  31324. * param p - point
  31325. * param ab - a.x = horizontal radius, a.y = vertical radius
  31326. */
  31327. 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";
  31328. /**
  31329. * Two render modes. Each mode has its own shader program. They are almost identical, the main difference is the output.
  31330. * SCREEN: output pixel colors to the screen
  31331. * PICKING: output z-order index to an offscreen framebuffer, used to detect what's under the mouse cursor
  31332. */
  31333. var RENDER_TARGET = {
  31334. SCREEN: {
  31335. name: 'screen',
  31336. screen: true
  31337. },
  31338. PICKING: {
  31339. name: 'picking',
  31340. picking: true
  31341. }
  31342. };
  31343. /**
  31344. * Special handing for label textures in PICKING mode. See issue #3337.
  31345. */
  31346. var TEX_PICKING_MODE = {
  31347. // render the texture just like in RENDER_TARGET.SCREEN mode
  31348. IGNORE: 1,
  31349. // don't render the texture at all
  31350. USE_BB: 2 // render the bounding box as an opaque rectangle
  31351. };
  31352. // Vertex types.
  31353. // Used directly in the shaders so must be numeric.
  31354. // There is only one shader program used for an entire frame that renders all types of elements.
  31355. // There are if-else blocks in the shaders that do different things depending on the vertex type.
  31356. // This allows all elements to be rendererd in large batches without switching shader programs.
  31357. var TEXTURE = 0;
  31358. var EDGE_STRAIGHT = 1;
  31359. var EDGE_CURVE_SEGMENT = 2;
  31360. var EDGE_ARROW = 3;
  31361. var RECTANGLE = 4;
  31362. var ROUND_RECTANGLE = 5;
  31363. var BOTTOM_ROUND_RECTANGLE = 6;
  31364. var ELLIPSE = 7;
  31365. var ElementDrawingWebGL = /*#__PURE__*/function () {
  31366. /**
  31367. * @param {WebGLRenderingContext} gl
  31368. */
  31369. function ElementDrawingWebGL(r, gl, opts) {
  31370. _classCallCheck(this, ElementDrawingWebGL);
  31371. this.r = r; // reference to the canvas renderer
  31372. this.gl = gl;
  31373. this.maxInstances = opts.webglBatchSize;
  31374. this.atlasSize = opts.webglTexSize;
  31375. this.bgColor = opts.bgColor;
  31376. this.debug = opts.webglDebug;
  31377. this.batchDebugInfo = [];
  31378. opts.enableWrapping = true;
  31379. opts.createTextureCanvas = createTextureCanvas; // Unit tests mock this
  31380. this.atlasManager = new AtlasManager(r, opts);
  31381. this.batchManager = new AtlasBatchManager(opts);
  31382. this.simpleShapeOptions = new Map();
  31383. this.program = this._createShaderProgram(RENDER_TARGET.SCREEN);
  31384. this.pickingProgram = this._createShaderProgram(RENDER_TARGET.PICKING);
  31385. this.vao = this._createVAO();
  31386. }
  31387. /**
  31388. * @param { string } collectionName
  31389. * @param {{ texRows: number }} opts
  31390. */
  31391. return _createClass(ElementDrawingWebGL, [{
  31392. key: "addAtlasCollection",
  31393. value: function addAtlasCollection(collectionName, opts) {
  31394. this.atlasManager.addAtlasCollection(collectionName, opts);
  31395. }
  31396. /**
  31397. * @typedef { Object } TextureRenderTypeOpts
  31398. * @property { string } collection - name of atlas collection to render textures to
  31399. * @property { function } getKey - returns the "style key" for an element, may be a single value or an array for multi-line lables
  31400. * @property { function } drawElement - uses a canvas renderer to draw the element to the texture atlas
  31401. * @property { boolean } drawClipped - if true the context will be clipped to the bounding box before drawElement() is called, may affect performance
  31402. * @property { function } getBoundingBox - returns the bounding box for an element
  31403. * @property { function } getRotation
  31404. * @property { function } getRotationPoint
  31405. * @property { function } getRotationOffset
  31406. * @property { function } isVisible - an extra check for visibility in addition to ele.visible()
  31407. * @property { function } getTexPickingMode - returns a value from the TEX_PICKING_MODE enum
  31408. */
  31409. /**
  31410. * @param { string } typeName
  31411. * @param { TextureRenderTypeOpts } opts
  31412. */
  31413. }, {
  31414. key: "addTextureAtlasRenderType",
  31415. value: function addTextureAtlasRenderType(typeName, opts) {
  31416. this.atlasManager.addRenderType(typeName, opts);
  31417. }
  31418. /**
  31419. * @typedef { Object } SimpleShapeRenderTypeOpts
  31420. * @property { function } getBoundingBox - returns the bounding box for an element
  31421. * @property { function } isVisible - this is an extra check for visibility in addition to ele.visible()
  31422. * @property { function } isSimple - check if element is a simple shape, or if it needs to fall back to texture rendering
  31423. * @property { ShapeVisualProperties } shapeProps
  31424. */
  31425. /**
  31426. * @typedef { Object } ShapeVisualProperties
  31427. * @property { string } shape
  31428. * @property { string } color
  31429. * @property { string } opacity
  31430. * @property { string } padding
  31431. * @property { string } radius
  31432. * @property { boolean } border
  31433. */
  31434. /**
  31435. * @param { string } typeName
  31436. * @param { SimpleShapeRenderTypeOpts } opts
  31437. */
  31438. }, {
  31439. key: "addSimpleShapeRenderType",
  31440. value: function addSimpleShapeRenderType(typeName, opts) {
  31441. this.simpleShapeOptions.set(typeName, opts);
  31442. }
  31443. /**
  31444. * Inform the atlasManager when element style keys may have changed.
  31445. * The atlasManager can then mark unused textures for "garbage collection".
  31446. */
  31447. }, {
  31448. key: "invalidate",
  31449. value: function invalidate(eles) {
  31450. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  31451. type = _ref.type;
  31452. var atlasManager = this.atlasManager;
  31453. if (type) {
  31454. return atlasManager.invalidate(eles, {
  31455. filterType: function filterType(t) {
  31456. return t === type;
  31457. },
  31458. forceRedraw: true
  31459. });
  31460. } else {
  31461. return atlasManager.invalidate(eles);
  31462. }
  31463. }
  31464. /**
  31465. * Run texture garbage collection.
  31466. */
  31467. }, {
  31468. key: "gc",
  31469. value: function gc() {
  31470. this.atlasManager.gc();
  31471. }
  31472. }, {
  31473. key: "_createShaderProgram",
  31474. value: function _createShaderProgram(renderTarget) {
  31475. var gl = this.gl;
  31476. 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 ");
  31477. var idxs = this.batchManager.getIndexArray();
  31478. 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) {
  31479. return "uniform sampler2D uTexture".concat(i, ";");
  31480. }).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) {
  31481. return "if(vAtlasId == ".concat(i, ") outColor = texture(uTexture").concat(i, ", vTexCoord);");
  31482. }).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 ");
  31483. var program = createProgram(gl, vertexShaderSource, fragmentShaderSource);
  31484. // instance geometry
  31485. program.aPosition = gl.getAttribLocation(program, 'aPosition');
  31486. // attributes
  31487. program.aIndex = gl.getAttribLocation(program, 'aIndex');
  31488. program.aVertType = gl.getAttribLocation(program, 'aVertType');
  31489. program.aTransform = gl.getAttribLocation(program, 'aTransform');
  31490. program.aAtlasId = gl.getAttribLocation(program, 'aAtlasId');
  31491. program.aTex = gl.getAttribLocation(program, 'aTex');
  31492. program.aPointAPointB = gl.getAttribLocation(program, 'aPointAPointB');
  31493. program.aPointCPointD = gl.getAttribLocation(program, 'aPointCPointD');
  31494. program.aLineWidth = gl.getAttribLocation(program, 'aLineWidth');
  31495. program.aColor = gl.getAttribLocation(program, 'aColor');
  31496. program.aCornerRadius = gl.getAttribLocation(program, 'aCornerRadius');
  31497. program.aBorderColor = gl.getAttribLocation(program, 'aBorderColor');
  31498. // uniforms
  31499. program.uPanZoomMatrix = gl.getUniformLocation(program, 'uPanZoomMatrix');
  31500. program.uAtlasSize = gl.getUniformLocation(program, 'uAtlasSize');
  31501. program.uBGColor = gl.getUniformLocation(program, 'uBGColor');
  31502. program.uZoom = gl.getUniformLocation(program, 'uZoom');
  31503. program.uTextures = [];
  31504. for (var i = 0; i < this.batchManager.getMaxAtlasesPerBatch(); i++) {
  31505. program.uTextures.push(gl.getUniformLocation(program, "uTexture".concat(i)));
  31506. }
  31507. return program;
  31508. }
  31509. }, {
  31510. key: "_createVAO",
  31511. value: function _createVAO() {
  31512. var unitSquare = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1];
  31513. this.vertexCount = unitSquare.length / 2;
  31514. var n = this.maxInstances;
  31515. var gl = this.gl,
  31516. program = this.program;
  31517. var vao = gl.createVertexArray();
  31518. gl.bindVertexArray(vao);
  31519. createBufferStaticDraw(gl, 'vec2', program.aPosition, unitSquare);
  31520. // Create buffers for all the attributes
  31521. this.transformBuffer = create3x3MatrixBufferDynamicDraw(gl, n, program.aTransform);
  31522. this.indexBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aIndex);
  31523. this.vertTypeBuffer = createBufferDynamicDraw(gl, n, 'int', program.aVertType);
  31524. this.atlasIdBuffer = createBufferDynamicDraw(gl, n, 'int', program.aAtlasId);
  31525. this.texBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aTex);
  31526. this.pointAPointBBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointAPointB);
  31527. this.pointCPointDBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointCPointD);
  31528. this.lineWidthBuffer = createBufferDynamicDraw(gl, n, 'vec2', program.aLineWidth);
  31529. this.colorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aColor);
  31530. this.cornerRadiusBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aCornerRadius);
  31531. this.borderColorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aBorderColor);
  31532. gl.bindVertexArray(null);
  31533. return vao;
  31534. }
  31535. }, {
  31536. key: "buffers",
  31537. get: function get() {
  31538. var _this = this;
  31539. if (!this._buffers) {
  31540. this._buffers = Object.keys(this).filter(function (k) {
  31541. return endsWith(k, 'Buffer');
  31542. }).map(function (k) {
  31543. return _this[k];
  31544. });
  31545. }
  31546. return this._buffers;
  31547. }
  31548. }, {
  31549. key: "startFrame",
  31550. value: function startFrame(panZoomMatrix) {
  31551. var renderTarget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : RENDER_TARGET.SCREEN;
  31552. this.panZoomMatrix = panZoomMatrix;
  31553. this.renderTarget = renderTarget;
  31554. this.batchDebugInfo = [];
  31555. this.wrappedCount = 0;
  31556. this.simpleCount = 0;
  31557. this.startBatch();
  31558. }
  31559. }, {
  31560. key: "startBatch",
  31561. value: function startBatch() {
  31562. this.instanceCount = 0;
  31563. this.batchManager.startBatch();
  31564. }
  31565. }, {
  31566. key: "endFrame",
  31567. value: function endFrame() {
  31568. this.endBatch();
  31569. }
  31570. }, {
  31571. key: "_isVisible",
  31572. value: function _isVisible(ele, opts) {
  31573. if (ele.visible()) {
  31574. if (opts && opts.isVisible) {
  31575. return opts.isVisible(ele);
  31576. }
  31577. return true;
  31578. }
  31579. return false;
  31580. }
  31581. /**
  31582. * Draws a texture using the texture atlas.
  31583. */
  31584. }, {
  31585. key: "drawTexture",
  31586. value: function drawTexture(ele, eleIndex, type) {
  31587. var atlasManager = this.atlasManager,
  31588. batchManager = this.batchManager;
  31589. var opts = atlasManager.getRenderTypeOpts(type);
  31590. if (!this._isVisible(ele, opts)) {
  31591. return;
  31592. }
  31593. // Edges with invalid points could be passed here (labels), causing errors
  31594. // Ref: Random "Script Error" thrown when generating nodes and edges in newest webgl version #3365
  31595. // https://github.com/cytoscape/cytoscape.js/issues/3365
  31596. if (ele.isEdge() && !this._isValidEdge(ele)) {
  31597. return;
  31598. }
  31599. if (this.renderTarget.picking && opts.getTexPickingMode) {
  31600. var mode = opts.getTexPickingMode(ele);
  31601. if (mode === TEX_PICKING_MODE.IGNORE) {
  31602. return;
  31603. } else if (mode == TEX_PICKING_MODE.USE_BB) {
  31604. this.drawPickingRectangle(ele, eleIndex, type);
  31605. return;
  31606. }
  31607. }
  31608. // Get the atlas and the texture coordinates, will draw the texture if it hasn't been drawn yet
  31609. // May be more than one texture if for example the label has multiple lines
  31610. var atlasInfoArray = atlasManager.getAtlasInfo(ele, type);
  31611. var _iterator = _createForOfIteratorHelper(atlasInfoArray),
  31612. _step;
  31613. try {
  31614. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  31615. var atlasInfo = _step.value;
  31616. var atlas = atlasInfo.atlas,
  31617. tex1 = atlasInfo.tex1,
  31618. tex2 = atlasInfo.tex2; // tex2 is used if the label wraps and there are two textures
  31619. if (!batchManager.canAddToCurrentBatch(atlas)) {
  31620. this.endBatch();
  31621. }
  31622. var atlasIndex = batchManager.getAtlasIndexForBatch(atlas);
  31623. for (var _i = 0, _arr = [[tex1, true], [tex2, false]]; _i < _arr.length; _i++) {
  31624. var _arr$_i = _slicedToArray(_arr[_i], 2),
  31625. tex = _arr$_i[0],
  31626. first = _arr$_i[1];
  31627. if (tex.w != 0) {
  31628. var instance = this.instanceCount;
  31629. this.vertTypeBuffer.getView(instance)[0] = TEXTURE;
  31630. var indexView = this.indexBuffer.getView(instance);
  31631. indexToVec4(eleIndex, indexView);
  31632. // Set values in the buffers using Typed Array Views for performance.
  31633. var atlasIdView = this.atlasIdBuffer.getView(instance);
  31634. atlasIdView[0] = atlasIndex;
  31635. // we have two sets of texture coordinates and transforms because textures can wrap in the atlas
  31636. var texView = this.texBuffer.getView(instance);
  31637. texView[0] = tex.x;
  31638. texView[1] = tex.y;
  31639. texView[2] = tex.w;
  31640. texView[3] = tex.h;
  31641. var matrixView = this.transformBuffer.getMatrixView(instance);
  31642. this.setTransformMatrix(ele, matrixView, opts, atlasInfo, first);
  31643. this.instanceCount++;
  31644. if (!first) this.wrappedCount++;
  31645. if (this.instanceCount >= this.maxInstances) {
  31646. this.endBatch();
  31647. }
  31648. }
  31649. }
  31650. }
  31651. } catch (err) {
  31652. _iterator.e(err);
  31653. } finally {
  31654. _iterator.f();
  31655. }
  31656. }
  31657. /**
  31658. * matrix is expected to be a 9 element array
  31659. * this function follows same pattern as CRp.drawCachedElementPortion(...)
  31660. */
  31661. }, {
  31662. key: "setTransformMatrix",
  31663. value: function setTransformMatrix(ele, matrix, opts, atlasInfo) {
  31664. var first = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  31665. var padding = 0;
  31666. if (opts.shapeProps && opts.shapeProps.padding) {
  31667. padding = ele.pstyle(opts.shapeProps.padding).pfValue;
  31668. }
  31669. if (atlasInfo) {
  31670. // we've already computed the bb and tex bounds for a texture
  31671. var bb = atlasInfo.bb,
  31672. tex1 = atlasInfo.tex1,
  31673. tex2 = atlasInfo.tex2;
  31674. // wrapped textures need separate matrix for each part
  31675. var ratio = tex1.w / (tex1.w + tex2.w);
  31676. if (!first) {
  31677. // first = true means its the first part of the wrapped texture
  31678. ratio = 1 - ratio;
  31679. }
  31680. var adjBB = this._getAdjustedBB(bb, padding, first, ratio);
  31681. this._applyTransformMatrix(matrix, adjBB, opts, ele);
  31682. } else {
  31683. // we don't have a texture, or we want to avoid creating a texture for simple shapes
  31684. var _bb = opts.getBoundingBox(ele);
  31685. var _adjBB = this._getAdjustedBB(_bb, padding, true, 1);
  31686. this._applyTransformMatrix(matrix, _adjBB, opts, ele);
  31687. }
  31688. }
  31689. }, {
  31690. key: "_applyTransformMatrix",
  31691. value: function _applyTransformMatrix(matrix, adjBB, opts, ele) {
  31692. var x, y;
  31693. identity(matrix);
  31694. var theta = opts.getRotation ? opts.getRotation(ele) : 0;
  31695. if (theta !== 0) {
  31696. var _opts$getRotationPoin = opts.getRotationPoint(ele),
  31697. sx = _opts$getRotationPoin.x,
  31698. sy = _opts$getRotationPoin.y;
  31699. translate(matrix, matrix, [sx, sy]);
  31700. rotate(matrix, matrix, theta);
  31701. var offset = opts.getRotationOffset(ele);
  31702. x = offset.x + (adjBB.xOffset || 0);
  31703. y = offset.y + (adjBB.yOffset || 0);
  31704. } else {
  31705. x = adjBB.x1;
  31706. y = adjBB.y1;
  31707. }
  31708. translate(matrix, matrix, [x, y]);
  31709. scale(matrix, matrix, [adjBB.w, adjBB.h]);
  31710. }
  31711. /**
  31712. * Adjusts a node or label BB to accomodate padding and split for wrapped textures.
  31713. * @param bb - the original bounding box
  31714. * @param padding - the padding to add to the bounding box
  31715. * @param first - whether this is the first part of a wrapped texture
  31716. * @param ratio - the ratio of the texture width of part of the text to the entire texture
  31717. */
  31718. }, {
  31719. key: "_getAdjustedBB",
  31720. value: function _getAdjustedBB(bb, padding, first, ratio) {
  31721. var x1 = bb.x1,
  31722. y1 = bb.y1,
  31723. w = bb.w,
  31724. h = bb.h,
  31725. yOffset = bb.yOffset;
  31726. if (padding) {
  31727. x1 -= padding;
  31728. y1 -= padding;
  31729. w += 2 * padding;
  31730. h += 2 * padding;
  31731. }
  31732. var xOffset = 0;
  31733. var adjW = w * ratio;
  31734. if (first && ratio < 1) {
  31735. w = adjW;
  31736. } else if (!first && ratio < 1) {
  31737. xOffset = w - adjW;
  31738. x1 += xOffset;
  31739. w = adjW;
  31740. }
  31741. return {
  31742. x1: x1,
  31743. y1: y1,
  31744. w: w,
  31745. h: h,
  31746. xOffset: xOffset,
  31747. yOffset: yOffset
  31748. };
  31749. }
  31750. /**
  31751. * Draw a solid opaque rectangle matching the element's Bounding Box.
  31752. * Used by the PICKING mode to make the entire BB of a label clickable.
  31753. */
  31754. }, {
  31755. key: "drawPickingRectangle",
  31756. value: function drawPickingRectangle(ele, eleIndex, type) {
  31757. var opts = this.atlasManager.getRenderTypeOpts(type);
  31758. var instance = this.instanceCount;
  31759. this.vertTypeBuffer.getView(instance)[0] = RECTANGLE;
  31760. var indexView = this.indexBuffer.getView(instance);
  31761. indexToVec4(eleIndex, indexView);
  31762. var colorView = this.colorBuffer.getView(instance);
  31763. toWebGLColor([0, 0, 0], 1, colorView); // opaque, so entire label BB is clickable
  31764. var matrixView = this.transformBuffer.getMatrixView(instance);
  31765. this.setTransformMatrix(ele, matrixView, opts);
  31766. this.simpleCount++;
  31767. this.instanceCount++;
  31768. if (this.instanceCount >= this.maxInstances) {
  31769. this.endBatch();
  31770. }
  31771. }
  31772. /**
  31773. * Draw a node using either a texture or a "simple shape".
  31774. */
  31775. }, {
  31776. key: "drawNode",
  31777. value: function drawNode(node, eleIndex, type) {
  31778. var opts = this.simpleShapeOptions.get(type);
  31779. if (!this._isVisible(node, opts)) {
  31780. return;
  31781. }
  31782. var props = opts.shapeProps;
  31783. // Check if we have to use a texture
  31784. var vertType = this._getVertTypeForShape(node, props.shape);
  31785. if (vertType === undefined || opts.isSimple && !opts.isSimple(node, this.renderTarget)) {
  31786. this.drawTexture(node, eleIndex, type);
  31787. return;
  31788. }
  31789. // Render a "simple shape" using SDF (signed distance fields)
  31790. var instance = this.instanceCount;
  31791. this.vertTypeBuffer.getView(instance)[0] = vertType;
  31792. if (vertType === ROUND_RECTANGLE || vertType === BOTTOM_ROUND_RECTANGLE) {
  31793. // get corner radius
  31794. var bb = opts.getBoundingBox(node);
  31795. var radius = this._getCornerRadius(node, props.radius, bb);
  31796. var radiusView = this.cornerRadiusBuffer.getView(instance);
  31797. radiusView[0] = radius; // top-right
  31798. radiusView[1] = radius; // bottom-right
  31799. radiusView[2] = radius; // top-left
  31800. radiusView[3] = radius; // bottom-left
  31801. if (vertType === BOTTOM_ROUND_RECTANGLE) {
  31802. radiusView[0] = 0;
  31803. radiusView[2] = 0;
  31804. }
  31805. }
  31806. var indexView = this.indexBuffer.getView(instance);
  31807. indexToVec4(eleIndex, indexView);
  31808. // Nodes should still be clickable if they pass the visibility check but
  31809. // have background-opacity: 0
  31810. var opacity = this.renderTarget.picking ? 1 : node.pstyle(props.opacity).value;
  31811. var color = node.pstyle(props.color).value;
  31812. var colorView = this.colorBuffer.getView(instance);
  31813. toWebGLColor(color, opacity, colorView);
  31814. var lineWidthView = this.lineWidthBuffer.getView(instance); // reuse edge line width attribute for node border
  31815. lineWidthView[0] = 0;
  31816. lineWidthView[1] = 0;
  31817. if (props.border) {
  31818. var borderWidth = node.pstyle('border-width').value;
  31819. if (borderWidth > 0) {
  31820. var borderColor = node.pstyle('border-color').value;
  31821. var borderOpacity = node.pstyle('border-opacity').value;
  31822. var borderColorView = this.borderColorBuffer.getView(instance);
  31823. toWebGLColor(borderColor, borderOpacity, borderColorView);
  31824. // SDF distance is negative inside the shape and positive outside
  31825. var borderPos = node.pstyle('border-position').value;
  31826. if (borderPos === 'inside') {
  31827. lineWidthView[0] = 0;
  31828. lineWidthView[1] = -borderWidth;
  31829. } else if (borderPos === 'outside') {
  31830. lineWidthView[0] = borderWidth;
  31831. lineWidthView[1] = 0;
  31832. } else {
  31833. // 'center'
  31834. var halfWidth = borderWidth / 2;
  31835. lineWidthView[0] = halfWidth;
  31836. lineWidthView[1] = -halfWidth;
  31837. }
  31838. }
  31839. }
  31840. var matrixView = this.transformBuffer.getMatrixView(instance);
  31841. this.setTransformMatrix(node, matrixView, opts);
  31842. this.simpleCount++;
  31843. this.instanceCount++;
  31844. if (this.instanceCount >= this.maxInstances) {
  31845. this.endBatch();
  31846. }
  31847. }
  31848. }, {
  31849. key: "_getVertTypeForShape",
  31850. value: function _getVertTypeForShape(node, shapeProp) {
  31851. var shape = node.pstyle(shapeProp).value;
  31852. switch (shape) {
  31853. case 'rectangle':
  31854. return RECTANGLE;
  31855. case 'ellipse':
  31856. return ELLIPSE;
  31857. case 'roundrectangle':
  31858. case 'round-rectangle':
  31859. return ROUND_RECTANGLE;
  31860. case 'bottom-round-rectangle':
  31861. return BOTTOM_ROUND_RECTANGLE;
  31862. default:
  31863. return undefined;
  31864. }
  31865. }
  31866. }, {
  31867. key: "_getCornerRadius",
  31868. value: function _getCornerRadius(node, radiusProp, _ref2) {
  31869. var w = _ref2.w,
  31870. h = _ref2.h;
  31871. // see CRp.drawRoundRectanglePath
  31872. if (node.pstyle(radiusProp).value === 'auto') {
  31873. return getRoundRectangleRadius(w, h);
  31874. } else {
  31875. var radius = node.pstyle(radiusProp).pfValue;
  31876. var halfWidth = w / 2;
  31877. var halfHeight = h / 2;
  31878. return Math.min(radius, halfHeight, halfWidth);
  31879. }
  31880. }
  31881. /**
  31882. * Only supports drawing triangles at the moment.
  31883. */
  31884. }, {
  31885. key: "drawEdgeArrow",
  31886. value: function drawEdgeArrow(edge, eleIndex, prefix) {
  31887. if (!edge.visible()) {
  31888. return;
  31889. }
  31890. // Edge points and arrow angles etc are calculated by the base renderer and cached in the rscratch object.
  31891. var rs = edge._private.rscratch;
  31892. var x, y, angle;
  31893. if (prefix === 'source') {
  31894. x = rs.arrowStartX;
  31895. y = rs.arrowStartY;
  31896. angle = rs.srcArrowAngle;
  31897. } else {
  31898. x = rs.arrowEndX;
  31899. y = rs.arrowEndY;
  31900. angle = rs.tgtArrowAngle;
  31901. }
  31902. // taken from CRp.drawArrowhead
  31903. if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
  31904. return;
  31905. }
  31906. // check shape after the x/y check because pstyle() is a bit slow
  31907. var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  31908. if (arrowShape === 'none') {
  31909. return;
  31910. }
  31911. var color = edge.pstyle(prefix + '-arrow-color').value;
  31912. var baseOpacity = edge.pstyle('opacity').value;
  31913. var lineOpacity = edge.pstyle('line-opacity').value;
  31914. var opacity = baseOpacity * lineOpacity;
  31915. var lineWidth = edge.pstyle('width').pfValue;
  31916. var scale$1 = edge.pstyle('arrow-scale').value;
  31917. var size = this.r.getArrowWidth(lineWidth, scale$1);
  31918. var instance = this.instanceCount;
  31919. var transform = this.transformBuffer.getMatrixView(instance);
  31920. identity(transform);
  31921. translate(transform, transform, [x, y]);
  31922. scale(transform, transform, [size, size]);
  31923. rotate(transform, transform, angle);
  31924. this.vertTypeBuffer.getView(instance)[0] = EDGE_ARROW;
  31925. var indexView = this.indexBuffer.getView(instance);
  31926. indexToVec4(eleIndex, indexView);
  31927. var colorView = this.colorBuffer.getView(instance);
  31928. toWebGLColor(color, opacity, colorView);
  31929. this.instanceCount++;
  31930. if (this.instanceCount >= this.maxInstances) {
  31931. this.endBatch();
  31932. }
  31933. }
  31934. /**
  31935. * Draw straight-line or bezier curve edges.
  31936. */
  31937. }, {
  31938. key: "drawEdgeLine",
  31939. value: function drawEdgeLine(edge, eleIndex) {
  31940. if (!edge.visible()) {
  31941. return;
  31942. }
  31943. var points = this._getEdgePoints(edge);
  31944. if (!points) {
  31945. return;
  31946. }
  31947. // line style
  31948. var baseOpacity = edge.pstyle('opacity').value;
  31949. var lineOpacity = edge.pstyle('line-opacity').value;
  31950. var width = edge.pstyle('width').pfValue;
  31951. var color = edge.pstyle('line-color').value;
  31952. var opacity = baseOpacity * lineOpacity;
  31953. if (points.length / 2 + this.instanceCount > this.maxInstances) {
  31954. this.endBatch();
  31955. }
  31956. if (points.length == 4) {
  31957. // straight line
  31958. var instance = this.instanceCount;
  31959. this.vertTypeBuffer.getView(instance)[0] = EDGE_STRAIGHT;
  31960. var indexView = this.indexBuffer.getView(instance);
  31961. indexToVec4(eleIndex, indexView);
  31962. var colorView = this.colorBuffer.getView(instance);
  31963. toWebGLColor(color, opacity, colorView);
  31964. var lineWidthBuffer = this.lineWidthBuffer.getView(instance);
  31965. lineWidthBuffer[0] = width;
  31966. var sourceTargetView = this.pointAPointBBuffer.getView(instance);
  31967. sourceTargetView[0] = points[0]; // source x
  31968. sourceTargetView[1] = points[1]; // source y
  31969. sourceTargetView[2] = points[2]; // target x
  31970. sourceTargetView[3] = points[3]; // target y
  31971. this.instanceCount++;
  31972. if (this.instanceCount >= this.maxInstances) {
  31973. this.endBatch();
  31974. }
  31975. } else {
  31976. // curved line
  31977. for (var i = 0; i < points.length - 2; i += 2) {
  31978. var _instance = this.instanceCount;
  31979. this.vertTypeBuffer.getView(_instance)[0] = EDGE_CURVE_SEGMENT;
  31980. var _indexView = this.indexBuffer.getView(_instance);
  31981. indexToVec4(eleIndex, _indexView);
  31982. var _colorView = this.colorBuffer.getView(_instance);
  31983. toWebGLColor(color, opacity, _colorView);
  31984. var _lineWidthBuffer = this.lineWidthBuffer.getView(_instance);
  31985. _lineWidthBuffer[0] = width;
  31986. var pAx = points[i - 2],
  31987. pAy = points[i - 1];
  31988. var pBx = points[i],
  31989. pBy = points[i + 1];
  31990. var pCx = points[i + 2],
  31991. pCy = points[i + 3];
  31992. var pDx = points[i + 4],
  31993. pDy = points[i + 5];
  31994. // make phantom points for the first and last segments
  31995. // TODO adding 0.001 to avoid division by zero in the shader (I think), need a better solution
  31996. if (i == 0) {
  31997. pAx = 2 * pBx - pCx + 0.001;
  31998. pAy = 2 * pBy - pCy + 0.001;
  31999. }
  32000. if (i == points.length - 4) {
  32001. pDx = 2 * pCx - pBx + 0.001;
  32002. pDy = 2 * pCy - pBy + 0.001;
  32003. }
  32004. var pointABView = this.pointAPointBBuffer.getView(_instance);
  32005. pointABView[0] = pAx;
  32006. pointABView[1] = pAy;
  32007. pointABView[2] = pBx;
  32008. pointABView[3] = pBy;
  32009. var pointCDView = this.pointCPointDBuffer.getView(_instance);
  32010. pointCDView[0] = pCx;
  32011. pointCDView[1] = pCy;
  32012. pointCDView[2] = pDx;
  32013. pointCDView[3] = pDy;
  32014. this.instanceCount++;
  32015. if (this.instanceCount >= this.maxInstances) {
  32016. this.endBatch();
  32017. }
  32018. }
  32019. }
  32020. }
  32021. }, {
  32022. key: "_isValidEdge",
  32023. value: function _isValidEdge(edge) {
  32024. var rs = edge._private.rscratch;
  32025. if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
  32026. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  32027. return false;
  32028. }
  32029. return true;
  32030. }
  32031. }, {
  32032. key: "_getEdgePoints",
  32033. value: function _getEdgePoints(edge) {
  32034. var rs = edge._private.rscratch;
  32035. // if bezier ctrl pts can not be calculated, then die
  32036. if (!this._isValidEdge(edge)) {
  32037. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  32038. return;
  32039. }
  32040. var controlPoints = rs.allpts;
  32041. if (controlPoints.length == 4) {
  32042. return controlPoints;
  32043. }
  32044. var numSegments = this._getNumSegments(edge);
  32045. return this._getCurveSegmentPoints(controlPoints, numSegments);
  32046. }
  32047. }, {
  32048. key: "_getNumSegments",
  32049. value: function _getNumSegments(edge) {
  32050. // TODO Need a heuristic that decides how many segments to use. Factors to consider:
  32051. // - edge width/length
  32052. // - edge curvature (the more the curvature, the more segments)
  32053. // - zoom level (more segments when zoomed in)
  32054. // - number of visible edges (more segments when there are fewer edges)
  32055. // - performance (fewer segments when performance is a concern)
  32056. // - user configurable option(s)
  32057. // note: number of segments must be less than the max number of instances
  32058. // note: segments don't need to be evenly spaced out, it might make sense to have shorter segments nearer to the control points
  32059. var numSegments = 15;
  32060. return Math.min(Math.max(numSegments, 5), this.maxInstances);
  32061. }
  32062. }, {
  32063. key: "_getCurveSegmentPoints",
  32064. value: function _getCurveSegmentPoints(controlPoints, segments) {
  32065. if (controlPoints.length == 4) {
  32066. return controlPoints; // straight line
  32067. }
  32068. var curvePoints = Array((segments + 1) * 2);
  32069. for (var i = 0; i <= segments; i++) {
  32070. // the first and last points are the same as the first and last control points
  32071. if (i == 0) {
  32072. curvePoints[0] = controlPoints[0];
  32073. curvePoints[1] = controlPoints[1];
  32074. } else if (i == segments) {
  32075. curvePoints[i * 2] = controlPoints[controlPoints.length - 2];
  32076. curvePoints[i * 2 + 1] = controlPoints[controlPoints.length - 1];
  32077. } else {
  32078. var t = i / segments; // segments have equal length, its not strictly necessary to do it this way
  32079. // pass in curvePoints to set the values in the array directly
  32080. this._setCurvePoint(controlPoints, t, curvePoints, i * 2);
  32081. }
  32082. }
  32083. return curvePoints;
  32084. }
  32085. }, {
  32086. key: "_setCurvePoint",
  32087. value: function _setCurvePoint(points, t, curvePoints, cpi) {
  32088. if (points.length <= 2) {
  32089. curvePoints[cpi] = points[0];
  32090. curvePoints[cpi + 1] = points[1];
  32091. } else {
  32092. var newpoints = Array(points.length - 2);
  32093. for (var i = 0; i < newpoints.length; i += 2) {
  32094. var x = (1 - t) * points[i] + t * points[i + 2];
  32095. var y = (1 - t) * points[i + 1] + t * points[i + 3];
  32096. newpoints[i] = x;
  32097. newpoints[i + 1] = y;
  32098. }
  32099. return this._setCurvePoint(newpoints, t, curvePoints, cpi);
  32100. }
  32101. }
  32102. }, {
  32103. key: "endBatch",
  32104. value: function endBatch() {
  32105. var gl = this.gl,
  32106. vao = this.vao,
  32107. vertexCount = this.vertexCount,
  32108. count = this.instanceCount;
  32109. if (count === 0) return;
  32110. var program = this.renderTarget.picking ? this.pickingProgram : this.program;
  32111. gl.useProgram(program);
  32112. gl.bindVertexArray(vao);
  32113. // buffer the attribute data
  32114. var _iterator2 = _createForOfIteratorHelper(this.buffers),
  32115. _step2;
  32116. try {
  32117. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  32118. var buffer = _step2.value;
  32119. buffer.bufferSubData(count);
  32120. }
  32121. } catch (err) {
  32122. _iterator2.e(err);
  32123. } finally {
  32124. _iterator2.f();
  32125. }
  32126. var atlases = this.batchManager.getAtlases();
  32127. // must buffer before activating texture units
  32128. for (var i = 0; i < atlases.length; i++) {
  32129. atlases[i].bufferIfNeeded(gl);
  32130. }
  32131. // Activate all the texture units that we need
  32132. for (var _i2 = 0; _i2 < atlases.length; _i2++) {
  32133. gl.activeTexture(gl.TEXTURE0 + _i2);
  32134. gl.bindTexture(gl.TEXTURE_2D, atlases[_i2].texture);
  32135. gl.uniform1i(program.uTextures[_i2], _i2);
  32136. }
  32137. // Set the uniforms
  32138. gl.uniform1f(program.uZoom, getEffectiveZoom(this.r));
  32139. gl.uniformMatrix3fv(program.uPanZoomMatrix, false, this.panZoomMatrix);
  32140. gl.uniform1i(program.uAtlasSize, this.batchManager.getAtlasSize());
  32141. // set background color, needed for edge arrow color blending
  32142. var webglBgColor = toWebGLColor(this.bgColor, 1);
  32143. gl.uniform4fv(program.uBGColor, webglBgColor);
  32144. // draw!
  32145. gl.drawArraysInstanced(gl.TRIANGLES, 0, vertexCount, count);
  32146. gl.bindVertexArray(null);
  32147. gl.bindTexture(gl.TEXTURE_2D, null); // TODO is this right when having multiple texture units?
  32148. if (this.debug) {
  32149. this.batchDebugInfo.push({
  32150. count: count,
  32151. // instance count
  32152. atlasCount: atlases.length
  32153. });
  32154. }
  32155. // start the next batch, even if not needed
  32156. this.startBatch();
  32157. }
  32158. }, {
  32159. key: "getDebugInfo",
  32160. value: function getDebugInfo() {
  32161. var atlasInfo = this.atlasManager.getDebugInfo();
  32162. var totalAtlases = atlasInfo.reduce(function (count, info) {
  32163. return count + info.atlasCount;
  32164. }, 0);
  32165. var batchInfo = this.batchDebugInfo;
  32166. var totalInstances = batchInfo.reduce(function (count, info) {
  32167. return count + info.count;
  32168. }, 0);
  32169. return {
  32170. atlasInfo: atlasInfo,
  32171. totalAtlases: totalAtlases,
  32172. wrappedCount: this.wrappedCount,
  32173. simpleCount: this.simpleCount,
  32174. batchCount: batchInfo.length,
  32175. batchInfo: batchInfo,
  32176. totalInstances: totalInstances
  32177. };
  32178. }
  32179. }]);
  32180. }();
  32181. var CRp$4 = {};
  32182. /**
  32183. * Initialize the WebGL rendering mode after the Canvas renderer has been initialized.
  32184. */
  32185. CRp$4.initWebgl = function (opts, fns) {
  32186. var r = this;
  32187. var gl = r.data.contexts[r.WEBGL];
  32188. // Set defaults and limits for configuration options.
  32189. opts.bgColor = getBGColor(r);
  32190. opts.webglTexSize = Math.min(opts.webglTexSize, gl.getParameter(gl.MAX_TEXTURE_SIZE));
  32191. opts.webglTexRows = Math.min(opts.webglTexRows, 54);
  32192. opts.webglTexRowsNodes = Math.min(opts.webglTexRowsNodes, 54);
  32193. opts.webglBatchSize = Math.min(opts.webglBatchSize, 16384);
  32194. opts.webglTexPerBatch = Math.min(opts.webglTexPerBatch, gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS));
  32195. // Turn debug mode on or off.
  32196. r.webglDebug = opts.webglDebug;
  32197. r.webglDebugShowAtlases = opts.webglDebugShowAtlases;
  32198. // Create offscreen framebuffer that stores the results when RENDER_TARGET.PICKING is enabled.
  32199. // This is used to store the topmost element z-index for each pixel, which is used to tell whats under the mouse cursor point.
  32200. r.pickingFrameBuffer = createPickingFrameBuffer(gl);
  32201. r.pickingFrameBuffer.needsDraw = true;
  32202. // Create an ElementDrawingWebGL instance wich is used to do the actual WebGL rendering.
  32203. // This instance needs to be configured to draw various types of elements.
  32204. r.drawing = new ElementDrawingWebGL(r, gl, opts);
  32205. // Some functions that are used to configure ElementDrawingWebGL
  32206. var getLabelRotation = function getLabelRotation(prop) {
  32207. return function (ele) {
  32208. return r.getTextAngle(ele, prop);
  32209. };
  32210. };
  32211. var isLabelVisible = function isLabelVisible(prop) {
  32212. return function (ele) {
  32213. var label = ele.pstyle(prop);
  32214. return label && label.value;
  32215. };
  32216. };
  32217. var isLayerVisible = function isLayerVisible(prefix) {
  32218. return function (node) {
  32219. // prefix is 'overlay' or 'underlay'
  32220. return node.pstyle("".concat(prefix, "-opacity")).value > 0;
  32221. };
  32222. };
  32223. var getTexPickingMode = function getTexPickingMode(ele) {
  32224. // tells when a label should be clickable
  32225. var enabled = ele.pstyle('text-events').strValue === 'yes';
  32226. return enabled ? TEX_PICKING_MODE.USE_BB : TEX_PICKING_MODE.IGNORE;
  32227. };
  32228. var getBBForSimpleShape = function getBBForSimpleShape(node) {
  32229. // "simple" shapes need their BB to include border and padding
  32230. var _node$position = node.position(),
  32231. x = _node$position.x,
  32232. y = _node$position.y;
  32233. var w = node.outerWidth(); // includes border and padding
  32234. var h = node.outerHeight();
  32235. return {
  32236. w: w,
  32237. h: h,
  32238. x1: x - w / 2,
  32239. y1: y - h / 2
  32240. };
  32241. };
  32242. // An AtlasCollection is a collection of Atlases that have the same configuraiton options.
  32243. // Create one for node bodies and one for all types of labels.
  32244. r.drawing.addAtlasCollection('node', {
  32245. texRows: opts.webglTexRowsNodes
  32246. });
  32247. r.drawing.addAtlasCollection('label', {
  32248. texRows: opts.webglTexRows
  32249. });
  32250. // Configure the different types of elements that can be rendered.
  32251. // Node bodies can be rendered as textures or as "simple shapes".
  32252. // Simple shapes are preferred because they do not use texture memory.
  32253. // Textures are required if the node body uses complex styles.
  32254. r.drawing.addTextureAtlasRenderType('node-body', {
  32255. collection: 'node',
  32256. getKey: fns.getStyleKey,
  32257. getBoundingBox: fns.getElementBox,
  32258. drawElement: fns.drawElement
  32259. });
  32260. r.drawing.addSimpleShapeRenderType('node-body', {
  32261. getBoundingBox: getBBForSimpleShape,
  32262. isSimple: isSimpleShape,
  32263. shapeProps: {
  32264. shape: 'shape',
  32265. color: 'background-color',
  32266. opacity: 'background-opacity',
  32267. radius: 'corner-radius',
  32268. border: true
  32269. }
  32270. });
  32271. r.drawing.addSimpleShapeRenderType('node-overlay', {
  32272. getBoundingBox: getBBForSimpleShape,
  32273. isVisible: isLayerVisible('overlay'),
  32274. shapeProps: {
  32275. shape: 'overlay-shape',
  32276. color: 'overlay-color',
  32277. opacity: 'overlay-opacity',
  32278. padding: 'overlay-padding',
  32279. radius: 'overlay-corner-radius'
  32280. }
  32281. });
  32282. r.drawing.addSimpleShapeRenderType('node-underlay', {
  32283. getBoundingBox: getBBForSimpleShape,
  32284. isVisible: isLayerVisible('underlay'),
  32285. shapeProps: {
  32286. shape: 'underlay-shape',
  32287. color: 'underlay-color',
  32288. opacity: 'underlay-opacity',
  32289. padding: 'underlay-padding',
  32290. radius: 'underlay-corner-radius'
  32291. }
  32292. });
  32293. r.drawing.addTextureAtlasRenderType('label', {
  32294. // node label or edge mid label
  32295. collection: 'label',
  32296. getTexPickingMode: getTexPickingMode,
  32297. getKey: getStyleKeysForLabel(fns.getLabelKey, null),
  32298. getBoundingBox: getBoundingBoxForLabel(fns.getLabelBox, null),
  32299. drawClipped: true,
  32300. drawElement: fns.drawLabel,
  32301. getRotation: getLabelRotation(null),
  32302. getRotationPoint: fns.getLabelRotationPoint,
  32303. getRotationOffset: fns.getLabelRotationOffset,
  32304. isVisible: isLabelVisible('label')
  32305. });
  32306. r.drawing.addTextureAtlasRenderType('edge-source-label', {
  32307. collection: 'label',
  32308. getTexPickingMode: getTexPickingMode,
  32309. getKey: getStyleKeysForLabel(fns.getSourceLabelKey, 'source'),
  32310. getBoundingBox: getBoundingBoxForLabel(fns.getSourceLabelBox, 'source'),
  32311. drawClipped: true,
  32312. drawElement: fns.drawSourceLabel,
  32313. getRotation: getLabelRotation('source'),
  32314. getRotationPoint: fns.getSourceLabelRotationPoint,
  32315. getRotationOffset: fns.getSourceLabelRotationOffset,
  32316. isVisible: isLabelVisible('source-label')
  32317. });
  32318. r.drawing.addTextureAtlasRenderType('edge-target-label', {
  32319. collection: 'label',
  32320. getTexPickingMode: getTexPickingMode,
  32321. getKey: getStyleKeysForLabel(fns.getTargetLabelKey, 'target'),
  32322. getBoundingBox: getBoundingBoxForLabel(fns.getTargetLabelBox, 'target'),
  32323. drawClipped: true,
  32324. drawElement: fns.drawTargetLabel,
  32325. getRotation: getLabelRotation('target'),
  32326. getRotationPoint: fns.getTargetLabelRotationPoint,
  32327. getRotationOffset: fns.getTargetLabelRotationOffset,
  32328. isVisible: isLabelVisible('target-label')
  32329. });
  32330. // Very simplistic way of triggering garbage collection, just use a timer.
  32331. var setGCFlag = debounce(function () {
  32332. console.log('garbage collect flag set');
  32333. r.data.gc = true;
  32334. }, 10000);
  32335. // Event listener checks if style keys are no longer in use.
  32336. r.onUpdateEleCalcs(function (willDraw, eles) {
  32337. var gcNeeded = false;
  32338. if (eles && eles.length > 0) {
  32339. gcNeeded |= r.drawing.invalidate(eles);
  32340. }
  32341. if (gcNeeded) {
  32342. setGCFlag();
  32343. }
  32344. });
  32345. // "Override" certain functions in canvas and base renderer
  32346. overrideCanvasRendererFunctions(r);
  32347. };
  32348. function getBGColor(r) {
  32349. var container = r.cy.container();
  32350. var cssColor = container && container.style && container.style.backgroundColor || 'white';
  32351. return color2tuple(cssColor);
  32352. }
  32353. function getLabelLines(ele, prefix) {
  32354. var rs = ele._private.rscratch;
  32355. return getPrefixedProperty(rs, 'labelWrapCachedLines', prefix) || [];
  32356. }
  32357. /**
  32358. * Handle multi-line labels by rendering each line as a seperate texture.
  32359. * That means each line needs its own style key.
  32360. */
  32361. var getStyleKeysForLabel = function getStyleKeysForLabel(getKey, prefix) {
  32362. return function (ele) {
  32363. var key = getKey(ele);
  32364. var lines = getLabelLines(ele, prefix);
  32365. if (lines.length > 1) {
  32366. return lines.map(function (line, index) {
  32367. return "".concat(key, "_").concat(index);
  32368. });
  32369. }
  32370. return key;
  32371. };
  32372. };
  32373. /**
  32374. * Need to create a separate bounding box for each line of a multi-line label.
  32375. * Note that 'drawClipped: true' should be used with this.
  32376. */
  32377. var getBoundingBoxForLabel = function getBoundingBoxForLabel(getBoundingBox, prefix) {
  32378. return function (ele, styleKey) {
  32379. var bb = getBoundingBox(ele);
  32380. if (typeof styleKey === 'string') {
  32381. var ui = styleKey.indexOf('_');
  32382. if (ui > 0) {
  32383. var lineIndex = Number(styleKey.substring(ui + 1));
  32384. var lines = getLabelLines(ele, prefix);
  32385. // Adjust the height and Y coordinate for one line of the label.
  32386. var h = bb.h / lines.length;
  32387. var yOffset = h * lineIndex;
  32388. var y1 = bb.y1 + yOffset;
  32389. // the yOffset is needed when rotating the label
  32390. return {
  32391. x1: bb.x1,
  32392. w: bb.w,
  32393. y1: y1,
  32394. h: h,
  32395. yOffset: yOffset
  32396. };
  32397. }
  32398. }
  32399. return bb;
  32400. };
  32401. };
  32402. /**
  32403. * Plug into the canvas renderer by dynamically overriding some of its functions.
  32404. * This requires minimal changes to the canvas rendrerer.
  32405. */
  32406. function overrideCanvasRendererFunctions(r) {
  32407. {
  32408. // Override the render function to call the webgl render function if the zoom level is appropriate
  32409. var renderCanvas = r.render;
  32410. r.render = function (options) {
  32411. options = options || {};
  32412. var cy = r.cy;
  32413. if (r.webgl) {
  32414. // If the zoom level is greater than the max zoom level, then disable webgl and switch back to
  32415. // the canvas renderer.
  32416. if (cy.zoom() > maxZoom$1) {
  32417. clearWebgl(r);
  32418. renderCanvas.call(r, options);
  32419. } else {
  32420. clearCanvas(r);
  32421. renderWebgl(r, options, RENDER_TARGET.SCREEN);
  32422. }
  32423. }
  32424. };
  32425. }
  32426. {
  32427. // Override the matchCanvasSize function to update the picking frame buffer size
  32428. var baseFunc = r.matchCanvasSize;
  32429. r.matchCanvasSize = function (container) {
  32430. baseFunc.call(r, container);
  32431. r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth, r.canvasHeight);
  32432. r.pickingFrameBuffer.needsDraw = true;
  32433. };
  32434. }
  32435. {
  32436. // Override function to call the webgl version for picking.
  32437. // Don't override r.getAllInBox() selction box picking, its not accurate enough with webgl
  32438. r.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  32439. // the canvas version of this function is very slow on large graphs
  32440. return findNearestElementsWebgl(r, x, y);
  32441. };
  32442. }
  32443. {
  32444. // need to know when the cached elements have changed so we can invalidate our caches
  32445. var _baseFunc = r.invalidateCachedZSortedEles;
  32446. r.invalidateCachedZSortedEles = function () {
  32447. _baseFunc.call(r);
  32448. r.pickingFrameBuffer.needsDraw = true;
  32449. };
  32450. }
  32451. {
  32452. // need to know when the cached elements have changed so we can invalidate our caches
  32453. var _baseFunc2 = r.notify;
  32454. r.notify = function (eventName, eles) {
  32455. _baseFunc2.call(r, eventName, eles);
  32456. if (eventName === 'viewport' || eventName === 'bounds') {
  32457. r.pickingFrameBuffer.needsDraw = true;
  32458. } else if (eventName === 'background') {
  32459. // background image finished loading, need to redraw
  32460. r.drawing.invalidate(eles, {
  32461. type: 'node-body'
  32462. });
  32463. }
  32464. };
  32465. }
  32466. }
  32467. function clearWebgl(r) {
  32468. var gl = r.data.contexts[r.WEBGL];
  32469. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  32470. }
  32471. function clearCanvas(r) {
  32472. // the CRp.clearCanvas() function doesn't take the transform into account
  32473. var clear = function clear(context) {
  32474. context.save();
  32475. context.setTransform(1, 0, 0, 1, 0, 0);
  32476. context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  32477. context.restore();
  32478. };
  32479. clear(r.data.contexts[r.NODE]);
  32480. clear(r.data.contexts[r.DRAG]);
  32481. }
  32482. function createPanZoomMatrix(r) {
  32483. var width = r.canvasWidth;
  32484. var height = r.canvasHeight;
  32485. var _util$getEffectivePan = getEffectivePanZoom(r),
  32486. pan = _util$getEffectivePan.pan,
  32487. zoom = _util$getEffectivePan.zoom;
  32488. var transform = create();
  32489. translate(transform, transform, [pan.x, pan.y]);
  32490. scale(transform, transform, [zoom, zoom]);
  32491. var projection$1 = create();
  32492. projection(projection$1, width, height);
  32493. var product = create();
  32494. multiply(product, projection$1, transform);
  32495. return product;
  32496. }
  32497. function setContextTransform(r, context) {
  32498. var width = r.canvasWidth;
  32499. var height = r.canvasHeight;
  32500. var _util$getEffectivePan2 = getEffectivePanZoom(r),
  32501. pan = _util$getEffectivePan2.pan,
  32502. zoom = _util$getEffectivePan2.zoom;
  32503. context.setTransform(1, 0, 0, 1, 0, 0);
  32504. context.clearRect(0, 0, width, height);
  32505. context.translate(pan.x, pan.y);
  32506. context.scale(zoom, zoom);
  32507. }
  32508. function drawSelectionRectangle(r, options) {
  32509. r.drawSelectionRectangle(options, function (context) {
  32510. return setContextTransform(r, context);
  32511. });
  32512. }
  32513. function drawAxes(r) {
  32514. // for debgging
  32515. var context = r.data.contexts[r.NODE];
  32516. context.save();
  32517. setContextTransform(r, context);
  32518. context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
  32519. context.beginPath();
  32520. context.moveTo(-1e3, 0);
  32521. context.lineTo(1000, 0);
  32522. context.stroke();
  32523. context.beginPath();
  32524. context.moveTo(0, -1e3);
  32525. context.lineTo(0, 1000);
  32526. context.stroke();
  32527. context.restore();
  32528. }
  32529. function drawAtlases(r) {
  32530. // For debugging the atlases, this doesn't work for Atlases that are locked
  32531. var draw = function draw(drawing, name, row) {
  32532. var collection = drawing.atlasManager.getAtlasCollection(name);
  32533. var context = r.data.contexts[r.NODE];
  32534. var atlases = collection.atlases;
  32535. for (var _i = 0; _i < atlases.length; _i++) {
  32536. var atlas = atlases[_i];
  32537. var canvas = atlas.canvas;
  32538. if (canvas) {
  32539. var w = canvas.width;
  32540. var h = canvas.height;
  32541. var x = w * _i;
  32542. var y = canvas.height * row;
  32543. var scale = 0.4;
  32544. context.save();
  32545. context.scale(scale, scale);
  32546. context.drawImage(canvas, x, y);
  32547. context.strokeStyle = 'black';
  32548. context.rect(x, y, w, h);
  32549. context.stroke();
  32550. context.restore();
  32551. }
  32552. }
  32553. };
  32554. var i = 0;
  32555. draw(r.drawing, 'node', i++);
  32556. draw(r.drawing, 'label', i++);
  32557. }
  32558. /**
  32559. * Returns the z-order index of elments under or very close to the mouse cursor point.
  32560. * Arguments are in model coordinates.
  32561. * (x1, y1) is top left corner
  32562. * (x2, y2) is bottom right corner (optional)
  32563. * Returns a Set of indexes.
  32564. */
  32565. function getPickingIndexes(r, mX1, mY1, mX2, mY2) {
  32566. var x, y, w, h;
  32567. var _util$getEffectivePan3 = getEffectivePanZoom(r),
  32568. pan = _util$getEffectivePan3.pan,
  32569. zoom = _util$getEffectivePan3.zoom;
  32570. {
  32571. var _util$modelToRendered = modelToRenderedPosition(r, pan, zoom, mX1, mY1),
  32572. _util$modelToRendered2 = _slicedToArray(_util$modelToRendered, 2),
  32573. cX1 = _util$modelToRendered2[0],
  32574. cY1 = _util$modelToRendered2[1];
  32575. var t = 6; // should be even
  32576. x = cX1 - t / 2;
  32577. y = cY1 - t / 2;
  32578. w = t;
  32579. h = t;
  32580. }
  32581. if (w === 0 || h === 0) {
  32582. return [];
  32583. }
  32584. var gl = r.data.contexts[r.WEBGL];
  32585. gl.bindFramebuffer(gl.FRAMEBUFFER, r.pickingFrameBuffer);
  32586. if (r.pickingFrameBuffer.needsDraw) {
  32587. // Draw element z-indexes to the picking framebuffer
  32588. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  32589. renderWebgl(r, null, RENDER_TARGET.PICKING);
  32590. r.pickingFrameBuffer.needsDraw = false;
  32591. }
  32592. var n = w * h; // number of pixels to read
  32593. var data = new Uint8Array(n * 4); // 4 bytes per pixel
  32594. gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, data);
  32595. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  32596. var indexes = new Set();
  32597. for (var i = 0; i < n; i++) {
  32598. var pixel = data.slice(i * 4, i * 4 + 4);
  32599. var index = vec4ToIndex(pixel) - 1; // The framebuffer is cleared with 0s, so z-indexes are offset by 1
  32600. if (index >= 0) {
  32601. indexes.add(index);
  32602. }
  32603. }
  32604. return indexes;
  32605. }
  32606. /**
  32607. * Cy.js: model coordinate y axis goes down
  32608. */
  32609. function findNearestElementsWebgl(r, x, y) {
  32610. // model coordinates
  32611. var indexes = getPickingIndexes(r, x, y);
  32612. var eles = r.getCachedZSortedEles();
  32613. var node, edge;
  32614. var _iterator = _createForOfIteratorHelper(indexes),
  32615. _step;
  32616. try {
  32617. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  32618. var index = _step.value;
  32619. var ele = eles[index];
  32620. if (!node && ele.isNode()) {
  32621. node = ele;
  32622. }
  32623. if (!edge && ele.isEdge()) {
  32624. edge = ele;
  32625. }
  32626. if (node && edge) {
  32627. break;
  32628. }
  32629. }
  32630. } catch (err) {
  32631. _iterator.e(err);
  32632. } finally {
  32633. _iterator.f();
  32634. }
  32635. return [node, edge].filter(Boolean);
  32636. }
  32637. /**
  32638. * Draw one node or edge.
  32639. */
  32640. function drawEle(r, index, ele) {
  32641. var drawing = r.drawing;
  32642. index += 1; // 0 is used to clear the background, need to offset all z-indexes by one
  32643. if (ele.isNode()) {
  32644. drawing.drawNode(ele, index, 'node-underlay');
  32645. drawing.drawNode(ele, index, 'node-body');
  32646. drawing.drawTexture(ele, index, 'label');
  32647. drawing.drawNode(ele, index, 'node-overlay');
  32648. } else {
  32649. drawing.drawEdgeLine(ele, index);
  32650. drawing.drawEdgeArrow(ele, index, 'source');
  32651. drawing.drawEdgeArrow(ele, index, 'target');
  32652. drawing.drawTexture(ele, index, 'label');
  32653. drawing.drawTexture(ele, index, 'edge-source-label');
  32654. drawing.drawTexture(ele, index, 'edge-target-label');
  32655. }
  32656. }
  32657. /**
  32658. * Render one frame.
  32659. */
  32660. function renderWebgl(r, options, renderTarget) {
  32661. var start;
  32662. if (r.webglDebug) {
  32663. start = performance.now(); // eslint-disable-line no-undef
  32664. }
  32665. var drawing = r.drawing;
  32666. var eleCount = 0;
  32667. if (renderTarget.screen) {
  32668. if (r.data.canvasNeedsRedraw[r.SELECT_BOX]) {
  32669. drawSelectionRectangle(r, options);
  32670. }
  32671. }
  32672. // see drawing-elements.js drawCachedElement()
  32673. if (r.data.canvasNeedsRedraw[r.NODE] || renderTarget.picking) {
  32674. var gl = r.data.contexts[r.WEBGL];
  32675. if (renderTarget.screen) {
  32676. gl.clearColor(0, 0, 0, 0); // background color
  32677. gl.enable(gl.BLEND); // enable alpha blending of colors
  32678. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // webgl colors use premultiplied alpha
  32679. } else {
  32680. gl.disable(gl.BLEND); // don't blend z-order index values! they are not colors
  32681. }
  32682. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  32683. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  32684. var panZoomMatrix = createPanZoomMatrix(r);
  32685. var eles = r.getCachedZSortedEles();
  32686. eleCount = eles.length;
  32687. drawing.startFrame(panZoomMatrix, renderTarget);
  32688. if (renderTarget.screen) {
  32689. for (var i = 0; i < eles.nondrag.length; i++) {
  32690. drawEle(r, i, eles.nondrag[i]);
  32691. }
  32692. for (var _i2 = 0; _i2 < eles.drag.length; _i2++) {
  32693. drawEle(r, _i2, eles.drag[_i2]);
  32694. }
  32695. } else if (renderTarget.picking) {
  32696. for (var _i3 = 0; _i3 < eles.length; _i3++) {
  32697. drawEle(r, _i3, eles[_i3]);
  32698. }
  32699. }
  32700. drawing.endFrame();
  32701. if (renderTarget.screen && r.webglDebugShowAtlases) {
  32702. drawAxes(r);
  32703. drawAtlases(r);
  32704. }
  32705. r.data.canvasNeedsRedraw[r.NODE] = false;
  32706. r.data.canvasNeedsRedraw[r.DRAG] = false;
  32707. }
  32708. if (r.webglDebug) {
  32709. // eslint-disable-next-line no-undef
  32710. var end = performance.now();
  32711. var compact = false;
  32712. var time = Math.ceil(end - start);
  32713. var debugInfo = drawing.getDebugInfo();
  32714. 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(', ');
  32715. if (compact) {
  32716. console.log("WebGL (".concat(renderTarget.name, ") - time ").concat(time, "ms, ").concat(report));
  32717. } else {
  32718. console.log("WebGL (".concat(renderTarget.name, ") - frame time ").concat(time, "ms"));
  32719. console.log('Totals:');
  32720. console.log(" ".concat(report));
  32721. console.log('Texture Atlases Used:');
  32722. var atlasInfo = debugInfo.atlasInfo;
  32723. var _iterator2 = _createForOfIteratorHelper(atlasInfo),
  32724. _step2;
  32725. try {
  32726. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  32727. var info = _step2.value;
  32728. console.log(" ".concat(info.type, ": ").concat(info.keyCount, " keys, ").concat(info.atlasCount, " atlases"));
  32729. }
  32730. } catch (err) {
  32731. _iterator2.e(err);
  32732. } finally {
  32733. _iterator2.f();
  32734. }
  32735. console.log('');
  32736. }
  32737. }
  32738. if (r.data.gc) {
  32739. console.log('Garbage Collect!');
  32740. r.data.gc = false;
  32741. drawing.gc();
  32742. }
  32743. }
  32744. var CRp$3 = {};
  32745. // @O Polygon drawing
  32746. CRp$3.drawPolygonPath = function (context, x, y, width, height, points) {
  32747. var halfW = width / 2;
  32748. var halfH = height / 2;
  32749. if (context.beginPath) {
  32750. context.beginPath();
  32751. }
  32752. context.moveTo(x + halfW * points[0], y + halfH * points[1]);
  32753. for (var i = 1; i < points.length / 2; i++) {
  32754. context.lineTo(x + halfW * points[i * 2], y + halfH * points[i * 2 + 1]);
  32755. }
  32756. context.closePath();
  32757. };
  32758. CRp$3.drawRoundPolygonPath = function (context, x, y, width, height, points, corners) {
  32759. corners.forEach(function (corner) {
  32760. return drawPreparedRoundCorner(context, corner);
  32761. });
  32762. context.closePath();
  32763. };
  32764. // Round rectangle drawing
  32765. CRp$3.drawRoundRectanglePath = function (context, x, y, width, height, radius) {
  32766. var halfWidth = width / 2;
  32767. var halfHeight = height / 2;
  32768. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : Math.min(radius, halfHeight, halfWidth);
  32769. if (context.beginPath) {
  32770. context.beginPath();
  32771. }
  32772. // Start at top middle
  32773. context.moveTo(x, y - halfHeight);
  32774. // Arc from middle top to right side
  32775. context.arcTo(x + halfWidth, y - halfHeight, x + halfWidth, y, cornerRadius);
  32776. // Arc from right side to bottom
  32777. context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  32778. // Arc from bottom to left side
  32779. context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  32780. // Arc from left side to topBorder
  32781. context.arcTo(x - halfWidth, y - halfHeight, x, y - halfHeight, cornerRadius);
  32782. // Join line
  32783. context.lineTo(x, y - halfHeight);
  32784. context.closePath();
  32785. };
  32786. CRp$3.drawBottomRoundRectanglePath = function (context, x, y, width, height, radius) {
  32787. var halfWidth = width / 2;
  32788. var halfHeight = height / 2;
  32789. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  32790. if (context.beginPath) {
  32791. context.beginPath();
  32792. }
  32793. // Start at top middle
  32794. context.moveTo(x, y - halfHeight);
  32795. context.lineTo(x + halfWidth, y - halfHeight);
  32796. context.lineTo(x + halfWidth, y);
  32797. context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  32798. context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  32799. context.lineTo(x - halfWidth, y - halfHeight);
  32800. context.lineTo(x, y - halfHeight);
  32801. context.closePath();
  32802. };
  32803. CRp$3.drawCutRectanglePath = function (context, x, y, width, height, points, corners) {
  32804. var halfWidth = width / 2;
  32805. var halfHeight = height / 2;
  32806. var cornerLength = corners === 'auto' ? getCutRectangleCornerLength() : corners;
  32807. if (context.beginPath) {
  32808. context.beginPath();
  32809. }
  32810. context.moveTo(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.lineTo(x + halfWidth - cornerLength, y + halfHeight);
  32815. context.lineTo(x - halfWidth + cornerLength, y + halfHeight);
  32816. context.lineTo(x - halfWidth, y + halfHeight - cornerLength);
  32817. context.lineTo(x - halfWidth, y - halfHeight + cornerLength);
  32818. context.closePath();
  32819. };
  32820. CRp$3.drawBarrelPath = function (context, x, y, width, height) {
  32821. var halfWidth = width / 2;
  32822. var halfHeight = height / 2;
  32823. var xBegin = x - halfWidth;
  32824. var xEnd = x + halfWidth;
  32825. var yBegin = y - halfHeight;
  32826. var yEnd = y + halfHeight;
  32827. var barrelCurveConstants = getBarrelCurveConstants(width, height);
  32828. var wOffset = barrelCurveConstants.widthOffset;
  32829. var hOffset = barrelCurveConstants.heightOffset;
  32830. var ctrlPtXOffset = barrelCurveConstants.ctrlPtOffsetPct * wOffset;
  32831. if (context.beginPath) {
  32832. context.beginPath();
  32833. }
  32834. context.moveTo(xBegin, yBegin + hOffset);
  32835. context.lineTo(xBegin, yEnd - hOffset);
  32836. context.quadraticCurveTo(xBegin + ctrlPtXOffset, yEnd, xBegin + wOffset, yEnd);
  32837. context.lineTo(xEnd - wOffset, yEnd);
  32838. context.quadraticCurveTo(xEnd - ctrlPtXOffset, yEnd, xEnd, yEnd - hOffset);
  32839. context.lineTo(xEnd, yBegin + hOffset);
  32840. context.quadraticCurveTo(xEnd - ctrlPtXOffset, yBegin, xEnd - wOffset, yBegin);
  32841. context.lineTo(xBegin + wOffset, yBegin);
  32842. context.quadraticCurveTo(xBegin + ctrlPtXOffset, yBegin, xBegin, yBegin + hOffset);
  32843. context.closePath();
  32844. };
  32845. var sin0 = Math.sin(0);
  32846. var cos0 = Math.cos(0);
  32847. var sin = {};
  32848. var cos = {};
  32849. var ellipseStepSize = Math.PI / 40;
  32850. for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  32851. sin[i] = Math.sin(i);
  32852. cos[i] = Math.cos(i);
  32853. }
  32854. CRp$3.drawEllipsePath = function (context, centerX, centerY, width, height) {
  32855. if (context.beginPath) {
  32856. context.beginPath();
  32857. }
  32858. if (context.ellipse) {
  32859. context.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, 2 * Math.PI);
  32860. } else {
  32861. var xPos, yPos;
  32862. var rw = width / 2;
  32863. var rh = height / 2;
  32864. for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  32865. xPos = centerX - rw * sin[i] * sin0 + rw * cos[i] * cos0;
  32866. yPos = centerY + rh * cos[i] * sin0 + rh * sin[i] * cos0;
  32867. if (i === 0) {
  32868. context.moveTo(xPos, yPos);
  32869. } else {
  32870. context.lineTo(xPos, yPos);
  32871. }
  32872. }
  32873. }
  32874. context.closePath();
  32875. };
  32876. /* global atob, ArrayBuffer, Uint8Array, Blob */
  32877. var CRp$2 = {};
  32878. CRp$2.createBuffer = function (w, h) {
  32879. var buffer = document.createElement('canvas'); // eslint-disable-line no-undef
  32880. buffer.width = w;
  32881. buffer.height = h;
  32882. return [buffer, buffer.getContext('2d')];
  32883. };
  32884. CRp$2.bufferCanvasImage = function (options) {
  32885. var cy = this.cy;
  32886. var eles = cy.mutableElements();
  32887. var bb = eles.boundingBox();
  32888. var ctrRect = this.findContainerClientCoords();
  32889. var width = options.full ? Math.ceil(bb.w) : ctrRect[2];
  32890. var height = options.full ? Math.ceil(bb.h) : ctrRect[3];
  32891. var specdMaxDims = number$1(options.maxWidth) || number$1(options.maxHeight);
  32892. var pxRatio = this.getPixelRatio();
  32893. var scale = 1;
  32894. if (options.scale !== undefined) {
  32895. width *= options.scale;
  32896. height *= options.scale;
  32897. scale = options.scale;
  32898. } else if (specdMaxDims) {
  32899. var maxScaleW = Infinity;
  32900. var maxScaleH = Infinity;
  32901. if (number$1(options.maxWidth)) {
  32902. maxScaleW = scale * options.maxWidth / width;
  32903. }
  32904. if (number$1(options.maxHeight)) {
  32905. maxScaleH = scale * options.maxHeight / height;
  32906. }
  32907. scale = Math.min(maxScaleW, maxScaleH);
  32908. width *= scale;
  32909. height *= scale;
  32910. }
  32911. if (!specdMaxDims) {
  32912. width *= pxRatio;
  32913. height *= pxRatio;
  32914. scale *= pxRatio;
  32915. }
  32916. var buffCanvas = document.createElement('canvas'); // eslint-disable-line no-undef
  32917. buffCanvas.width = width;
  32918. buffCanvas.height = height;
  32919. buffCanvas.style.width = width + 'px';
  32920. buffCanvas.style.height = height + 'px';
  32921. var buffCxt = buffCanvas.getContext('2d');
  32922. // Rasterize the layers, but only if container has nonzero size
  32923. if (width > 0 && height > 0) {
  32924. buffCxt.clearRect(0, 0, width, height);
  32925. buffCxt.globalCompositeOperation = 'source-over';
  32926. var zsortedEles = this.getCachedZSortedEles();
  32927. if (options.full) {
  32928. // draw the full bounds of the graph
  32929. buffCxt.translate(-bb.x1 * scale, -bb.y1 * scale);
  32930. buffCxt.scale(scale, scale);
  32931. this.drawElements(buffCxt, zsortedEles);
  32932. buffCxt.scale(1 / scale, 1 / scale);
  32933. buffCxt.translate(bb.x1 * scale, bb.y1 * scale);
  32934. } else {
  32935. // draw the current view
  32936. var pan = cy.pan();
  32937. var translation = {
  32938. x: pan.x * scale,
  32939. y: pan.y * scale
  32940. };
  32941. scale *= cy.zoom();
  32942. buffCxt.translate(translation.x, translation.y);
  32943. buffCxt.scale(scale, scale);
  32944. this.drawElements(buffCxt, zsortedEles);
  32945. buffCxt.scale(1 / scale, 1 / scale);
  32946. buffCxt.translate(-translation.x, -translation.y);
  32947. }
  32948. // need to fill bg at end like this in order to fill cleared transparent pixels in jpgs
  32949. if (options.bg) {
  32950. buffCxt.globalCompositeOperation = 'destination-over';
  32951. buffCxt.fillStyle = options.bg;
  32952. buffCxt.rect(0, 0, width, height);
  32953. buffCxt.fill();
  32954. }
  32955. }
  32956. return buffCanvas;
  32957. };
  32958. function b64ToBlob(b64, mimeType) {
  32959. var bytes = atob(b64);
  32960. var buff = new ArrayBuffer(bytes.length);
  32961. var buffUint8 = new Uint8Array(buff);
  32962. for (var i = 0; i < bytes.length; i++) {
  32963. buffUint8[i] = bytes.charCodeAt(i);
  32964. }
  32965. return new Blob([buff], {
  32966. type: mimeType
  32967. });
  32968. }
  32969. function b64UriToB64(b64uri) {
  32970. var i = b64uri.indexOf(',');
  32971. return b64uri.substr(i + 1);
  32972. }
  32973. function output(options, canvas, mimeType) {
  32974. var getB64Uri = function getB64Uri() {
  32975. return canvas.toDataURL(mimeType, options.quality);
  32976. };
  32977. switch (options.output) {
  32978. case 'blob-promise':
  32979. return new Promise$1(function (resolve, reject) {
  32980. try {
  32981. canvas.toBlob(function (blob) {
  32982. if (blob != null) {
  32983. resolve(blob);
  32984. } else {
  32985. reject(new Error('`canvas.toBlob()` sent a null value in its callback'));
  32986. }
  32987. }, mimeType, options.quality);
  32988. } catch (err) {
  32989. reject(err);
  32990. }
  32991. });
  32992. case 'blob':
  32993. return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);
  32994. case 'base64':
  32995. return b64UriToB64(getB64Uri());
  32996. case 'base64uri':
  32997. default:
  32998. return getB64Uri();
  32999. }
  33000. }
  33001. CRp$2.png = function (options) {
  33002. return output(options, this.bufferCanvasImage(options), 'image/png');
  33003. };
  33004. CRp$2.jpg = function (options) {
  33005. return output(options, this.bufferCanvasImage(options), 'image/jpeg');
  33006. };
  33007. var CRp$1 = {};
  33008. CRp$1.nodeShapeImpl = function (name, context, centerX, centerY, width, height, points, corners) {
  33009. switch (name) {
  33010. case 'ellipse':
  33011. return this.drawEllipsePath(context, centerX, centerY, width, height);
  33012. case 'polygon':
  33013. return this.drawPolygonPath(context, centerX, centerY, width, height, points);
  33014. case 'round-polygon':
  33015. return this.drawRoundPolygonPath(context, centerX, centerY, width, height, points, corners);
  33016. case 'roundrectangle':
  33017. case 'round-rectangle':
  33018. return this.drawRoundRectanglePath(context, centerX, centerY, width, height, corners);
  33019. case 'cutrectangle':
  33020. case 'cut-rectangle':
  33021. return this.drawCutRectanglePath(context, centerX, centerY, width, height, points, corners);
  33022. case 'bottomroundrectangle':
  33023. case 'bottom-round-rectangle':
  33024. return this.drawBottomRoundRectanglePath(context, centerX, centerY, width, height, corners);
  33025. case 'barrel':
  33026. return this.drawBarrelPath(context, centerX, centerY, width, height);
  33027. }
  33028. };
  33029. var CR = CanvasRenderer;
  33030. var CRp = CanvasRenderer.prototype;
  33031. CRp.CANVAS_LAYERS = 3;
  33032. //
  33033. CRp.SELECT_BOX = 0;
  33034. CRp.DRAG = 1;
  33035. CRp.NODE = 2;
  33036. CRp.WEBGL = 3;
  33037. CRp.CANVAS_TYPES = ['2d', '2d', '2d', 'webgl2'];
  33038. CRp.BUFFER_COUNT = 3;
  33039. //
  33040. CRp.TEXTURE_BUFFER = 0;
  33041. CRp.MOTIONBLUR_BUFFER_NODE = 1;
  33042. CRp.MOTIONBLUR_BUFFER_DRAG = 2;
  33043. function CanvasRenderer(options) {
  33044. var r = this;
  33045. var containerWindow = r.cy.window();
  33046. var document = containerWindow.document;
  33047. if (options.webgl) {
  33048. CRp.CANVAS_LAYERS = r.CANVAS_LAYERS = 4;
  33049. console.log('webgl rendering enabled');
  33050. }
  33051. r.data = {
  33052. canvases: new Array(CRp.CANVAS_LAYERS),
  33053. contexts: new Array(CRp.CANVAS_LAYERS),
  33054. canvasNeedsRedraw: new Array(CRp.CANVAS_LAYERS),
  33055. bufferCanvases: new Array(CRp.BUFFER_COUNT),
  33056. bufferContexts: new Array(CRp.CANVAS_LAYERS)
  33057. };
  33058. var tapHlOffAttr = '-webkit-tap-highlight-color';
  33059. var tapHlOffStyle = 'rgba(0,0,0,0)';
  33060. r.data.canvasContainer = document.createElement('div'); // eslint-disable-line no-undef
  33061. var containerStyle = r.data.canvasContainer.style;
  33062. r.data.canvasContainer.style[tapHlOffAttr] = tapHlOffStyle;
  33063. containerStyle.position = 'relative';
  33064. containerStyle.zIndex = '0';
  33065. containerStyle.overflow = 'hidden';
  33066. var container = options.cy.container();
  33067. container.appendChild(r.data.canvasContainer);
  33068. container.style[tapHlOffAttr] = tapHlOffStyle;
  33069. var styleMap = {
  33070. '-webkit-user-select': 'none',
  33071. '-moz-user-select': '-moz-none',
  33072. 'user-select': 'none',
  33073. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',
  33074. 'outline-style': 'none'
  33075. };
  33076. if (ms()) {
  33077. styleMap['-ms-touch-action'] = 'none';
  33078. styleMap['touch-action'] = 'none';
  33079. }
  33080. for (var i = 0; i < CRp.CANVAS_LAYERS; i++) {
  33081. var canvas = r.data.canvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
  33082. var type = CRp.CANVAS_TYPES[i];
  33083. r.data.contexts[i] = canvas.getContext(type);
  33084. if (!r.data.contexts[i]) {
  33085. error('Could not create canvas of type ' + type);
  33086. }
  33087. Object.keys(styleMap).forEach(function (k) {
  33088. canvas.style[k] = styleMap[k];
  33089. });
  33090. canvas.style.position = 'absolute';
  33091. canvas.setAttribute('data-id', 'layer' + i);
  33092. canvas.style.zIndex = String(CRp.CANVAS_LAYERS - i);
  33093. r.data.canvasContainer.appendChild(canvas);
  33094. r.data.canvasNeedsRedraw[i] = false;
  33095. }
  33096. r.data.topCanvas = r.data.canvases[0];
  33097. r.data.canvases[CRp.NODE].setAttribute('data-id', 'layer' + CRp.NODE + '-node');
  33098. r.data.canvases[CRp.SELECT_BOX].setAttribute('data-id', 'layer' + CRp.SELECT_BOX + '-selectbox');
  33099. r.data.canvases[CRp.DRAG].setAttribute('data-id', 'layer' + CRp.DRAG + '-drag');
  33100. if (r.data.canvases[CRp.WEBGL]) {
  33101. r.data.canvases[CRp.WEBGL].setAttribute('data-id', 'layer' + CRp.WEBGL + '-webgl');
  33102. }
  33103. for (var i = 0; i < CRp.BUFFER_COUNT; i++) {
  33104. r.data.bufferCanvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
  33105. r.data.bufferContexts[i] = r.data.bufferCanvases[i].getContext('2d');
  33106. r.data.bufferCanvases[i].style.position = 'absolute';
  33107. r.data.bufferCanvases[i].setAttribute('data-id', 'buffer' + i);
  33108. r.data.bufferCanvases[i].style.zIndex = String(-i - 1);
  33109. r.data.bufferCanvases[i].style.visibility = 'hidden';
  33110. //r.data.canvasContainer.appendChild(r.data.bufferCanvases[i]);
  33111. }
  33112. r.pathsEnabled = true;
  33113. var emptyBb = makeBoundingBox();
  33114. var getBoxCenter = function getBoxCenter(bb) {
  33115. return {
  33116. x: (bb.x1 + bb.x2) / 2,
  33117. y: (bb.y1 + bb.y2) / 2
  33118. };
  33119. };
  33120. var getCenterOffset = function getCenterOffset(bb) {
  33121. return {
  33122. x: -bb.w / 2,
  33123. y: -bb.h / 2
  33124. };
  33125. };
  33126. var backgroundTimestampHasChanged = function backgroundTimestampHasChanged(ele) {
  33127. var _p = ele[0]._private;
  33128. var same = _p.oldBackgroundTimestamp === _p.backgroundTimestamp;
  33129. return !same;
  33130. };
  33131. var getStyleKey = function getStyleKey(ele) {
  33132. return ele[0]._private.nodeKey;
  33133. };
  33134. var getLabelKey = function getLabelKey(ele) {
  33135. return ele[0]._private.labelStyleKey;
  33136. };
  33137. var getSourceLabelKey = function getSourceLabelKey(ele) {
  33138. return ele[0]._private.sourceLabelStyleKey;
  33139. };
  33140. var getTargetLabelKey = function getTargetLabelKey(ele) {
  33141. return ele[0]._private.targetLabelStyleKey;
  33142. };
  33143. var drawElement = function drawElement(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33144. return r.drawElement(context, ele, bb, false, false, useEleOpacity);
  33145. };
  33146. var drawLabel = function drawLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33147. return r.drawElementText(context, ele, bb, scaledLabelShown, 'main', useEleOpacity);
  33148. };
  33149. var drawSourceLabel = function drawSourceLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33150. return r.drawElementText(context, ele, bb, scaledLabelShown, 'source', useEleOpacity);
  33151. };
  33152. var drawTargetLabel = function drawTargetLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33153. return r.drawElementText(context, ele, bb, scaledLabelShown, 'target', useEleOpacity);
  33154. };
  33155. var getElementBox = function getElementBox(ele) {
  33156. ele.boundingBox();
  33157. return ele[0]._private.bodyBounds;
  33158. };
  33159. var getLabelBox = function getLabelBox(ele) {
  33160. ele.boundingBox();
  33161. return ele[0]._private.labelBounds.main || emptyBb;
  33162. };
  33163. var getSourceLabelBox = function getSourceLabelBox(ele) {
  33164. ele.boundingBox();
  33165. return ele[0]._private.labelBounds.source || emptyBb;
  33166. };
  33167. var getTargetLabelBox = function getTargetLabelBox(ele) {
  33168. ele.boundingBox();
  33169. return ele[0]._private.labelBounds.target || emptyBb;
  33170. };
  33171. var isLabelVisibleAtScale = function isLabelVisibleAtScale(ele, scaledLabelShown) {
  33172. return scaledLabelShown;
  33173. };
  33174. var getElementRotationPoint = function getElementRotationPoint(ele) {
  33175. return getBoxCenter(getElementBox(ele));
  33176. };
  33177. var addTextMargin = function addTextMargin(prefix, pt, ele) {
  33178. var pre = prefix ? prefix + '-' : '';
  33179. return {
  33180. x: pt.x + ele.pstyle(pre + 'text-margin-x').pfValue,
  33181. y: pt.y + ele.pstyle(pre + 'text-margin-y').pfValue
  33182. };
  33183. };
  33184. var getRsPt = function getRsPt(ele, x, y) {
  33185. var rs = ele[0]._private.rscratch;
  33186. return {
  33187. x: rs[x],
  33188. y: rs[y]
  33189. };
  33190. };
  33191. var getLabelRotationPoint = function getLabelRotationPoint(ele) {
  33192. return addTextMargin('', getRsPt(ele, 'labelX', 'labelY'), ele);
  33193. };
  33194. var getSourceLabelRotationPoint = function getSourceLabelRotationPoint(ele) {
  33195. return addTextMargin('source', getRsPt(ele, 'sourceLabelX', 'sourceLabelY'), ele);
  33196. };
  33197. var getTargetLabelRotationPoint = function getTargetLabelRotationPoint(ele) {
  33198. return addTextMargin('target', getRsPt(ele, 'targetLabelX', 'targetLabelY'), ele);
  33199. };
  33200. var getElementRotationOffset = function getElementRotationOffset(ele) {
  33201. return getCenterOffset(getElementBox(ele));
  33202. };
  33203. var getSourceLabelRotationOffset = function getSourceLabelRotationOffset(ele) {
  33204. return getCenterOffset(getSourceLabelBox(ele));
  33205. };
  33206. var getTargetLabelRotationOffset = function getTargetLabelRotationOffset(ele) {
  33207. return getCenterOffset(getTargetLabelBox(ele));
  33208. };
  33209. var getLabelRotationOffset = function getLabelRotationOffset(ele) {
  33210. var bb = getLabelBox(ele);
  33211. var p = getCenterOffset(getLabelBox(ele));
  33212. if (ele.isNode()) {
  33213. switch (ele.pstyle('text-halign').value) {
  33214. case 'left':
  33215. p.x = -bb.w - (bb.leftPad || 0);
  33216. break;
  33217. case 'right':
  33218. p.x = -(bb.rightPad || 0);
  33219. break;
  33220. }
  33221. switch (ele.pstyle('text-valign').value) {
  33222. case 'top':
  33223. p.y = -bb.h - (bb.topPad || 0);
  33224. break;
  33225. case 'bottom':
  33226. p.y = -(bb.botPad || 0);
  33227. break;
  33228. }
  33229. }
  33230. return p;
  33231. };
  33232. var eleTxrCache = r.data.eleTxrCache = new ElementTextureCache(r, {
  33233. getKey: getStyleKey,
  33234. doesEleInvalidateKey: backgroundTimestampHasChanged,
  33235. drawElement: drawElement,
  33236. getBoundingBox: getElementBox,
  33237. getRotationPoint: getElementRotationPoint,
  33238. getRotationOffset: getElementRotationOffset,
  33239. allowEdgeTxrCaching: false,
  33240. allowParentTxrCaching: false
  33241. });
  33242. var lblTxrCache = r.data.lblTxrCache = new ElementTextureCache(r, {
  33243. getKey: getLabelKey,
  33244. drawElement: drawLabel,
  33245. getBoundingBox: getLabelBox,
  33246. getRotationPoint: getLabelRotationPoint,
  33247. getRotationOffset: getLabelRotationOffset,
  33248. isVisible: isLabelVisibleAtScale
  33249. });
  33250. var slbTxrCache = r.data.slbTxrCache = new ElementTextureCache(r, {
  33251. getKey: getSourceLabelKey,
  33252. drawElement: drawSourceLabel,
  33253. getBoundingBox: getSourceLabelBox,
  33254. getRotationPoint: getSourceLabelRotationPoint,
  33255. getRotationOffset: getSourceLabelRotationOffset,
  33256. isVisible: isLabelVisibleAtScale
  33257. });
  33258. var tlbTxrCache = r.data.tlbTxrCache = new ElementTextureCache(r, {
  33259. getKey: getTargetLabelKey,
  33260. drawElement: drawTargetLabel,
  33261. getBoundingBox: getTargetLabelBox,
  33262. getRotationPoint: getTargetLabelRotationPoint,
  33263. getRotationOffset: getTargetLabelRotationOffset,
  33264. isVisible: isLabelVisibleAtScale
  33265. });
  33266. var lyrTxrCache = r.data.lyrTxrCache = new LayeredTextureCache(r);
  33267. r.onUpdateEleCalcs(function invalidateTextureCaches(willDraw, eles) {
  33268. // each cache should check for sub-key diff to see that the update affects that cache particularly
  33269. eleTxrCache.invalidateElements(eles);
  33270. lblTxrCache.invalidateElements(eles);
  33271. slbTxrCache.invalidateElements(eles);
  33272. tlbTxrCache.invalidateElements(eles);
  33273. // any change invalidates the layers
  33274. lyrTxrCache.invalidateElements(eles);
  33275. // update the old bg timestamp so diffs can be done in the ele txr caches
  33276. for (var _i = 0; _i < eles.length; _i++) {
  33277. var _p = eles[_i]._private;
  33278. _p.oldBackgroundTimestamp = _p.backgroundTimestamp;
  33279. }
  33280. });
  33281. var refineInLayers = function refineInLayers(reqs) {
  33282. for (var i = 0; i < reqs.length; i++) {
  33283. lyrTxrCache.enqueueElementRefinement(reqs[i].ele);
  33284. }
  33285. };
  33286. eleTxrCache.onDequeue(refineInLayers);
  33287. lblTxrCache.onDequeue(refineInLayers);
  33288. slbTxrCache.onDequeue(refineInLayers);
  33289. tlbTxrCache.onDequeue(refineInLayers);
  33290. if (options.webgl) {
  33291. r.initWebgl(options, {
  33292. getStyleKey: getStyleKey,
  33293. getLabelKey: getLabelKey,
  33294. getSourceLabelKey: getSourceLabelKey,
  33295. getTargetLabelKey: getTargetLabelKey,
  33296. drawElement: drawElement,
  33297. drawLabel: drawLabel,
  33298. drawSourceLabel: drawSourceLabel,
  33299. drawTargetLabel: drawTargetLabel,
  33300. getElementBox: getElementBox,
  33301. getLabelBox: getLabelBox,
  33302. getSourceLabelBox: getSourceLabelBox,
  33303. getTargetLabelBox: getTargetLabelBox,
  33304. getElementRotationPoint: getElementRotationPoint,
  33305. getElementRotationOffset: getElementRotationOffset,
  33306. getLabelRotationPoint: getLabelRotationPoint,
  33307. getSourceLabelRotationPoint: getSourceLabelRotationPoint,
  33308. getTargetLabelRotationPoint: getTargetLabelRotationPoint,
  33309. getLabelRotationOffset: getLabelRotationOffset,
  33310. getSourceLabelRotationOffset: getSourceLabelRotationOffset,
  33311. getTargetLabelRotationOffset: getTargetLabelRotationOffset
  33312. });
  33313. }
  33314. }
  33315. CRp.redrawHint = function (group, bool) {
  33316. var r = this;
  33317. switch (group) {
  33318. case 'eles':
  33319. r.data.canvasNeedsRedraw[CRp.NODE] = bool;
  33320. break;
  33321. case 'drag':
  33322. r.data.canvasNeedsRedraw[CRp.DRAG] = bool;
  33323. break;
  33324. case 'select':
  33325. r.data.canvasNeedsRedraw[CRp.SELECT_BOX] = bool;
  33326. break;
  33327. case 'gc':
  33328. r.data.gc = true;
  33329. break;
  33330. }
  33331. };
  33332. // whether to use Path2D caching for drawing
  33333. var pathsImpld = typeof Path2D !== 'undefined';
  33334. CRp.path2dEnabled = function (on) {
  33335. if (on === undefined) {
  33336. return this.pathsEnabled;
  33337. }
  33338. this.pathsEnabled = on ? true : false;
  33339. };
  33340. CRp.usePaths = function () {
  33341. return pathsImpld && this.pathsEnabled;
  33342. };
  33343. CRp.setImgSmoothing = function (context, bool) {
  33344. if (context.imageSmoothingEnabled != null) {
  33345. context.imageSmoothingEnabled = bool;
  33346. } else {
  33347. context.webkitImageSmoothingEnabled = bool;
  33348. context.mozImageSmoothingEnabled = bool;
  33349. context.msImageSmoothingEnabled = bool;
  33350. }
  33351. };
  33352. CRp.getImgSmoothing = function (context) {
  33353. if (context.imageSmoothingEnabled != null) {
  33354. return context.imageSmoothingEnabled;
  33355. } else {
  33356. return context.webkitImageSmoothingEnabled || context.mozImageSmoothingEnabled || context.msImageSmoothingEnabled;
  33357. }
  33358. };
  33359. CRp.makeOffscreenCanvas = function (width, height) {
  33360. var canvas;
  33361. if ((typeof OffscreenCanvas === "undefined" ? "undefined" : _typeof(OffscreenCanvas)) !== ("undefined" )) {
  33362. canvas = new OffscreenCanvas(width, height);
  33363. } else {
  33364. var containerWindow = this.cy.window();
  33365. var document = containerWindow.document;
  33366. canvas = document.createElement('canvas'); // eslint-disable-line no-undef
  33367. canvas.width = width;
  33368. canvas.height = height;
  33369. }
  33370. return canvas;
  33371. };
  33372. [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) {
  33373. extend(CRp, props);
  33374. });
  33375. var renderer = [{
  33376. name: 'null',
  33377. impl: NullRenderer
  33378. }, {
  33379. name: 'base',
  33380. impl: BR
  33381. }, {
  33382. name: 'canvas',
  33383. impl: CR
  33384. }];
  33385. var incExts = [{
  33386. type: 'layout',
  33387. extensions: layout
  33388. }, {
  33389. type: 'renderer',
  33390. extensions: renderer
  33391. }];
  33392. // registered extensions to cytoscape, indexed by name
  33393. var extensions = {};
  33394. // registered modules for extensions, indexed by name
  33395. var modules = {};
  33396. function setExtension(type, name, registrant) {
  33397. var ext = registrant;
  33398. var overrideErr = function overrideErr(field) {
  33399. warn('Can not register `' + name + '` for `' + type + '` since `' + field + '` already exists in the prototype and can not be overridden');
  33400. };
  33401. if (type === 'core') {
  33402. if (Core.prototype[name]) {
  33403. return overrideErr(name);
  33404. } else {
  33405. Core.prototype[name] = registrant;
  33406. }
  33407. } else if (type === 'collection') {
  33408. if (Collection.prototype[name]) {
  33409. return overrideErr(name);
  33410. } else {
  33411. Collection.prototype[name] = registrant;
  33412. }
  33413. } else if (type === 'layout') {
  33414. // fill in missing layout functions in the prototype
  33415. var Layout = function Layout(options) {
  33416. this.options = options;
  33417. registrant.call(this, options);
  33418. // make sure layout has _private for use w/ std apis like .on()
  33419. if (!plainObject(this._private)) {
  33420. this._private = {};
  33421. }
  33422. this._private.cy = options.cy;
  33423. this._private.listeners = [];
  33424. this.createEmitter();
  33425. };
  33426. var layoutProto = Layout.prototype = Object.create(registrant.prototype);
  33427. var optLayoutFns = [];
  33428. for (var i = 0; i < optLayoutFns.length; i++) {
  33429. var fnName = optLayoutFns[i];
  33430. layoutProto[fnName] = layoutProto[fnName] || function () {
  33431. return this;
  33432. };
  33433. }
  33434. // either .start() or .run() is defined, so autogen the other
  33435. if (layoutProto.start && !layoutProto.run) {
  33436. layoutProto.run = function () {
  33437. this.start();
  33438. return this;
  33439. };
  33440. } else if (!layoutProto.start && layoutProto.run) {
  33441. layoutProto.start = function () {
  33442. this.run();
  33443. return this;
  33444. };
  33445. }
  33446. var regStop = registrant.prototype.stop;
  33447. layoutProto.stop = function () {
  33448. var opts = this.options;
  33449. if (opts && opts.animate) {
  33450. var anis = this.animations;
  33451. if (anis) {
  33452. for (var _i = 0; _i < anis.length; _i++) {
  33453. anis[_i].stop();
  33454. }
  33455. }
  33456. }
  33457. if (regStop) {
  33458. regStop.call(this);
  33459. } else {
  33460. this.emit('layoutstop');
  33461. }
  33462. return this;
  33463. };
  33464. if (!layoutProto.destroy) {
  33465. layoutProto.destroy = function () {
  33466. return this;
  33467. };
  33468. }
  33469. layoutProto.cy = function () {
  33470. return this._private.cy;
  33471. };
  33472. var getCy = function getCy(layout) {
  33473. return layout._private.cy;
  33474. };
  33475. var emitterOpts = {
  33476. addEventFields: function addEventFields(layout, evt) {
  33477. evt.layout = layout;
  33478. evt.cy = getCy(layout);
  33479. evt.target = layout;
  33480. },
  33481. bubble: function bubble() {
  33482. return true;
  33483. },
  33484. parent: function parent(layout) {
  33485. return getCy(layout);
  33486. }
  33487. };
  33488. extend(layoutProto, {
  33489. createEmitter: function createEmitter() {
  33490. this._private.emitter = new Emitter(emitterOpts, this);
  33491. return this;
  33492. },
  33493. emitter: function emitter() {
  33494. return this._private.emitter;
  33495. },
  33496. on: function on(evt, cb) {
  33497. this.emitter().on(evt, cb);
  33498. return this;
  33499. },
  33500. one: function one(evt, cb) {
  33501. this.emitter().one(evt, cb);
  33502. return this;
  33503. },
  33504. once: function once(evt, cb) {
  33505. this.emitter().one(evt, cb);
  33506. return this;
  33507. },
  33508. removeListener: function removeListener(evt, cb) {
  33509. this.emitter().removeListener(evt, cb);
  33510. return this;
  33511. },
  33512. removeAllListeners: function removeAllListeners() {
  33513. this.emitter().removeAllListeners();
  33514. return this;
  33515. },
  33516. emit: function emit(evt, params) {
  33517. this.emitter().emit(evt, params);
  33518. return this;
  33519. }
  33520. });
  33521. define.eventAliasesOn(layoutProto);
  33522. ext = Layout; // replace with our wrapped layout
  33523. } else if (type === 'renderer' && name !== 'null' && name !== 'base') {
  33524. // user registered renderers inherit from base
  33525. var BaseRenderer = getExtension('renderer', 'base');
  33526. var bProto = BaseRenderer.prototype;
  33527. var RegistrantRenderer = registrant;
  33528. var rProto = registrant.prototype;
  33529. var Renderer = function Renderer() {
  33530. BaseRenderer.apply(this, arguments);
  33531. RegistrantRenderer.apply(this, arguments);
  33532. };
  33533. var proto = Renderer.prototype;
  33534. for (var pName in bProto) {
  33535. var pVal = bProto[pName];
  33536. var existsInR = rProto[pName] != null;
  33537. if (existsInR) {
  33538. return overrideErr(pName);
  33539. }
  33540. proto[pName] = pVal; // take impl from base
  33541. }
  33542. for (var _pName in rProto) {
  33543. proto[_pName] = rProto[_pName]; // take impl from registrant
  33544. }
  33545. bProto.clientFunctions.forEach(function (name) {
  33546. proto[name] = proto[name] || function () {
  33547. error('Renderer does not implement `renderer.' + name + '()` on its prototype');
  33548. };
  33549. });
  33550. ext = Renderer;
  33551. } else if (type === '__proto__' || type === 'constructor' || type === 'prototype') {
  33552. // to avoid potential prototype pollution
  33553. return error(type + ' is an illegal type to be registered, possibly lead to prototype pollutions');
  33554. }
  33555. return setMap({
  33556. map: extensions,
  33557. keys: [type, name],
  33558. value: ext
  33559. });
  33560. }
  33561. function getExtension(type, name) {
  33562. return getMap({
  33563. map: extensions,
  33564. keys: [type, name]
  33565. });
  33566. }
  33567. function setModule(type, name, moduleType, moduleName, registrant) {
  33568. return setMap({
  33569. map: modules,
  33570. keys: [type, name, moduleType, moduleName],
  33571. value: registrant
  33572. });
  33573. }
  33574. function getModule(type, name, moduleType, moduleName) {
  33575. return getMap({
  33576. map: modules,
  33577. keys: [type, name, moduleType, moduleName]
  33578. });
  33579. }
  33580. var extension = function extension() {
  33581. // e.g. extension('renderer', 'svg')
  33582. if (arguments.length === 2) {
  33583. return getExtension.apply(null, arguments);
  33584. }
  33585. // e.g. extension('renderer', 'svg', { ... })
  33586. else if (arguments.length === 3) {
  33587. return setExtension.apply(null, arguments);
  33588. }
  33589. // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse')
  33590. else if (arguments.length === 4) {
  33591. return getModule.apply(null, arguments);
  33592. }
  33593. // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse', { ... })
  33594. else if (arguments.length === 5) {
  33595. return setModule.apply(null, arguments);
  33596. } else {
  33597. error('Invalid extension access syntax');
  33598. }
  33599. };
  33600. // allows a core instance to access extensions internally
  33601. Core.prototype.extension = extension;
  33602. // included extensions
  33603. incExts.forEach(function (group) {
  33604. group.extensions.forEach(function (ext) {
  33605. setExtension(group.type, ext.name, ext.impl);
  33606. });
  33607. });
  33608. // a dummy stylesheet object that doesn't need a reference to the core
  33609. // (useful for init)
  33610. var _Stylesheet = function Stylesheet() {
  33611. if (!(this instanceof _Stylesheet)) {
  33612. return new _Stylesheet();
  33613. }
  33614. this.length = 0;
  33615. };
  33616. var sheetfn = _Stylesheet.prototype;
  33617. sheetfn.instanceString = function () {
  33618. return 'stylesheet';
  33619. };
  33620. // just store the selector to be parsed later
  33621. sheetfn.selector = function (selector) {
  33622. var i = this.length++;
  33623. this[i] = {
  33624. selector: selector,
  33625. properties: []
  33626. };
  33627. return this; // chaining
  33628. };
  33629. // just store the property to be parsed later
  33630. sheetfn.css = function (name, value) {
  33631. var i = this.length - 1;
  33632. if (string(name)) {
  33633. this[i].properties.push({
  33634. name: name,
  33635. value: value
  33636. });
  33637. } else if (plainObject(name)) {
  33638. var map = name;
  33639. var propNames = Object.keys(map);
  33640. for (var j = 0; j < propNames.length; j++) {
  33641. var key = propNames[j];
  33642. var mapVal = map[key];
  33643. if (mapVal == null) {
  33644. continue;
  33645. }
  33646. var prop = _Style.properties[key] || _Style.properties[dash2camel(key)];
  33647. if (prop == null) {
  33648. continue;
  33649. }
  33650. var _name = prop.name;
  33651. var _value = mapVal;
  33652. this[i].properties.push({
  33653. name: _name,
  33654. value: _value
  33655. });
  33656. }
  33657. }
  33658. return this; // chaining
  33659. };
  33660. sheetfn.style = sheetfn.css;
  33661. // generate a real style object from the dummy stylesheet
  33662. sheetfn.generateStyle = function (cy) {
  33663. var style = new _Style(cy);
  33664. return this.appendToStyle(style);
  33665. };
  33666. // append a dummy stylesheet object on a real style object
  33667. sheetfn.appendToStyle = function (style) {
  33668. for (var i = 0; i < this.length; i++) {
  33669. var context = this[i];
  33670. var selector = context.selector;
  33671. var props = context.properties;
  33672. style.selector(selector); // apply selector
  33673. for (var j = 0; j < props.length; j++) {
  33674. var prop = props[j];
  33675. style.css(prop.name, prop.value); // apply property
  33676. }
  33677. }
  33678. return style;
  33679. };
  33680. var version = "3.33.2";
  33681. var cytoscape = function cytoscape(options) {
  33682. // if no options specified, use default
  33683. if (options === undefined) {
  33684. options = {};
  33685. }
  33686. // create instance
  33687. if (plainObject(options)) {
  33688. return new Core(options);
  33689. }
  33690. // allow for registration of extensions
  33691. else if (string(options)) {
  33692. return extension.apply(extension, arguments);
  33693. }
  33694. };
  33695. // e.g. cytoscape.use( require('cytoscape-foo'), bar )
  33696. cytoscape.use = function (ext) {
  33697. var args = Array.prototype.slice.call(arguments, 1); // args to pass to ext
  33698. args.unshift(cytoscape); // cytoscape is first arg to ext
  33699. ext.apply(null, args);
  33700. return this;
  33701. };
  33702. cytoscape.warnings = function (bool) {
  33703. return warnings(bool);
  33704. };
  33705. // replaced by build system
  33706. cytoscape.version = version;
  33707. // expose public apis (mostly for extensions)
  33708. cytoscape.stylesheet = cytoscape.Stylesheet = _Stylesheet;
  33709. return cytoscape;
  33710. }));