cytoscape.esm.mjs 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591
  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 _arrayLikeToArray(r, a) {
  23. (null == a || a > r.length) && (a = r.length);
  24. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  25. return n;
  26. }
  27. function _arrayWithHoles(r) {
  28. if (Array.isArray(r)) return r;
  29. }
  30. function _arrayWithoutHoles(r) {
  31. if (Array.isArray(r)) return _arrayLikeToArray(r);
  32. }
  33. function _classCallCheck(a, n) {
  34. if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
  35. }
  36. function _defineProperties(e, r) {
  37. for (var t = 0; t < r.length; t++) {
  38. var o = r[t];
  39. o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  40. }
  41. }
  42. function _createClass(e, r, t) {
  43. return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
  44. writable: false
  45. }), e;
  46. }
  47. function _createForOfIteratorHelper(r, e) {
  48. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  49. if (!t) {
  50. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
  51. t && (r = t);
  52. var n = 0,
  53. F = function () {};
  54. return {
  55. s: F,
  56. n: function () {
  57. return n >= r.length ? {
  58. done: true
  59. } : {
  60. done: false,
  61. value: r[n++]
  62. };
  63. },
  64. e: function (r) {
  65. throw r;
  66. },
  67. f: F
  68. };
  69. }
  70. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  71. }
  72. var o,
  73. a = true,
  74. u = false;
  75. return {
  76. s: function () {
  77. t = t.call(r);
  78. },
  79. n: function () {
  80. var r = t.next();
  81. return a = r.done, r;
  82. },
  83. e: function (r) {
  84. u = true, o = r;
  85. },
  86. f: function () {
  87. try {
  88. a || null == t.return || t.return();
  89. } finally {
  90. if (u) throw o;
  91. }
  92. }
  93. };
  94. }
  95. function _defineProperty$1(e, r, t) {
  96. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  97. value: t,
  98. enumerable: true,
  99. configurable: true,
  100. writable: true
  101. }) : e[r] = t, e;
  102. }
  103. function _iterableToArray(r) {
  104. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  105. }
  106. function _iterableToArrayLimit(r, l) {
  107. var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  108. if (null != t) {
  109. var e,
  110. n,
  111. i,
  112. u,
  113. a = [],
  114. f = true,
  115. o = false;
  116. try {
  117. if (i = (t = t.call(r)).next, 0 === l) {
  118. if (Object(t) !== t) return;
  119. f = !1;
  120. } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
  121. } catch (r) {
  122. o = true, n = r;
  123. } finally {
  124. try {
  125. if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
  126. } finally {
  127. if (o) throw n;
  128. }
  129. }
  130. return a;
  131. }
  132. }
  133. function _nonIterableRest() {
  134. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  135. }
  136. function _nonIterableSpread() {
  137. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  138. }
  139. function _slicedToArray(r, e) {
  140. return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
  141. }
  142. function _toConsumableArray(r) {
  143. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  144. }
  145. function _toPrimitive(t, r) {
  146. if ("object" != typeof t || !t) return t;
  147. var e = t[Symbol.toPrimitive];
  148. if (undefined !== e) {
  149. var i = e.call(t, r);
  150. if ("object" != typeof i) return i;
  151. throw new TypeError("@@toPrimitive must return a primitive value.");
  152. }
  153. return (String )(t);
  154. }
  155. function _toPropertyKey(t) {
  156. var i = _toPrimitive(t, "string");
  157. return "symbol" == typeof i ? i : i + "";
  158. }
  159. function _typeof(o) {
  160. "@babel/helpers - typeof";
  161. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  162. return typeof o;
  163. } : function (o) {
  164. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  165. }, _typeof(o);
  166. }
  167. function _unsupportedIterableToArray(r, a) {
  168. if (r) {
  169. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  170. var t = {}.toString.call(r).slice(8, -1);
  171. 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;
  172. }
  173. }
  174. var _window = typeof window === 'undefined' ? null : window; // eslint-disable-line no-undef
  175. var navigator = _window ? _window.navigator : null;
  176. _window ? _window.document : null;
  177. var typeofstr = _typeof('');
  178. var typeofobj = _typeof({});
  179. var typeoffn = _typeof(function () {});
  180. var typeofhtmlele = typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement);
  181. var instanceStr = function instanceStr(obj) {
  182. return obj && obj.instanceString && fn$6(obj.instanceString) ? obj.instanceString() : null;
  183. };
  184. var string = function string(obj) {
  185. return obj != null && _typeof(obj) == typeofstr;
  186. };
  187. var fn$6 = function fn(obj) {
  188. return obj != null && _typeof(obj) === typeoffn;
  189. };
  190. var array = function array(obj) {
  191. return !elementOrCollection(obj) && (Array.isArray ? Array.isArray(obj) : obj != null && obj instanceof Array);
  192. };
  193. var plainObject = function plainObject(obj) {
  194. return obj != null && _typeof(obj) === typeofobj && !array(obj) && obj.constructor === Object;
  195. };
  196. var object = function object(obj) {
  197. return obj != null && _typeof(obj) === typeofobj;
  198. };
  199. var number$1 = function number(obj) {
  200. return obj != null && _typeof(obj) === _typeof(1) && !isNaN(obj);
  201. };
  202. var integer = function integer(obj) {
  203. return number$1(obj) && Math.floor(obj) === obj;
  204. };
  205. var htmlElement = function htmlElement(obj) {
  206. if ('undefined' === typeofhtmlele) {
  207. return undefined;
  208. } else {
  209. return null != obj && obj instanceof HTMLElement;
  210. }
  211. };
  212. var elementOrCollection = function elementOrCollection(obj) {
  213. return element(obj) || collection(obj);
  214. };
  215. var element = function element(obj) {
  216. return instanceStr(obj) === 'collection' && obj._private.single;
  217. };
  218. var collection = function collection(obj) {
  219. return instanceStr(obj) === 'collection' && !obj._private.single;
  220. };
  221. var core = function core(obj) {
  222. return instanceStr(obj) === 'core';
  223. };
  224. var stylesheet = function stylesheet(obj) {
  225. return instanceStr(obj) === 'stylesheet';
  226. };
  227. var event = function event(obj) {
  228. return instanceStr(obj) === 'event';
  229. };
  230. var emptyString = function emptyString(obj) {
  231. if (obj === undefined || obj === null) {
  232. // null is empty
  233. return true;
  234. } else if (obj === '' || obj.match(/^\s+$/)) {
  235. return true; // empty string is empty
  236. }
  237. return false; // otherwise, we don't know what we've got
  238. };
  239. var domElement = function domElement(obj) {
  240. if (typeof HTMLElement === 'undefined') {
  241. return false; // we're not in a browser so it doesn't matter
  242. } else {
  243. return obj instanceof HTMLElement;
  244. }
  245. };
  246. var boundingBox = function boundingBox(obj) {
  247. return plainObject(obj) && number$1(obj.x1) && number$1(obj.x2) && number$1(obj.y1) && number$1(obj.y2);
  248. };
  249. var promise = function promise(obj) {
  250. return object(obj) && fn$6(obj.then);
  251. };
  252. var ms = function ms() {
  253. return navigator && navigator.userAgent.match(/msie|trident|edge/i);
  254. }; // probably a better way to detect this...
  255. var memoize = function memoize(fn, keyFn) {
  256. if (!keyFn) {
  257. keyFn = function keyFn() {
  258. if (arguments.length === 1) {
  259. return arguments[0];
  260. } else if (arguments.length === 0) {
  261. return 'undefined';
  262. }
  263. var args = [];
  264. for (var i = 0; i < arguments.length; i++) {
  265. args.push(arguments[i]);
  266. }
  267. return args.join('$');
  268. };
  269. }
  270. var _memoizedFn = function memoizedFn() {
  271. var self = this;
  272. var args = arguments;
  273. var ret;
  274. var k = keyFn.apply(self, args);
  275. var cache = _memoizedFn.cache;
  276. if (!(ret = cache[k])) {
  277. ret = cache[k] = fn.apply(self, args);
  278. }
  279. return ret;
  280. };
  281. _memoizedFn.cache = {};
  282. return _memoizedFn;
  283. };
  284. var camel2dash = memoize(function (str) {
  285. return str.replace(/([A-Z])/g, function (v) {
  286. return '-' + v.toLowerCase();
  287. });
  288. });
  289. var dash2camel = memoize(function (str) {
  290. return str.replace(/(-\w)/g, function (v) {
  291. return v[1].toUpperCase();
  292. });
  293. });
  294. var prependCamel = memoize(function (prefix, str) {
  295. return prefix + str[0].toUpperCase() + str.substring(1);
  296. }, function (prefix, str) {
  297. return prefix + '$' + str;
  298. });
  299. var capitalize = function capitalize(str) {
  300. if (emptyString(str)) {
  301. return str;
  302. }
  303. return str.charAt(0).toUpperCase() + str.substring(1);
  304. };
  305. var endsWith = function endsWith(string, suffix) {
  306. return string.slice(-1 * suffix.length) === suffix;
  307. };
  308. var number = '(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))';
  309. var rgba = 'rgb[a]?\\((' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)\\s*,\\s*(' + number + '[%]?)(?:\\s*,\\s*(' + number + '))?\\)';
  310. var rgbaNoBackRefs = 'rgb[a]?\\((?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)\\s*,\\s*(?:' + number + '[%]?)(?:\\s*,\\s*(?:' + number + '))?\\)';
  311. var hsla = 'hsl[a]?\\((' + number + ')\\s*,\\s*(' + number + '[%])\\s*,\\s*(' + number + '[%])(?:\\s*,\\s*(' + number + '))?\\)';
  312. var hslaNoBackRefs = 'hsl[a]?\\((?:' + number + ')\\s*,\\s*(?:' + number + '[%])\\s*,\\s*(?:' + number + '[%])(?:\\s*,\\s*(?:' + number + '))?\\)';
  313. var hex3 = '\\#[0-9a-fA-F]{3}';
  314. var hex6 = '\\#[0-9a-fA-F]{6}';
  315. var ascending = function ascending(a, b) {
  316. if (a < b) {
  317. return -1;
  318. } else if (a > b) {
  319. return 1;
  320. } else {
  321. return 0;
  322. }
  323. };
  324. var descending = function descending(a, b) {
  325. return -1 * ascending(a, b);
  326. };
  327. var extend = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
  328. var args = arguments;
  329. for (var i = 1; i < args.length; i++) {
  330. var obj = args[i];
  331. if (obj == null) {
  332. continue;
  333. }
  334. var keys = Object.keys(obj);
  335. for (var j = 0; j < keys.length; j++) {
  336. var k = keys[j];
  337. tgt[k] = obj[k];
  338. }
  339. }
  340. return tgt;
  341. };
  342. // get [r, g, b] from #abc or #aabbcc
  343. var hex2tuple = function hex2tuple(hex) {
  344. if (!(hex.length === 4 || hex.length === 7) || hex[0] !== '#') {
  345. return;
  346. }
  347. var shortHex = hex.length === 4;
  348. var r, g, b;
  349. var base = 16;
  350. if (shortHex) {
  351. r = parseInt(hex[1] + hex[1], base);
  352. g = parseInt(hex[2] + hex[2], base);
  353. b = parseInt(hex[3] + hex[3], base);
  354. } else {
  355. r = parseInt(hex[1] + hex[2], base);
  356. g = parseInt(hex[3] + hex[4], base);
  357. b = parseInt(hex[5] + hex[6], base);
  358. }
  359. return [r, g, b];
  360. };
  361. // get [r, g, b, a] from hsl(0, 0, 0) or hsla(0, 0, 0, 0)
  362. var hsl2tuple = function hsl2tuple(hsl) {
  363. var ret;
  364. var h, s, l, a, r, g, b;
  365. function hue2rgb(p, q, t) {
  366. if (t < 0) t += 1;
  367. if (t > 1) t -= 1;
  368. if (t < 1 / 6) return p + (q - p) * 6 * t;
  369. if (t < 1 / 2) return q;
  370. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  371. return p;
  372. }
  373. var m = new RegExp('^' + hsla + '$').exec(hsl);
  374. if (m) {
  375. // get hue
  376. h = parseInt(m[1]);
  377. if (h < 0) {
  378. h = (360 - -1 * h % 360) % 360;
  379. } else if (h > 360) {
  380. h = h % 360;
  381. }
  382. h /= 360; // normalise on [0, 1]
  383. s = parseFloat(m[2]);
  384. if (s < 0 || s > 100) {
  385. return;
  386. } // saturation is [0, 100]
  387. s = s / 100; // normalise on [0, 1]
  388. l = parseFloat(m[3]);
  389. if (l < 0 || l > 100) {
  390. return;
  391. } // lightness is [0, 100]
  392. l = l / 100; // normalise on [0, 1]
  393. a = m[4];
  394. if (a !== undefined) {
  395. a = parseFloat(a);
  396. if (a < 0 || a > 1) {
  397. return;
  398. } // alpha is [0, 1]
  399. }
  400. // now, convert to rgb
  401. // code from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  402. if (s === 0) {
  403. r = g = b = Math.round(l * 255); // achromatic
  404. } else {
  405. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  406. var p = 2 * l - q;
  407. r = Math.round(255 * hue2rgb(p, q, h + 1 / 3));
  408. g = Math.round(255 * hue2rgb(p, q, h));
  409. b = Math.round(255 * hue2rgb(p, q, h - 1 / 3));
  410. }
  411. ret = [r, g, b, a];
  412. }
  413. return ret;
  414. };
  415. // get [r, g, b, a] from rgb(0, 0, 0) or rgba(0, 0, 0, 0)
  416. var rgb2tuple = function rgb2tuple(rgb) {
  417. var ret;
  418. var m = new RegExp('^' + rgba + '$').exec(rgb);
  419. if (m) {
  420. ret = [];
  421. var isPct = [];
  422. for (var i = 1; i <= 3; i++) {
  423. var channel = m[i];
  424. if (channel[channel.length - 1] === '%') {
  425. isPct[i] = true;
  426. }
  427. channel = parseFloat(channel);
  428. if (isPct[i]) {
  429. channel = channel / 100 * 255; // normalise to [0, 255]
  430. }
  431. if (channel < 0 || channel > 255) {
  432. return;
  433. } // invalid channel value
  434. ret.push(Math.floor(channel));
  435. }
  436. var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];
  437. var allArePct = isPct[1] && isPct[2] && isPct[3];
  438. if (atLeastOneIsPct && !allArePct) {
  439. return;
  440. } // must all be percent values if one is
  441. var alpha = m[4];
  442. if (alpha !== undefined) {
  443. alpha = parseFloat(alpha);
  444. if (alpha < 0 || alpha > 1) {
  445. return;
  446. } // invalid alpha value
  447. ret.push(alpha);
  448. }
  449. }
  450. return ret;
  451. };
  452. var colorname2tuple = function colorname2tuple(color) {
  453. return colors[color.toLowerCase()];
  454. };
  455. var color2tuple = function color2tuple(color) {
  456. return (array(color) ? color : null) || colorname2tuple(color) || hex2tuple(color) || rgb2tuple(color) || hsl2tuple(color);
  457. };
  458. var colors = {
  459. // special colour names
  460. transparent: [0, 0, 0, 0],
  461. // NB alpha === 0
  462. // regular colours
  463. aliceblue: [240, 248, 255],
  464. antiquewhite: [250, 235, 215],
  465. aqua: [0, 255, 255],
  466. aquamarine: [127, 255, 212],
  467. azure: [240, 255, 255],
  468. beige: [245, 245, 220],
  469. bisque: [255, 228, 196],
  470. black: [0, 0, 0],
  471. blanchedalmond: [255, 235, 205],
  472. blue: [0, 0, 255],
  473. blueviolet: [138, 43, 226],
  474. brown: [165, 42, 42],
  475. burlywood: [222, 184, 135],
  476. cadetblue: [95, 158, 160],
  477. chartreuse: [127, 255, 0],
  478. chocolate: [210, 105, 30],
  479. coral: [255, 127, 80],
  480. cornflowerblue: [100, 149, 237],
  481. cornsilk: [255, 248, 220],
  482. crimson: [220, 20, 60],
  483. cyan: [0, 255, 255],
  484. darkblue: [0, 0, 139],
  485. darkcyan: [0, 139, 139],
  486. darkgoldenrod: [184, 134, 11],
  487. darkgray: [169, 169, 169],
  488. darkgreen: [0, 100, 0],
  489. darkgrey: [169, 169, 169],
  490. darkkhaki: [189, 183, 107],
  491. darkmagenta: [139, 0, 139],
  492. darkolivegreen: [85, 107, 47],
  493. darkorange: [255, 140, 0],
  494. darkorchid: [153, 50, 204],
  495. darkred: [139, 0, 0],
  496. darksalmon: [233, 150, 122],
  497. darkseagreen: [143, 188, 143],
  498. darkslateblue: [72, 61, 139],
  499. darkslategray: [47, 79, 79],
  500. darkslategrey: [47, 79, 79],
  501. darkturquoise: [0, 206, 209],
  502. darkviolet: [148, 0, 211],
  503. deeppink: [255, 20, 147],
  504. deepskyblue: [0, 191, 255],
  505. dimgray: [105, 105, 105],
  506. dimgrey: [105, 105, 105],
  507. dodgerblue: [30, 144, 255],
  508. firebrick: [178, 34, 34],
  509. floralwhite: [255, 250, 240],
  510. forestgreen: [34, 139, 34],
  511. fuchsia: [255, 0, 255],
  512. gainsboro: [220, 220, 220],
  513. ghostwhite: [248, 248, 255],
  514. gold: [255, 215, 0],
  515. goldenrod: [218, 165, 32],
  516. gray: [128, 128, 128],
  517. grey: [128, 128, 128],
  518. green: [0, 128, 0],
  519. greenyellow: [173, 255, 47],
  520. honeydew: [240, 255, 240],
  521. hotpink: [255, 105, 180],
  522. indianred: [205, 92, 92],
  523. indigo: [75, 0, 130],
  524. ivory: [255, 255, 240],
  525. khaki: [240, 230, 140],
  526. lavender: [230, 230, 250],
  527. lavenderblush: [255, 240, 245],
  528. lawngreen: [124, 252, 0],
  529. lemonchiffon: [255, 250, 205],
  530. lightblue: [173, 216, 230],
  531. lightcoral: [240, 128, 128],
  532. lightcyan: [224, 255, 255],
  533. lightgoldenrodyellow: [250, 250, 210],
  534. lightgray: [211, 211, 211],
  535. lightgreen: [144, 238, 144],
  536. lightgrey: [211, 211, 211],
  537. lightpink: [255, 182, 193],
  538. lightsalmon: [255, 160, 122],
  539. lightseagreen: [32, 178, 170],
  540. lightskyblue: [135, 206, 250],
  541. lightslategray: [119, 136, 153],
  542. lightslategrey: [119, 136, 153],
  543. lightsteelblue: [176, 196, 222],
  544. lightyellow: [255, 255, 224],
  545. lime: [0, 255, 0],
  546. limegreen: [50, 205, 50],
  547. linen: [250, 240, 230],
  548. magenta: [255, 0, 255],
  549. maroon: [128, 0, 0],
  550. mediumaquamarine: [102, 205, 170],
  551. mediumblue: [0, 0, 205],
  552. mediumorchid: [186, 85, 211],
  553. mediumpurple: [147, 112, 219],
  554. mediumseagreen: [60, 179, 113],
  555. mediumslateblue: [123, 104, 238],
  556. mediumspringgreen: [0, 250, 154],
  557. mediumturquoise: [72, 209, 204],
  558. mediumvioletred: [199, 21, 133],
  559. midnightblue: [25, 25, 112],
  560. mintcream: [245, 255, 250],
  561. mistyrose: [255, 228, 225],
  562. moccasin: [255, 228, 181],
  563. navajowhite: [255, 222, 173],
  564. navy: [0, 0, 128],
  565. oldlace: [253, 245, 230],
  566. olive: [128, 128, 0],
  567. olivedrab: [107, 142, 35],
  568. orange: [255, 165, 0],
  569. orangered: [255, 69, 0],
  570. orchid: [218, 112, 214],
  571. palegoldenrod: [238, 232, 170],
  572. palegreen: [152, 251, 152],
  573. paleturquoise: [175, 238, 238],
  574. palevioletred: [219, 112, 147],
  575. papayawhip: [255, 239, 213],
  576. peachpuff: [255, 218, 185],
  577. peru: [205, 133, 63],
  578. pink: [255, 192, 203],
  579. plum: [221, 160, 221],
  580. powderblue: [176, 224, 230],
  581. purple: [128, 0, 128],
  582. red: [255, 0, 0],
  583. rosybrown: [188, 143, 143],
  584. royalblue: [65, 105, 225],
  585. saddlebrown: [139, 69, 19],
  586. salmon: [250, 128, 114],
  587. sandybrown: [244, 164, 96],
  588. seagreen: [46, 139, 87],
  589. seashell: [255, 245, 238],
  590. sienna: [160, 82, 45],
  591. silver: [192, 192, 192],
  592. skyblue: [135, 206, 235],
  593. slateblue: [106, 90, 205],
  594. slategray: [112, 128, 144],
  595. slategrey: [112, 128, 144],
  596. snow: [255, 250, 250],
  597. springgreen: [0, 255, 127],
  598. steelblue: [70, 130, 180],
  599. tan: [210, 180, 140],
  600. teal: [0, 128, 128],
  601. thistle: [216, 191, 216],
  602. tomato: [255, 99, 71],
  603. turquoise: [64, 224, 208],
  604. violet: [238, 130, 238],
  605. wheat: [245, 222, 179],
  606. white: [255, 255, 255],
  607. whitesmoke: [245, 245, 245],
  608. yellow: [255, 255, 0],
  609. yellowgreen: [154, 205, 50]
  610. };
  611. // sets the value in a map (map may not be built)
  612. var setMap = function setMap(options) {
  613. var obj = options.map;
  614. var keys = options.keys;
  615. var l = keys.length;
  616. for (var i = 0; i < l; i++) {
  617. var key = keys[i];
  618. if (plainObject(key)) {
  619. throw Error('Tried to set map with object key');
  620. }
  621. if (i < keys.length - 1) {
  622. // extend the map if necessary
  623. if (obj[key] == null) {
  624. obj[key] = {};
  625. }
  626. obj = obj[key];
  627. } else {
  628. // set the value
  629. obj[key] = options.value;
  630. }
  631. }
  632. };
  633. // gets the value in a map even if it's not built in places
  634. var getMap = function getMap(options) {
  635. var obj = options.map;
  636. var keys = options.keys;
  637. var l = keys.length;
  638. for (var i = 0; i < l; i++) {
  639. var key = keys[i];
  640. if (plainObject(key)) {
  641. throw Error('Tried to get map with object key');
  642. }
  643. obj = obj[key];
  644. if (obj == null) {
  645. return obj;
  646. }
  647. }
  648. return obj;
  649. };
  650. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  651. function getDefaultExportFromCjs (x) {
  652. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  653. }
  654. /**
  655. * Checks if `value` is the
  656. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  657. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  658. *
  659. * @static
  660. * @memberOf _
  661. * @since 0.1.0
  662. * @category Lang
  663. * @param {*} value The value to check.
  664. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  665. * @example
  666. *
  667. * _.isObject({});
  668. * // => true
  669. *
  670. * _.isObject([1, 2, 3]);
  671. * // => true
  672. *
  673. * _.isObject(_.noop);
  674. * // => true
  675. *
  676. * _.isObject(null);
  677. * // => false
  678. */
  679. var isObject_1;
  680. var hasRequiredIsObject;
  681. function requireIsObject () {
  682. if (hasRequiredIsObject) return isObject_1;
  683. hasRequiredIsObject = 1;
  684. function isObject(value) {
  685. var type = typeof value;
  686. return value != null && (type == 'object' || type == 'function');
  687. }
  688. isObject_1 = isObject;
  689. return isObject_1;
  690. }
  691. /** Detect free variable `global` from Node.js. */
  692. var _freeGlobal;
  693. var hasRequired_freeGlobal;
  694. function require_freeGlobal () {
  695. if (hasRequired_freeGlobal) return _freeGlobal;
  696. hasRequired_freeGlobal = 1;
  697. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  698. _freeGlobal = freeGlobal;
  699. return _freeGlobal;
  700. }
  701. var _root;
  702. var hasRequired_root;
  703. function require_root () {
  704. if (hasRequired_root) return _root;
  705. hasRequired_root = 1;
  706. var freeGlobal = require_freeGlobal();
  707. /** Detect free variable `self`. */
  708. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  709. /** Used as a reference to the global object. */
  710. var root = freeGlobal || freeSelf || Function('return this')();
  711. _root = root;
  712. return _root;
  713. }
  714. var now_1;
  715. var hasRequiredNow;
  716. function requireNow () {
  717. if (hasRequiredNow) return now_1;
  718. hasRequiredNow = 1;
  719. var root = require_root();
  720. /**
  721. * Gets the timestamp of the number of milliseconds that have elapsed since
  722. * the Unix epoch (1 January 1970 00:00:00 UTC).
  723. *
  724. * @static
  725. * @memberOf _
  726. * @since 2.4.0
  727. * @category Date
  728. * @returns {number} Returns the timestamp.
  729. * @example
  730. *
  731. * _.defer(function(stamp) {
  732. * console.log(_.now() - stamp);
  733. * }, _.now());
  734. * // => Logs the number of milliseconds it took for the deferred invocation.
  735. */
  736. var now = function() {
  737. return root.Date.now();
  738. };
  739. now_1 = now;
  740. return now_1;
  741. }
  742. /** Used to match a single whitespace character. */
  743. var _trimmedEndIndex;
  744. var hasRequired_trimmedEndIndex;
  745. function require_trimmedEndIndex () {
  746. if (hasRequired_trimmedEndIndex) return _trimmedEndIndex;
  747. hasRequired_trimmedEndIndex = 1;
  748. var reWhitespace = /\s/;
  749. /**
  750. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  751. * character of `string`.
  752. *
  753. * @private
  754. * @param {string} string The string to inspect.
  755. * @returns {number} Returns the index of the last non-whitespace character.
  756. */
  757. function trimmedEndIndex(string) {
  758. var index = string.length;
  759. while (index-- && reWhitespace.test(string.charAt(index))) {}
  760. return index;
  761. }
  762. _trimmedEndIndex = trimmedEndIndex;
  763. return _trimmedEndIndex;
  764. }
  765. var _baseTrim;
  766. var hasRequired_baseTrim;
  767. function require_baseTrim () {
  768. if (hasRequired_baseTrim) return _baseTrim;
  769. hasRequired_baseTrim = 1;
  770. var trimmedEndIndex = require_trimmedEndIndex();
  771. /** Used to match leading whitespace. */
  772. var reTrimStart = /^\s+/;
  773. /**
  774. * The base implementation of `_.trim`.
  775. *
  776. * @private
  777. * @param {string} string The string to trim.
  778. * @returns {string} Returns the trimmed string.
  779. */
  780. function baseTrim(string) {
  781. return string
  782. ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  783. : string;
  784. }
  785. _baseTrim = baseTrim;
  786. return _baseTrim;
  787. }
  788. var _Symbol;
  789. var hasRequired_Symbol;
  790. function require_Symbol () {
  791. if (hasRequired_Symbol) return _Symbol;
  792. hasRequired_Symbol = 1;
  793. var root = require_root();
  794. /** Built-in value references. */
  795. var Symbol = root.Symbol;
  796. _Symbol = Symbol;
  797. return _Symbol;
  798. }
  799. var _getRawTag;
  800. var hasRequired_getRawTag;
  801. function require_getRawTag () {
  802. if (hasRequired_getRawTag) return _getRawTag;
  803. hasRequired_getRawTag = 1;
  804. var Symbol = require_Symbol();
  805. /** Used for built-in method references. */
  806. var objectProto = Object.prototype;
  807. /** Used to check objects for own properties. */
  808. var hasOwnProperty = objectProto.hasOwnProperty;
  809. /**
  810. * Used to resolve the
  811. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  812. * of values.
  813. */
  814. var nativeObjectToString = objectProto.toString;
  815. /** Built-in value references. */
  816. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  817. /**
  818. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  819. *
  820. * @private
  821. * @param {*} value The value to query.
  822. * @returns {string} Returns the raw `toStringTag`.
  823. */
  824. function getRawTag(value) {
  825. var isOwn = hasOwnProperty.call(value, symToStringTag),
  826. tag = value[symToStringTag];
  827. try {
  828. value[symToStringTag] = undefined;
  829. var unmasked = true;
  830. } catch (e) {}
  831. var result = nativeObjectToString.call(value);
  832. if (unmasked) {
  833. if (isOwn) {
  834. value[symToStringTag] = tag;
  835. } else {
  836. delete value[symToStringTag];
  837. }
  838. }
  839. return result;
  840. }
  841. _getRawTag = getRawTag;
  842. return _getRawTag;
  843. }
  844. /** Used for built-in method references. */
  845. var _objectToString;
  846. var hasRequired_objectToString;
  847. function require_objectToString () {
  848. if (hasRequired_objectToString) return _objectToString;
  849. hasRequired_objectToString = 1;
  850. var objectProto = Object.prototype;
  851. /**
  852. * Used to resolve the
  853. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  854. * of values.
  855. */
  856. var nativeObjectToString = objectProto.toString;
  857. /**
  858. * Converts `value` to a string using `Object.prototype.toString`.
  859. *
  860. * @private
  861. * @param {*} value The value to convert.
  862. * @returns {string} Returns the converted string.
  863. */
  864. function objectToString(value) {
  865. return nativeObjectToString.call(value);
  866. }
  867. _objectToString = objectToString;
  868. return _objectToString;
  869. }
  870. var _baseGetTag;
  871. var hasRequired_baseGetTag;
  872. function require_baseGetTag () {
  873. if (hasRequired_baseGetTag) return _baseGetTag;
  874. hasRequired_baseGetTag = 1;
  875. var Symbol = require_Symbol(),
  876. getRawTag = require_getRawTag(),
  877. objectToString = require_objectToString();
  878. /** `Object#toString` result references. */
  879. var nullTag = '[object Null]',
  880. undefinedTag = '[object Undefined]';
  881. /** Built-in value references. */
  882. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  883. /**
  884. * The base implementation of `getTag` without fallbacks for buggy environments.
  885. *
  886. * @private
  887. * @param {*} value The value to query.
  888. * @returns {string} Returns the `toStringTag`.
  889. */
  890. function baseGetTag(value) {
  891. if (value == null) {
  892. return value === undefined ? undefinedTag : nullTag;
  893. }
  894. return (symToStringTag && symToStringTag in Object(value))
  895. ? getRawTag(value)
  896. : objectToString(value);
  897. }
  898. _baseGetTag = baseGetTag;
  899. return _baseGetTag;
  900. }
  901. /**
  902. * Checks if `value` is object-like. A value is object-like if it's not `null`
  903. * and has a `typeof` result of "object".
  904. *
  905. * @static
  906. * @memberOf _
  907. * @since 4.0.0
  908. * @category Lang
  909. * @param {*} value The value to check.
  910. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  911. * @example
  912. *
  913. * _.isObjectLike({});
  914. * // => true
  915. *
  916. * _.isObjectLike([1, 2, 3]);
  917. * // => true
  918. *
  919. * _.isObjectLike(_.noop);
  920. * // => false
  921. *
  922. * _.isObjectLike(null);
  923. * // => false
  924. */
  925. var isObjectLike_1;
  926. var hasRequiredIsObjectLike;
  927. function requireIsObjectLike () {
  928. if (hasRequiredIsObjectLike) return isObjectLike_1;
  929. hasRequiredIsObjectLike = 1;
  930. function isObjectLike(value) {
  931. return value != null && typeof value == 'object';
  932. }
  933. isObjectLike_1 = isObjectLike;
  934. return isObjectLike_1;
  935. }
  936. var isSymbol_1;
  937. var hasRequiredIsSymbol;
  938. function requireIsSymbol () {
  939. if (hasRequiredIsSymbol) return isSymbol_1;
  940. hasRequiredIsSymbol = 1;
  941. var baseGetTag = require_baseGetTag(),
  942. isObjectLike = requireIsObjectLike();
  943. /** `Object#toString` result references. */
  944. var symbolTag = '[object Symbol]';
  945. /**
  946. * Checks if `value` is classified as a `Symbol` primitive or object.
  947. *
  948. * @static
  949. * @memberOf _
  950. * @since 4.0.0
  951. * @category Lang
  952. * @param {*} value The value to check.
  953. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  954. * @example
  955. *
  956. * _.isSymbol(Symbol.iterator);
  957. * // => true
  958. *
  959. * _.isSymbol('abc');
  960. * // => false
  961. */
  962. function isSymbol(value) {
  963. return typeof value == 'symbol' ||
  964. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  965. }
  966. isSymbol_1 = isSymbol;
  967. return isSymbol_1;
  968. }
  969. var toNumber_1;
  970. var hasRequiredToNumber;
  971. function requireToNumber () {
  972. if (hasRequiredToNumber) return toNumber_1;
  973. hasRequiredToNumber = 1;
  974. var baseTrim = require_baseTrim(),
  975. isObject = requireIsObject(),
  976. isSymbol = requireIsSymbol();
  977. /** Used as references for various `Number` constants. */
  978. var NAN = 0 / 0;
  979. /** Used to detect bad signed hexadecimal string values. */
  980. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  981. /** Used to detect binary string values. */
  982. var reIsBinary = /^0b[01]+$/i;
  983. /** Used to detect octal string values. */
  984. var reIsOctal = /^0o[0-7]+$/i;
  985. /** Built-in method references without a dependency on `root`. */
  986. var freeParseInt = parseInt;
  987. /**
  988. * Converts `value` to a number.
  989. *
  990. * @static
  991. * @memberOf _
  992. * @since 4.0.0
  993. * @category Lang
  994. * @param {*} value The value to process.
  995. * @returns {number} Returns the number.
  996. * @example
  997. *
  998. * _.toNumber(3.2);
  999. * // => 3.2
  1000. *
  1001. * _.toNumber(Number.MIN_VALUE);
  1002. * // => 5e-324
  1003. *
  1004. * _.toNumber(Infinity);
  1005. * // => Infinity
  1006. *
  1007. * _.toNumber('3.2');
  1008. * // => 3.2
  1009. */
  1010. function toNumber(value) {
  1011. if (typeof value == 'number') {
  1012. return value;
  1013. }
  1014. if (isSymbol(value)) {
  1015. return NAN;
  1016. }
  1017. if (isObject(value)) {
  1018. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1019. value = isObject(other) ? (other + '') : other;
  1020. }
  1021. if (typeof value != 'string') {
  1022. return value === 0 ? value : +value;
  1023. }
  1024. value = baseTrim(value);
  1025. var isBinary = reIsBinary.test(value);
  1026. return (isBinary || reIsOctal.test(value))
  1027. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1028. : (reIsBadHex.test(value) ? NAN : +value);
  1029. }
  1030. toNumber_1 = toNumber;
  1031. return toNumber_1;
  1032. }
  1033. var debounce_1;
  1034. var hasRequiredDebounce;
  1035. function requireDebounce () {
  1036. if (hasRequiredDebounce) return debounce_1;
  1037. hasRequiredDebounce = 1;
  1038. var isObject = requireIsObject(),
  1039. now = requireNow(),
  1040. toNumber = requireToNumber();
  1041. /** Error message constants. */
  1042. var FUNC_ERROR_TEXT = 'Expected a function';
  1043. /* Built-in method references for those with the same name as other `lodash` methods. */
  1044. var nativeMax = Math.max,
  1045. nativeMin = Math.min;
  1046. /**
  1047. * Creates a debounced function that delays invoking `func` until after `wait`
  1048. * milliseconds have elapsed since the last time the debounced function was
  1049. * invoked. The debounced function comes with a `cancel` method to cancel
  1050. * delayed `func` invocations and a `flush` method to immediately invoke them.
  1051. * Provide `options` to indicate whether `func` should be invoked on the
  1052. * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
  1053. * with the last arguments provided to the debounced function. Subsequent
  1054. * calls to the debounced function return the result of the last `func`
  1055. * invocation.
  1056. *
  1057. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  1058. * invoked on the trailing edge of the timeout only if the debounced function
  1059. * is invoked more than once during the `wait` timeout.
  1060. *
  1061. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  1062. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  1063. *
  1064. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  1065. * for details over the differences between `_.debounce` and `_.throttle`.
  1066. *
  1067. * @static
  1068. * @memberOf _
  1069. * @since 0.1.0
  1070. * @category Function
  1071. * @param {Function} func The function to debounce.
  1072. * @param {number} [wait=0] The number of milliseconds to delay.
  1073. * @param {Object} [options={}] The options object.
  1074. * @param {boolean} [options.leading=false]
  1075. * Specify invoking on the leading edge of the timeout.
  1076. * @param {number} [options.maxWait]
  1077. * The maximum time `func` is allowed to be delayed before it's invoked.
  1078. * @param {boolean} [options.trailing=true]
  1079. * Specify invoking on the trailing edge of the timeout.
  1080. * @returns {Function} Returns the new debounced function.
  1081. * @example
  1082. *
  1083. * // Avoid costly calculations while the window size is in flux.
  1084. * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  1085. *
  1086. * // Invoke `sendMail` when clicked, debouncing subsequent calls.
  1087. * jQuery(element).on('click', _.debounce(sendMail, 300, {
  1088. * 'leading': true,
  1089. * 'trailing': false
  1090. * }));
  1091. *
  1092. * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
  1093. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
  1094. * var source = new EventSource('/stream');
  1095. * jQuery(source).on('message', debounced);
  1096. *
  1097. * // Cancel the trailing debounced invocation.
  1098. * jQuery(window).on('popstate', debounced.cancel);
  1099. */
  1100. function debounce(func, wait, options) {
  1101. var lastArgs,
  1102. lastThis,
  1103. maxWait,
  1104. result,
  1105. timerId,
  1106. lastCallTime,
  1107. lastInvokeTime = 0,
  1108. leading = false,
  1109. maxing = false,
  1110. trailing = true;
  1111. if (typeof func != 'function') {
  1112. throw new TypeError(FUNC_ERROR_TEXT);
  1113. }
  1114. wait = toNumber(wait) || 0;
  1115. if (isObject(options)) {
  1116. leading = !!options.leading;
  1117. maxing = 'maxWait' in options;
  1118. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  1119. trailing = 'trailing' in options ? !!options.trailing : trailing;
  1120. }
  1121. function invokeFunc(time) {
  1122. var args = lastArgs,
  1123. thisArg = lastThis;
  1124. lastArgs = lastThis = undefined;
  1125. lastInvokeTime = time;
  1126. result = func.apply(thisArg, args);
  1127. return result;
  1128. }
  1129. function leadingEdge(time) {
  1130. // Reset any `maxWait` timer.
  1131. lastInvokeTime = time;
  1132. // Start the timer for the trailing edge.
  1133. timerId = setTimeout(timerExpired, wait);
  1134. // Invoke the leading edge.
  1135. return leading ? invokeFunc(time) : result;
  1136. }
  1137. function remainingWait(time) {
  1138. var timeSinceLastCall = time - lastCallTime,
  1139. timeSinceLastInvoke = time - lastInvokeTime,
  1140. timeWaiting = wait - timeSinceLastCall;
  1141. return maxing
  1142. ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
  1143. : timeWaiting;
  1144. }
  1145. function shouldInvoke(time) {
  1146. var timeSinceLastCall = time - lastCallTime,
  1147. timeSinceLastInvoke = time - lastInvokeTime;
  1148. // Either this is the first call, activity has stopped and we're at the
  1149. // trailing edge, the system time has gone backwards and we're treating
  1150. // it as the trailing edge, or we've hit the `maxWait` limit.
  1151. return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
  1152. (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  1153. }
  1154. function timerExpired() {
  1155. var time = now();
  1156. if (shouldInvoke(time)) {
  1157. return trailingEdge(time);
  1158. }
  1159. // Restart the timer.
  1160. timerId = setTimeout(timerExpired, remainingWait(time));
  1161. }
  1162. function trailingEdge(time) {
  1163. timerId = undefined;
  1164. // Only invoke if we have `lastArgs` which means `func` has been
  1165. // debounced at least once.
  1166. if (trailing && lastArgs) {
  1167. return invokeFunc(time);
  1168. }
  1169. lastArgs = lastThis = undefined;
  1170. return result;
  1171. }
  1172. function cancel() {
  1173. if (timerId !== undefined) {
  1174. clearTimeout(timerId);
  1175. }
  1176. lastInvokeTime = 0;
  1177. lastArgs = lastCallTime = lastThis = timerId = undefined;
  1178. }
  1179. function flush() {
  1180. return timerId === undefined ? result : trailingEdge(now());
  1181. }
  1182. function debounced() {
  1183. var time = now(),
  1184. isInvoking = shouldInvoke(time);
  1185. lastArgs = arguments;
  1186. lastThis = this;
  1187. lastCallTime = time;
  1188. if (isInvoking) {
  1189. if (timerId === undefined) {
  1190. return leadingEdge(lastCallTime);
  1191. }
  1192. if (maxing) {
  1193. // Handle invocations in a tight loop.
  1194. clearTimeout(timerId);
  1195. timerId = setTimeout(timerExpired, wait);
  1196. return invokeFunc(lastCallTime);
  1197. }
  1198. }
  1199. if (timerId === undefined) {
  1200. timerId = setTimeout(timerExpired, wait);
  1201. }
  1202. return result;
  1203. }
  1204. debounced.cancel = cancel;
  1205. debounced.flush = flush;
  1206. return debounced;
  1207. }
  1208. debounce_1 = debounce;
  1209. return debounce_1;
  1210. }
  1211. var debounceExports = requireDebounce();
  1212. var debounce = /*@__PURE__*/getDefaultExportFromCjs(debounceExports);
  1213. var performance$1 = _window ? _window.performance : null;
  1214. var pnow = performance$1 && performance$1.now ? function () {
  1215. return performance$1.now();
  1216. } : function () {
  1217. return Date.now();
  1218. };
  1219. var raf = function () {
  1220. if (_window) {
  1221. if (_window.requestAnimationFrame) {
  1222. return function (fn) {
  1223. _window.requestAnimationFrame(fn);
  1224. };
  1225. } else if (_window.mozRequestAnimationFrame) {
  1226. return function (fn) {
  1227. _window.mozRequestAnimationFrame(fn);
  1228. };
  1229. } else if (_window.webkitRequestAnimationFrame) {
  1230. return function (fn) {
  1231. _window.webkitRequestAnimationFrame(fn);
  1232. };
  1233. } else if (_window.msRequestAnimationFrame) {
  1234. return function (fn) {
  1235. _window.msRequestAnimationFrame(fn);
  1236. };
  1237. }
  1238. }
  1239. return function (fn) {
  1240. if (fn) {
  1241. setTimeout(function () {
  1242. fn(pnow());
  1243. }, 1000 / 60);
  1244. }
  1245. };
  1246. }();
  1247. var requestAnimationFrame = function requestAnimationFrame(fn) {
  1248. return raf(fn);
  1249. };
  1250. var performanceNow = pnow;
  1251. var DEFAULT_HASH_SEED = 9261;
  1252. var K = 65599; // 37 also works pretty well
  1253. var DEFAULT_HASH_SEED_ALT = 5381;
  1254. var hashIterableInts = function hashIterableInts(iterator) {
  1255. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  1256. // sdbm/string-hash
  1257. var hash = seed;
  1258. var entry;
  1259. for (;;) {
  1260. entry = iterator.next();
  1261. if (entry.done) {
  1262. break;
  1263. }
  1264. hash = hash * K + entry.value | 0;
  1265. }
  1266. return hash;
  1267. };
  1268. var hashInt = function hashInt(num) {
  1269. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED;
  1270. // sdbm/string-hash
  1271. return seed * K + num | 0;
  1272. };
  1273. var hashIntAlt = function hashIntAlt(num) {
  1274. var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_HASH_SEED_ALT;
  1275. // djb2/string-hash
  1276. return (seed << 5) + seed + num | 0;
  1277. };
  1278. var combineHashes = function combineHashes(hash1, hash2) {
  1279. return hash1 * 0x200000 + hash2;
  1280. };
  1281. var combineHashesArray = function combineHashesArray(hashes) {
  1282. return hashes[0] * 0x200000 + hashes[1];
  1283. };
  1284. var hashArrays = function hashArrays(hashes1, hashes2) {
  1285. return [hashInt(hashes1[0], hashes2[0]), hashIntAlt(hashes1[1], hashes2[1])];
  1286. };
  1287. var hashIntsArray = function hashIntsArray(ints, seed) {
  1288. var entry = {
  1289. value: 0,
  1290. done: false
  1291. };
  1292. var i = 0;
  1293. var length = ints.length;
  1294. var iterator = {
  1295. next: function next() {
  1296. if (i < length) {
  1297. entry.value = ints[i++];
  1298. } else {
  1299. entry.done = true;
  1300. }
  1301. return entry;
  1302. }
  1303. };
  1304. return hashIterableInts(iterator, seed);
  1305. };
  1306. var hashString = function hashString(str, seed) {
  1307. var entry = {
  1308. value: 0,
  1309. done: false
  1310. };
  1311. var i = 0;
  1312. var length = str.length;
  1313. var iterator = {
  1314. next: function next() {
  1315. if (i < length) {
  1316. entry.value = str.charCodeAt(i++);
  1317. } else {
  1318. entry.done = true;
  1319. }
  1320. return entry;
  1321. }
  1322. };
  1323. return hashIterableInts(iterator, seed);
  1324. };
  1325. var hashStrings = function hashStrings() {
  1326. return hashStringsArray(arguments);
  1327. };
  1328. var hashStringsArray = function hashStringsArray(strs) {
  1329. var hash;
  1330. for (var i = 0; i < strs.length; i++) {
  1331. var str = strs[i];
  1332. if (i === 0) {
  1333. hash = hashString(str);
  1334. } else {
  1335. hash = hashString(str, hash);
  1336. }
  1337. }
  1338. return hash;
  1339. };
  1340. function rotatePoint(x, y, centerX, centerY, angleDegrees) {
  1341. var angleRadians = angleDegrees * Math.PI / 180;
  1342. var rotatedX = Math.cos(angleRadians) * (x - centerX) - Math.sin(angleRadians) * (y - centerY) + centerX;
  1343. var rotatedY = Math.sin(angleRadians) * (x - centerX) + Math.cos(angleRadians) * (y - centerY) + centerY;
  1344. return {
  1345. x: rotatedX,
  1346. y: rotatedY
  1347. };
  1348. }
  1349. var movePointByBoxAspect = function movePointByBoxAspect(x, y, boxX, boxY, skewX, skewY) {
  1350. return {
  1351. x: (x - boxX) * skewX + boxX,
  1352. y: (y - boxY) * skewY + boxY
  1353. };
  1354. };
  1355. function rotatePosAndSkewByBox(pos, box, angleDegrees) {
  1356. if (angleDegrees === 0) return pos;
  1357. var centerX = (box.x1 + box.x2) / 2;
  1358. var centerY = (box.y1 + box.y2) / 2;
  1359. var skewX = box.w / box.h;
  1360. var skewY = 1 / skewX;
  1361. var rotated = rotatePoint(pos.x, pos.y, centerX, centerY, angleDegrees);
  1362. var skewed = movePointByBoxAspect(rotated.x, rotated.y, centerX, centerY, skewX, skewY);
  1363. return {
  1364. x: skewed.x,
  1365. y: skewed.y
  1366. };
  1367. }
  1368. var warningsEnabled = true;
  1369. var warnSupported = console.warn != null;
  1370. var traceSupported = console.trace != null;
  1371. var MAX_INT$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;
  1372. var trueify = function trueify() {
  1373. return true;
  1374. };
  1375. var falsify = function falsify() {
  1376. return false;
  1377. };
  1378. var zeroify = function zeroify() {
  1379. return 0;
  1380. };
  1381. var noop$1 = function noop() {};
  1382. var error = function error(msg) {
  1383. throw new Error(msg);
  1384. };
  1385. var warnings = function warnings(enabled) {
  1386. if (enabled !== undefined) {
  1387. warningsEnabled = !!enabled;
  1388. } else {
  1389. return warningsEnabled;
  1390. }
  1391. };
  1392. var warn = function warn(msg) {
  1393. if (!warnings()) {
  1394. return;
  1395. }
  1396. if (warnSupported) {
  1397. console.warn(msg);
  1398. } else {
  1399. console.log(msg);
  1400. if (traceSupported) {
  1401. console.trace();
  1402. }
  1403. }
  1404. };
  1405. var clone = function clone(obj) {
  1406. return extend({}, obj);
  1407. };
  1408. // gets a shallow copy of the argument
  1409. var copy = function copy(obj) {
  1410. if (obj == null) {
  1411. return obj;
  1412. }
  1413. if (array(obj)) {
  1414. return obj.slice();
  1415. } else if (plainObject(obj)) {
  1416. return clone(obj);
  1417. } else {
  1418. return obj;
  1419. }
  1420. };
  1421. var copyArray = function copyArray(arr) {
  1422. return arr.slice();
  1423. };
  1424. var uuid = function uuid(a, b /* placeholders */) {
  1425. for (
  1426. // loop :)
  1427. b = a = '';
  1428. // b - result , a - numeric letiable
  1429. a++ < 36;
  1430. //
  1431. b += a * 51 & 52 // if "a" is not 9 or 14 or 19 or 24
  1432. ?
  1433. // return a random number or 4
  1434. (a ^ 15 // if "a" is not 15
  1435. ?
  1436. // generate a random number from 0 to 15
  1437. 8 ^ Math.random() * (a ^ 20 ? 16 : 4) // unless "a" is 20, in which case a random number from 8 to 11
  1438. : 4 // otherwise 4
  1439. ).toString(16) : '-' // in other cases (if "a" is 9,14,19,24) insert "-"
  1440. );
  1441. return b;
  1442. };
  1443. var _staticEmptyObject = {};
  1444. var staticEmptyObject = function staticEmptyObject() {
  1445. return _staticEmptyObject;
  1446. };
  1447. var defaults$g = function defaults(_defaults) {
  1448. var keys = Object.keys(_defaults);
  1449. return function (opts) {
  1450. var filledOpts = {};
  1451. for (var i = 0; i < keys.length; i++) {
  1452. var key = keys[i];
  1453. var optVal = opts == null ? undefined : opts[key];
  1454. filledOpts[key] = optVal === undefined ? _defaults[key] : optVal;
  1455. }
  1456. return filledOpts;
  1457. };
  1458. };
  1459. var removeFromArray = function removeFromArray(arr, ele, oneCopy) {
  1460. for (var i = arr.length - 1; i >= 0; i--) {
  1461. if (arr[i] === ele) {
  1462. arr.splice(i, 1);
  1463. }
  1464. }
  1465. };
  1466. var clearArray = function clearArray(arr) {
  1467. arr.splice(0, arr.length);
  1468. };
  1469. var push = function push(arr, otherArr) {
  1470. for (var i = 0; i < otherArr.length; i++) {
  1471. var el = otherArr[i];
  1472. arr.push(el);
  1473. }
  1474. };
  1475. var getPrefixedProperty = function getPrefixedProperty(obj, propName, prefix) {
  1476. if (prefix) {
  1477. propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  1478. }
  1479. return obj[propName];
  1480. };
  1481. var setPrefixedProperty = function setPrefixedProperty(obj, propName, prefix, value) {
  1482. if (prefix) {
  1483. propName = prependCamel(prefix, propName); // e.g. (labelWidth, source) => sourceLabelWidth
  1484. }
  1485. obj[propName] = value;
  1486. };
  1487. /* global Map */
  1488. var ObjectMap = /*#__PURE__*/function () {
  1489. function ObjectMap() {
  1490. _classCallCheck(this, ObjectMap);
  1491. this._obj = {};
  1492. }
  1493. return _createClass(ObjectMap, [{
  1494. key: "set",
  1495. value: function set(key, val) {
  1496. this._obj[key] = val;
  1497. return this;
  1498. }
  1499. }, {
  1500. key: "delete",
  1501. value: function _delete(key) {
  1502. this._obj[key] = undefined;
  1503. return this;
  1504. }
  1505. }, {
  1506. key: "clear",
  1507. value: function clear() {
  1508. this._obj = {};
  1509. }
  1510. }, {
  1511. key: "has",
  1512. value: function has(key) {
  1513. return this._obj[key] !== undefined;
  1514. }
  1515. }, {
  1516. key: "get",
  1517. value: function get(key) {
  1518. return this._obj[key];
  1519. }
  1520. }]);
  1521. }();
  1522. var Map$1 = typeof Map !== 'undefined' ? Map : ObjectMap;
  1523. /* global Set */
  1524. var undef = "undefined" ;
  1525. var ObjectSet = /*#__PURE__*/function () {
  1526. function ObjectSet(arrayOrObjectSet) {
  1527. _classCallCheck(this, ObjectSet);
  1528. this._obj = Object.create(null);
  1529. this.size = 0;
  1530. if (arrayOrObjectSet != null) {
  1531. var arr;
  1532. if (arrayOrObjectSet.instanceString != null && arrayOrObjectSet.instanceString() === this.instanceString()) {
  1533. arr = arrayOrObjectSet.toArray();
  1534. } else {
  1535. arr = arrayOrObjectSet;
  1536. }
  1537. for (var i = 0; i < arr.length; i++) {
  1538. this.add(arr[i]);
  1539. }
  1540. }
  1541. }
  1542. return _createClass(ObjectSet, [{
  1543. key: "instanceString",
  1544. value: function instanceString() {
  1545. return 'set';
  1546. }
  1547. }, {
  1548. key: "add",
  1549. value: function add(val) {
  1550. var o = this._obj;
  1551. if (o[val] !== 1) {
  1552. o[val] = 1;
  1553. this.size++;
  1554. }
  1555. }
  1556. }, {
  1557. key: "delete",
  1558. value: function _delete(val) {
  1559. var o = this._obj;
  1560. if (o[val] === 1) {
  1561. o[val] = 0;
  1562. this.size--;
  1563. }
  1564. }
  1565. }, {
  1566. key: "clear",
  1567. value: function clear() {
  1568. this._obj = Object.create(null);
  1569. }
  1570. }, {
  1571. key: "has",
  1572. value: function has(val) {
  1573. return this._obj[val] === 1;
  1574. }
  1575. }, {
  1576. key: "toArray",
  1577. value: function toArray() {
  1578. var _this = this;
  1579. return Object.keys(this._obj).filter(function (key) {
  1580. return _this.has(key);
  1581. });
  1582. }
  1583. }, {
  1584. key: "forEach",
  1585. value: function forEach(callback, thisArg) {
  1586. return this.toArray().forEach(callback, thisArg);
  1587. }
  1588. }]);
  1589. }();
  1590. var Set$1 = (typeof Set === "undefined" ? "undefined" : _typeof(Set)) !== undef ? Set : ObjectSet;
  1591. // represents a node or an edge
  1592. var Element = function Element(cy, params) {
  1593. var restore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  1594. if (cy === undefined || params === undefined || !core(cy)) {
  1595. error('An element must have a core reference and parameters set');
  1596. return;
  1597. }
  1598. var group = params.group;
  1599. // try to automatically infer the group if unspecified
  1600. if (group == null) {
  1601. if (params.data && params.data.source != null && params.data.target != null) {
  1602. group = 'edges';
  1603. } else {
  1604. group = 'nodes';
  1605. }
  1606. }
  1607. // validate group
  1608. if (group !== 'nodes' && group !== 'edges') {
  1609. error('An element must be of type `nodes` or `edges`; you specified `' + group + '`');
  1610. return;
  1611. }
  1612. // make the element array-like, just like a collection
  1613. this.length = 1;
  1614. this[0] = this;
  1615. // NOTE: when something is added here, add also to ele.json()
  1616. var _p = this._private = {
  1617. cy: cy,
  1618. single: true,
  1619. // indicates this is an element
  1620. data: params.data || {},
  1621. // data object
  1622. position: params.position || {
  1623. x: 0,
  1624. y: 0
  1625. },
  1626. // (x, y) position pair
  1627. autoWidth: undefined,
  1628. // width and height of nodes calculated by the renderer when set to special 'auto' value
  1629. autoHeight: undefined,
  1630. autoPadding: undefined,
  1631. compoundBoundsClean: false,
  1632. // whether the compound dimensions need to be recalculated the next time dimensions are read
  1633. listeners: [],
  1634. // array of bound listeners
  1635. group: group,
  1636. // string; 'nodes' or 'edges'
  1637. style: {},
  1638. // properties as set by the style
  1639. rstyle: {},
  1640. // properties for style sent from the renderer to the core
  1641. styleCxts: [],
  1642. // applied style contexts from the styler
  1643. styleKeys: {},
  1644. // per-group keys of style property values
  1645. removed: true,
  1646. // whether it's inside the vis; true if removed (set true here since we call restore)
  1647. selected: params.selected ? true : false,
  1648. // whether it's selected
  1649. selectable: params.selectable === undefined ? true : params.selectable ? true : false,
  1650. // whether it's selectable
  1651. locked: params.locked ? true : false,
  1652. // whether the element is locked (cannot be moved)
  1653. grabbed: false,
  1654. // whether the element is grabbed by the mouse; renderer sets this privately
  1655. grabbable: params.grabbable === undefined ? true : params.grabbable ? true : false,
  1656. // whether the element can be grabbed
  1657. pannable: params.pannable === undefined ? group === 'edges' ? true : false : params.pannable ? true : false,
  1658. // whether the element has passthrough panning enabled
  1659. active: false,
  1660. // whether the element is active from user interaction
  1661. classes: new Set$1(),
  1662. // map ( className => true )
  1663. animation: {
  1664. // object for currently-running animations
  1665. current: [],
  1666. queue: []
  1667. },
  1668. rscratch: {},
  1669. // object in which the renderer can store information
  1670. scratch: params.scratch || {},
  1671. // scratch objects
  1672. edges: [],
  1673. // array of connected edges
  1674. children: [],
  1675. // array of children
  1676. parent: params.parent && params.parent.isNode() ? params.parent : null,
  1677. // parent ref
  1678. traversalCache: {},
  1679. // cache of output of traversal functions
  1680. backgrounding: false,
  1681. // whether background images are loading
  1682. bbCache: null,
  1683. // cache of the current bounding box
  1684. bbCacheShift: {
  1685. x: 0,
  1686. y: 0
  1687. },
  1688. // shift applied to cached bb to be applied on next get
  1689. bodyBounds: null,
  1690. // bounds cache of element body, w/o overlay
  1691. overlayBounds: null,
  1692. // bounds cache of element body, including overlay
  1693. labelBounds: {
  1694. // bounds cache of labels
  1695. all: null,
  1696. source: null,
  1697. target: null,
  1698. main: null
  1699. },
  1700. arrowBounds: {
  1701. // bounds cache of edge arrows
  1702. source: null,
  1703. target: null,
  1704. 'mid-source': null,
  1705. 'mid-target': null
  1706. }
  1707. };
  1708. if (_p.position.x == null) {
  1709. _p.position.x = 0;
  1710. }
  1711. if (_p.position.y == null) {
  1712. _p.position.y = 0;
  1713. }
  1714. // renderedPosition overrides if specified
  1715. if (params.renderedPosition) {
  1716. var rpos = params.renderedPosition;
  1717. var pan = cy.pan();
  1718. var zoom = cy.zoom();
  1719. _p.position = {
  1720. x: (rpos.x - pan.x) / zoom,
  1721. y: (rpos.y - pan.y) / zoom
  1722. };
  1723. }
  1724. var classes = [];
  1725. if (array(params.classes)) {
  1726. classes = params.classes;
  1727. } else if (string(params.classes)) {
  1728. classes = params.classes.split(/\s+/);
  1729. }
  1730. for (var i = 0, l = classes.length; i < l; i++) {
  1731. var cls = classes[i];
  1732. if (!cls || cls === '') {
  1733. continue;
  1734. }
  1735. _p.classes.add(cls);
  1736. }
  1737. this.createEmitter();
  1738. if (restore === undefined || restore) {
  1739. this.restore();
  1740. }
  1741. var bypass = params.style || params.css;
  1742. if (bypass) {
  1743. warn('Setting a `style` bypass at element creation should be done only when absolutely necessary. Try to use the stylesheet instead.');
  1744. this.style(bypass);
  1745. }
  1746. };
  1747. var defineSearch = function defineSearch(params) {
  1748. params = {
  1749. bfs: params.bfs || !params.dfs,
  1750. dfs: params.dfs || !params.bfs
  1751. };
  1752. // from pseudocode on wikipedia
  1753. return function searchFn(roots, fn, directed) {
  1754. var options;
  1755. if (plainObject(roots) && !elementOrCollection(roots)) {
  1756. options = roots;
  1757. roots = options.roots || options.root;
  1758. fn = options.visit;
  1759. directed = options.directed;
  1760. }
  1761. directed = arguments.length === 2 && !fn$6(fn) ? fn : directed;
  1762. fn = fn$6(fn) ? fn : function () {};
  1763. var cy = this._private.cy;
  1764. var v = roots = string(roots) ? this.filter(roots) : roots;
  1765. var Q = [];
  1766. var connectedNodes = [];
  1767. var connectedBy = {};
  1768. var id2depth = {};
  1769. var V = {};
  1770. var j = 0;
  1771. var found;
  1772. var _this$byGroup = this.byGroup(),
  1773. nodes = _this$byGroup.nodes,
  1774. edges = _this$byGroup.edges;
  1775. // enqueue v
  1776. for (var i = 0; i < v.length; i++) {
  1777. var vi = v[i];
  1778. var viId = vi.id();
  1779. if (vi.isNode()) {
  1780. Q.unshift(vi);
  1781. if (params.bfs) {
  1782. V[viId] = true;
  1783. connectedNodes.push(vi);
  1784. }
  1785. id2depth[viId] = 0;
  1786. }
  1787. }
  1788. var _loop = function _loop() {
  1789. var v = params.bfs ? Q.shift() : Q.pop();
  1790. var vId = v.id();
  1791. if (params.dfs) {
  1792. if (V[vId]) {
  1793. return 0; // continue
  1794. }
  1795. V[vId] = true;
  1796. connectedNodes.push(v);
  1797. }
  1798. var depth = id2depth[vId];
  1799. var prevEdge = connectedBy[vId];
  1800. var src = prevEdge != null ? prevEdge.source() : null;
  1801. var tgt = prevEdge != null ? prevEdge.target() : null;
  1802. var prevNode = prevEdge == null ? undefined : v.same(src) ? tgt[0] : src[0];
  1803. var ret;
  1804. ret = fn(v, prevEdge, prevNode, j++, depth);
  1805. if (ret === true) {
  1806. found = v;
  1807. return 1; // break
  1808. }
  1809. if (ret === false) {
  1810. return 1; // break
  1811. }
  1812. var vwEdges = v.connectedEdges().filter(function (e) {
  1813. return (!directed || e.source().same(v)) && edges.has(e);
  1814. });
  1815. for (var _i2 = 0; _i2 < vwEdges.length; _i2++) {
  1816. var e = vwEdges[_i2];
  1817. var w = e.connectedNodes().filter(function (n) {
  1818. return !n.same(v) && nodes.has(n);
  1819. });
  1820. var wId = w.id();
  1821. if (w.length !== 0 && !V[wId]) {
  1822. w = w[0];
  1823. Q.push(w);
  1824. if (params.bfs) {
  1825. V[wId] = true;
  1826. connectedNodes.push(w);
  1827. }
  1828. connectedBy[wId] = e;
  1829. id2depth[wId] = id2depth[vId] + 1;
  1830. }
  1831. }
  1832. },
  1833. _ret;
  1834. while (Q.length !== 0) {
  1835. _ret = _loop();
  1836. if (_ret === 0) continue;
  1837. if (_ret === 1) break;
  1838. }
  1839. var connectedEles = cy.collection();
  1840. for (var _i = 0; _i < connectedNodes.length; _i++) {
  1841. var node = connectedNodes[_i];
  1842. var edge = connectedBy[node.id()];
  1843. if (edge != null) {
  1844. connectedEles.push(edge);
  1845. }
  1846. connectedEles.push(node);
  1847. }
  1848. return {
  1849. path: cy.collection(connectedEles),
  1850. found: cy.collection(found)
  1851. };
  1852. };
  1853. };
  1854. // search, spanning trees, etc
  1855. var elesfn$v = {
  1856. breadthFirstSearch: defineSearch({
  1857. bfs: true
  1858. }),
  1859. depthFirstSearch: defineSearch({
  1860. dfs: true
  1861. })
  1862. };
  1863. // nice, short mathematical alias
  1864. elesfn$v.bfs = elesfn$v.breadthFirstSearch;
  1865. elesfn$v.dfs = elesfn$v.depthFirstSearch;
  1866. var heap$2 = {exports: {}};
  1867. var heap$1 = heap$2.exports;
  1868. var hasRequiredHeap$1;
  1869. function requireHeap$1 () {
  1870. if (hasRequiredHeap$1) return heap$2.exports;
  1871. hasRequiredHeap$1 = 1;
  1872. (function (module, exports) {
  1873. // Generated by CoffeeScript 1.8.0
  1874. (function() {
  1875. var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
  1876. floor = Math.floor, min = Math.min;
  1877. /*
  1878. Default comparison function to be used
  1879. */
  1880. defaultCmp = function(x, y) {
  1881. if (x < y) {
  1882. return -1;
  1883. }
  1884. if (x > y) {
  1885. return 1;
  1886. }
  1887. return 0;
  1888. };
  1889. /*
  1890. Insert item x in list a, and keep it sorted assuming a is sorted.
  1891. If x is already in a, insert it to the right of the rightmost x.
  1892. Optional args lo (default 0) and hi (default a.length) bound the slice
  1893. of a to be searched.
  1894. */
  1895. insort = function(a, x, lo, hi, cmp) {
  1896. var mid;
  1897. if (lo == null) {
  1898. lo = 0;
  1899. }
  1900. if (cmp == null) {
  1901. cmp = defaultCmp;
  1902. }
  1903. if (lo < 0) {
  1904. throw new Error('lo must be non-negative');
  1905. }
  1906. if (hi == null) {
  1907. hi = a.length;
  1908. }
  1909. while (lo < hi) {
  1910. mid = floor((lo + hi) / 2);
  1911. if (cmp(x, a[mid]) < 0) {
  1912. hi = mid;
  1913. } else {
  1914. lo = mid + 1;
  1915. }
  1916. }
  1917. return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
  1918. };
  1919. /*
  1920. Push item onto heap, maintaining the heap invariant.
  1921. */
  1922. heappush = function(array, item, cmp) {
  1923. if (cmp == null) {
  1924. cmp = defaultCmp;
  1925. }
  1926. array.push(item);
  1927. return _siftdown(array, 0, array.length - 1, cmp);
  1928. };
  1929. /*
  1930. Pop the smallest item off the heap, maintaining the heap invariant.
  1931. */
  1932. heappop = function(array, cmp) {
  1933. var lastelt, returnitem;
  1934. if (cmp == null) {
  1935. cmp = defaultCmp;
  1936. }
  1937. lastelt = array.pop();
  1938. if (array.length) {
  1939. returnitem = array[0];
  1940. array[0] = lastelt;
  1941. _siftup(array, 0, cmp);
  1942. } else {
  1943. returnitem = lastelt;
  1944. }
  1945. return returnitem;
  1946. };
  1947. /*
  1948. Pop and return the current smallest value, and add the new item.
  1949. This is more efficient than heappop() followed by heappush(), and can be
  1950. more appropriate when using a fixed size heap. Note that the value
  1951. returned may be larger than item! That constrains reasonable use of
  1952. this routine unless written as part of a conditional replacement:
  1953. if item > array[0]
  1954. item = heapreplace(array, item)
  1955. */
  1956. heapreplace = function(array, item, cmp) {
  1957. var returnitem;
  1958. if (cmp == null) {
  1959. cmp = defaultCmp;
  1960. }
  1961. returnitem = array[0];
  1962. array[0] = item;
  1963. _siftup(array, 0, cmp);
  1964. return returnitem;
  1965. };
  1966. /*
  1967. Fast version of a heappush followed by a heappop.
  1968. */
  1969. heappushpop = function(array, item, cmp) {
  1970. var _ref;
  1971. if (cmp == null) {
  1972. cmp = defaultCmp;
  1973. }
  1974. if (array.length && cmp(array[0], item) < 0) {
  1975. _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
  1976. _siftup(array, 0, cmp);
  1977. }
  1978. return item;
  1979. };
  1980. /*
  1981. Transform list into a heap, in-place, in O(array.length) time.
  1982. */
  1983. heapify = function(array, cmp) {
  1984. var i, _i, _len, _ref1, _results, _results1;
  1985. if (cmp == null) {
  1986. cmp = defaultCmp;
  1987. }
  1988. _ref1 = (function() {
  1989. _results1 = [];
  1990. for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
  1991. return _results1;
  1992. }).apply(this).reverse();
  1993. _results = [];
  1994. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  1995. i = _ref1[_i];
  1996. _results.push(_siftup(array, i, cmp));
  1997. }
  1998. return _results;
  1999. };
  2000. /*
  2001. Update the position of the given item in the heap.
  2002. This function should be called every time the item is being modified.
  2003. */
  2004. updateItem = function(array, item, cmp) {
  2005. var pos;
  2006. if (cmp == null) {
  2007. cmp = defaultCmp;
  2008. }
  2009. pos = array.indexOf(item);
  2010. if (pos === -1) {
  2011. return;
  2012. }
  2013. _siftdown(array, 0, pos, cmp);
  2014. return _siftup(array, pos, cmp);
  2015. };
  2016. /*
  2017. Find the n largest elements in a dataset.
  2018. */
  2019. nlargest = function(array, n, cmp) {
  2020. var elem, result, _i, _len, _ref;
  2021. if (cmp == null) {
  2022. cmp = defaultCmp;
  2023. }
  2024. result = array.slice(0, n);
  2025. if (!result.length) {
  2026. return result;
  2027. }
  2028. heapify(result, cmp);
  2029. _ref = array.slice(n);
  2030. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2031. elem = _ref[_i];
  2032. heappushpop(result, elem, cmp);
  2033. }
  2034. return result.sort(cmp).reverse();
  2035. };
  2036. /*
  2037. Find the n smallest elements in a dataset.
  2038. */
  2039. nsmallest = function(array, n, cmp) {
  2040. var elem, los, result, _i, _j, _len, _ref, _ref1, _results;
  2041. if (cmp == null) {
  2042. cmp = defaultCmp;
  2043. }
  2044. if (n * 10 <= array.length) {
  2045. result = array.slice(0, n).sort(cmp);
  2046. if (!result.length) {
  2047. return result;
  2048. }
  2049. los = result[result.length - 1];
  2050. _ref = array.slice(n);
  2051. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  2052. elem = _ref[_i];
  2053. if (cmp(elem, los) < 0) {
  2054. insort(result, elem, 0, null, cmp);
  2055. result.pop();
  2056. los = result[result.length - 1];
  2057. }
  2058. }
  2059. return result;
  2060. }
  2061. heapify(array, cmp);
  2062. _results = [];
  2063. for (_j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; 0 <= _ref1 ? ++_j : --_j) {
  2064. _results.push(heappop(array, cmp));
  2065. }
  2066. return _results;
  2067. };
  2068. _siftdown = function(array, startpos, pos, cmp) {
  2069. var newitem, parent, parentpos;
  2070. if (cmp == null) {
  2071. cmp = defaultCmp;
  2072. }
  2073. newitem = array[pos];
  2074. while (pos > startpos) {
  2075. parentpos = (pos - 1) >> 1;
  2076. parent = array[parentpos];
  2077. if (cmp(newitem, parent) < 0) {
  2078. array[pos] = parent;
  2079. pos = parentpos;
  2080. continue;
  2081. }
  2082. break;
  2083. }
  2084. return array[pos] = newitem;
  2085. };
  2086. _siftup = function(array, pos, cmp) {
  2087. var childpos, endpos, newitem, rightpos, startpos;
  2088. if (cmp == null) {
  2089. cmp = defaultCmp;
  2090. }
  2091. endpos = array.length;
  2092. startpos = pos;
  2093. newitem = array[pos];
  2094. childpos = 2 * pos + 1;
  2095. while (childpos < endpos) {
  2096. rightpos = childpos + 1;
  2097. if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
  2098. childpos = rightpos;
  2099. }
  2100. array[pos] = array[childpos];
  2101. pos = childpos;
  2102. childpos = 2 * pos + 1;
  2103. }
  2104. array[pos] = newitem;
  2105. return _siftdown(array, startpos, pos, cmp);
  2106. };
  2107. Heap = (function() {
  2108. Heap.push = heappush;
  2109. Heap.pop = heappop;
  2110. Heap.replace = heapreplace;
  2111. Heap.pushpop = heappushpop;
  2112. Heap.heapify = heapify;
  2113. Heap.updateItem = updateItem;
  2114. Heap.nlargest = nlargest;
  2115. Heap.nsmallest = nsmallest;
  2116. function Heap(cmp) {
  2117. this.cmp = cmp != null ? cmp : defaultCmp;
  2118. this.nodes = [];
  2119. }
  2120. Heap.prototype.push = function(x) {
  2121. return heappush(this.nodes, x, this.cmp);
  2122. };
  2123. Heap.prototype.pop = function() {
  2124. return heappop(this.nodes, this.cmp);
  2125. };
  2126. Heap.prototype.peek = function() {
  2127. return this.nodes[0];
  2128. };
  2129. Heap.prototype.contains = function(x) {
  2130. return this.nodes.indexOf(x) !== -1;
  2131. };
  2132. Heap.prototype.replace = function(x) {
  2133. return heapreplace(this.nodes, x, this.cmp);
  2134. };
  2135. Heap.prototype.pushpop = function(x) {
  2136. return heappushpop(this.nodes, x, this.cmp);
  2137. };
  2138. Heap.prototype.heapify = function() {
  2139. return heapify(this.nodes, this.cmp);
  2140. };
  2141. Heap.prototype.updateItem = function(x) {
  2142. return updateItem(this.nodes, x, this.cmp);
  2143. };
  2144. Heap.prototype.clear = function() {
  2145. return this.nodes = [];
  2146. };
  2147. Heap.prototype.empty = function() {
  2148. return this.nodes.length === 0;
  2149. };
  2150. Heap.prototype.size = function() {
  2151. return this.nodes.length;
  2152. };
  2153. Heap.prototype.clone = function() {
  2154. var heap;
  2155. heap = new Heap();
  2156. heap.nodes = this.nodes.slice(0);
  2157. return heap;
  2158. };
  2159. Heap.prototype.toArray = function() {
  2160. return this.nodes.slice(0);
  2161. };
  2162. Heap.prototype.insert = Heap.prototype.push;
  2163. Heap.prototype.top = Heap.prototype.peek;
  2164. Heap.prototype.front = Heap.prototype.peek;
  2165. Heap.prototype.has = Heap.prototype.contains;
  2166. Heap.prototype.copy = Heap.prototype.clone;
  2167. return Heap;
  2168. })();
  2169. (function(root, factory) {
  2170. {
  2171. return module.exports = factory();
  2172. }
  2173. })(this, function() {
  2174. return Heap;
  2175. });
  2176. }).call(heap$1);
  2177. } (heap$2));
  2178. return heap$2.exports;
  2179. }
  2180. var heap;
  2181. var hasRequiredHeap;
  2182. function requireHeap () {
  2183. if (hasRequiredHeap) return heap;
  2184. hasRequiredHeap = 1;
  2185. heap = requireHeap$1();
  2186. return heap;
  2187. }
  2188. var heapExports = requireHeap();
  2189. var Heap = /*@__PURE__*/getDefaultExportFromCjs(heapExports);
  2190. var dijkstraDefaults = defaults$g({
  2191. root: null,
  2192. weight: function weight(edge) {
  2193. return 1;
  2194. },
  2195. directed: false
  2196. });
  2197. var elesfn$u = {
  2198. dijkstra: function dijkstra(options) {
  2199. if (!plainObject(options)) {
  2200. var args = arguments;
  2201. options = {
  2202. root: args[0],
  2203. weight: args[1],
  2204. directed: args[2]
  2205. };
  2206. }
  2207. var _dijkstraDefaults = dijkstraDefaults(options),
  2208. root = _dijkstraDefaults.root,
  2209. weight = _dijkstraDefaults.weight,
  2210. directed = _dijkstraDefaults.directed;
  2211. var eles = this;
  2212. var weightFn = weight;
  2213. var source = string(root) ? this.filter(root)[0] : root[0];
  2214. var dist = {};
  2215. var prev = {};
  2216. var knownDist = {};
  2217. var _this$byGroup = this.byGroup(),
  2218. nodes = _this$byGroup.nodes,
  2219. edges = _this$byGroup.edges;
  2220. edges.unmergeBy(function (ele) {
  2221. return ele.isLoop();
  2222. });
  2223. var getDist = function getDist(node) {
  2224. return dist[node.id()];
  2225. };
  2226. var setDist = function setDist(node, d) {
  2227. dist[node.id()] = d;
  2228. Q.updateItem(node);
  2229. };
  2230. var Q = new Heap(function (a, b) {
  2231. return getDist(a) - getDist(b);
  2232. });
  2233. for (var i = 0; i < nodes.length; i++) {
  2234. var node = nodes[i];
  2235. dist[node.id()] = node.same(source) ? 0 : Infinity;
  2236. Q.push(node);
  2237. }
  2238. var distBetween = function distBetween(u, v) {
  2239. var uvs = (directed ? u.edgesTo(v) : u.edgesWith(v)).intersect(edges);
  2240. var smallestDistance = Infinity;
  2241. var smallestEdge;
  2242. for (var _i = 0; _i < uvs.length; _i++) {
  2243. var edge = uvs[_i];
  2244. var _weight = weightFn(edge);
  2245. if (_weight < smallestDistance || !smallestEdge) {
  2246. smallestDistance = _weight;
  2247. smallestEdge = edge;
  2248. }
  2249. }
  2250. return {
  2251. edge: smallestEdge,
  2252. dist: smallestDistance
  2253. };
  2254. };
  2255. while (Q.size() > 0) {
  2256. var u = Q.pop();
  2257. var smalletsDist = getDist(u);
  2258. var uid = u.id();
  2259. knownDist[uid] = smalletsDist;
  2260. if (smalletsDist === Infinity) {
  2261. continue;
  2262. }
  2263. var neighbors = u.neighborhood().intersect(nodes);
  2264. for (var _i2 = 0; _i2 < neighbors.length; _i2++) {
  2265. var v = neighbors[_i2];
  2266. var vid = v.id();
  2267. var vDist = distBetween(u, v);
  2268. var alt = smalletsDist + vDist.dist;
  2269. if (alt < getDist(v)) {
  2270. setDist(v, alt);
  2271. prev[vid] = {
  2272. node: u,
  2273. edge: vDist.edge
  2274. };
  2275. }
  2276. } // for
  2277. } // while
  2278. return {
  2279. distanceTo: function distanceTo(node) {
  2280. var target = string(node) ? nodes.filter(node)[0] : node[0];
  2281. return knownDist[target.id()];
  2282. },
  2283. pathTo: function pathTo(node) {
  2284. var target = string(node) ? nodes.filter(node)[0] : node[0];
  2285. var S = [];
  2286. var u = target;
  2287. var uid = u.id();
  2288. if (target.length > 0) {
  2289. S.unshift(target);
  2290. while (prev[uid]) {
  2291. var p = prev[uid];
  2292. S.unshift(p.edge);
  2293. S.unshift(p.node);
  2294. u = p.node;
  2295. uid = u.id();
  2296. }
  2297. }
  2298. return eles.spawn(S);
  2299. }
  2300. };
  2301. }
  2302. };
  2303. var elesfn$t = {
  2304. // kruskal's algorithm (finds min spanning tree, assuming undirected graph)
  2305. // implemented from pseudocode from wikipedia
  2306. kruskal: function kruskal(weightFn) {
  2307. weightFn = weightFn || function (edge) {
  2308. return 1;
  2309. };
  2310. var _this$byGroup = this.byGroup(),
  2311. nodes = _this$byGroup.nodes,
  2312. edges = _this$byGroup.edges;
  2313. var numNodes = nodes.length;
  2314. var forest = new Array(numNodes);
  2315. var A = nodes; // assumes byGroup() creates new collections that can be safely mutated
  2316. var findSetIndex = function findSetIndex(ele) {
  2317. for (var i = 0; i < forest.length; i++) {
  2318. var eles = forest[i];
  2319. if (eles.has(ele)) {
  2320. return i;
  2321. }
  2322. }
  2323. };
  2324. // start with one forest per node
  2325. for (var i = 0; i < numNodes; i++) {
  2326. forest[i] = this.spawn(nodes[i]);
  2327. }
  2328. var S = edges.sort(function (a, b) {
  2329. return weightFn(a) - weightFn(b);
  2330. });
  2331. for (var _i = 0; _i < S.length; _i++) {
  2332. var edge = S[_i];
  2333. var u = edge.source()[0];
  2334. var v = edge.target()[0];
  2335. var setUIndex = findSetIndex(u);
  2336. var setVIndex = findSetIndex(v);
  2337. var setU = forest[setUIndex];
  2338. var setV = forest[setVIndex];
  2339. if (setUIndex !== setVIndex) {
  2340. A.merge(edge);
  2341. // combine forests for u and v
  2342. setU.merge(setV);
  2343. forest.splice(setVIndex, 1);
  2344. }
  2345. }
  2346. return A;
  2347. }
  2348. };
  2349. var aStarDefaults = defaults$g({
  2350. root: null,
  2351. goal: null,
  2352. weight: function weight(edge) {
  2353. return 1;
  2354. },
  2355. heuristic: function heuristic(edge) {
  2356. return 0;
  2357. },
  2358. directed: false
  2359. });
  2360. var elesfn$s = {
  2361. // Implemented from pseudocode from wikipedia
  2362. aStar: function aStar(options) {
  2363. var cy = this.cy();
  2364. var _aStarDefaults = aStarDefaults(options),
  2365. root = _aStarDefaults.root,
  2366. goal = _aStarDefaults.goal,
  2367. heuristic = _aStarDefaults.heuristic,
  2368. directed = _aStarDefaults.directed,
  2369. weight = _aStarDefaults.weight;
  2370. root = cy.collection(root)[0];
  2371. goal = cy.collection(goal)[0];
  2372. var sid = root.id();
  2373. var tid = goal.id();
  2374. var gScore = {};
  2375. var fScore = {};
  2376. var closedSetIds = {};
  2377. var openSet = new Heap(function (a, b) {
  2378. return fScore[a.id()] - fScore[b.id()];
  2379. });
  2380. var openSetIds = new Set$1();
  2381. var cameFrom = {};
  2382. var cameFromEdge = {};
  2383. var addToOpenSet = function addToOpenSet(ele, id) {
  2384. openSet.push(ele);
  2385. openSetIds.add(id);
  2386. };
  2387. var cMin, cMinId;
  2388. var popFromOpenSet = function popFromOpenSet() {
  2389. cMin = openSet.pop();
  2390. cMinId = cMin.id();
  2391. openSetIds["delete"](cMinId);
  2392. };
  2393. var isInOpenSet = function isInOpenSet(id) {
  2394. return openSetIds.has(id);
  2395. };
  2396. addToOpenSet(root, sid);
  2397. gScore[sid] = 0;
  2398. fScore[sid] = heuristic(root);
  2399. // Counter
  2400. var steps = 0;
  2401. // Main loop
  2402. while (openSet.size() > 0) {
  2403. popFromOpenSet();
  2404. steps++;
  2405. // If we've found our goal, then we are done
  2406. if (cMinId === tid) {
  2407. var path = [];
  2408. var pathNode = goal;
  2409. var pathNodeId = tid;
  2410. var pathEdge = cameFromEdge[pathNodeId];
  2411. for (;;) {
  2412. path.unshift(pathNode);
  2413. if (pathEdge != null) {
  2414. path.unshift(pathEdge);
  2415. }
  2416. pathNode = cameFrom[pathNodeId];
  2417. if (pathNode == null) {
  2418. break;
  2419. }
  2420. pathNodeId = pathNode.id();
  2421. pathEdge = cameFromEdge[pathNodeId];
  2422. }
  2423. return {
  2424. found: true,
  2425. distance: gScore[cMinId],
  2426. path: this.spawn(path),
  2427. steps: steps
  2428. };
  2429. }
  2430. // Add cMin to processed nodes
  2431. closedSetIds[cMinId] = true;
  2432. // Update scores for neighbors of cMin
  2433. // Take into account if graph is directed or not
  2434. var vwEdges = cMin._private.edges;
  2435. for (var i = 0; i < vwEdges.length; i++) {
  2436. var e = vwEdges[i];
  2437. // edge must be in set of calling eles
  2438. if (!this.hasElementWithId(e.id())) {
  2439. continue;
  2440. }
  2441. // cMin must be the source of edge if directed
  2442. if (directed && e.data('source') !== cMinId) {
  2443. continue;
  2444. }
  2445. var wSrc = e.source();
  2446. var wTgt = e.target();
  2447. var w = wSrc.id() !== cMinId ? wSrc : wTgt;
  2448. var wid = w.id();
  2449. // node must be in set of calling eles
  2450. if (!this.hasElementWithId(wid)) {
  2451. continue;
  2452. }
  2453. // if node is in closedSet, ignore it
  2454. if (closedSetIds[wid]) {
  2455. continue;
  2456. }
  2457. // New tentative score for node w
  2458. var tempScore = gScore[cMinId] + weight(e);
  2459. // Update gScore for node w if:
  2460. // w not present in openSet
  2461. // OR
  2462. // tentative gScore is less than previous value
  2463. // w not in openSet
  2464. if (!isInOpenSet(wid)) {
  2465. gScore[wid] = tempScore;
  2466. fScore[wid] = tempScore + heuristic(w);
  2467. addToOpenSet(w, wid);
  2468. cameFrom[wid] = cMin;
  2469. cameFromEdge[wid] = e;
  2470. continue;
  2471. }
  2472. // w already in openSet, but with greater gScore
  2473. if (tempScore < gScore[wid]) {
  2474. gScore[wid] = tempScore;
  2475. fScore[wid] = tempScore + heuristic(w);
  2476. cameFrom[wid] = cMin;
  2477. cameFromEdge[wid] = e;
  2478. }
  2479. } // End of neighbors update
  2480. } // End of main loop
  2481. // If we've reached here, then we've not reached our goal
  2482. return {
  2483. found: false,
  2484. distance: undefined,
  2485. path: undefined,
  2486. steps: steps
  2487. };
  2488. }
  2489. }; // elesfn
  2490. var floydWarshallDefaults = defaults$g({
  2491. weight: function weight(edge) {
  2492. return 1;
  2493. },
  2494. directed: false
  2495. });
  2496. var elesfn$r = {
  2497. // Implemented from pseudocode from wikipedia
  2498. floydWarshall: function floydWarshall(options) {
  2499. var cy = this.cy();
  2500. var _floydWarshallDefault = floydWarshallDefaults(options),
  2501. weight = _floydWarshallDefault.weight,
  2502. directed = _floydWarshallDefault.directed;
  2503. var weightFn = weight;
  2504. var _this$byGroup = this.byGroup(),
  2505. nodes = _this$byGroup.nodes,
  2506. edges = _this$byGroup.edges;
  2507. var N = nodes.length;
  2508. var Nsq = N * N;
  2509. var indexOf = function indexOf(node) {
  2510. return nodes.indexOf(node);
  2511. };
  2512. var atIndex = function atIndex(i) {
  2513. return nodes[i];
  2514. };
  2515. // Initialize distance matrix
  2516. var dist = new Array(Nsq);
  2517. for (var n = 0; n < Nsq; n++) {
  2518. var j = n % N;
  2519. var i = (n - j) / N;
  2520. if (i === j) {
  2521. dist[n] = 0;
  2522. } else {
  2523. dist[n] = Infinity;
  2524. }
  2525. }
  2526. // Initialize matrix used for path reconstruction
  2527. // Initialize distance matrix
  2528. var next = new Array(Nsq);
  2529. var edgeNext = new Array(Nsq);
  2530. // Process edges
  2531. for (var _i = 0; _i < edges.length; _i++) {
  2532. var edge = edges[_i];
  2533. var src = edge.source()[0];
  2534. var tgt = edge.target()[0];
  2535. if (src === tgt) {
  2536. continue;
  2537. } // exclude loops
  2538. var s = indexOf(src);
  2539. var t = indexOf(tgt);
  2540. var st = s * N + t; // source to target index
  2541. var _weight = weightFn(edge);
  2542. // Check if already process another edge between same 2 nodes
  2543. if (dist[st] > _weight) {
  2544. dist[st] = _weight;
  2545. next[st] = t;
  2546. edgeNext[st] = edge;
  2547. }
  2548. // If undirected graph, process 'reversed' edge
  2549. if (!directed) {
  2550. var ts = t * N + s; // target to source index
  2551. if (!directed && dist[ts] > _weight) {
  2552. dist[ts] = _weight;
  2553. next[ts] = s;
  2554. edgeNext[ts] = edge;
  2555. }
  2556. }
  2557. }
  2558. // Main loop
  2559. for (var k = 0; k < N; k++) {
  2560. for (var _i2 = 0; _i2 < N; _i2++) {
  2561. var ik = _i2 * N + k;
  2562. for (var _j = 0; _j < N; _j++) {
  2563. var ij = _i2 * N + _j;
  2564. var kj = k * N + _j;
  2565. if (dist[ik] + dist[kj] < dist[ij]) {
  2566. dist[ij] = dist[ik] + dist[kj];
  2567. next[ij] = next[ik];
  2568. }
  2569. }
  2570. }
  2571. }
  2572. var getArgEle = function getArgEle(ele) {
  2573. return (string(ele) ? cy.filter(ele) : ele)[0];
  2574. };
  2575. var indexOfArgEle = function indexOfArgEle(ele) {
  2576. return indexOf(getArgEle(ele));
  2577. };
  2578. var res = {
  2579. distance: function distance(from, to) {
  2580. var i = indexOfArgEle(from);
  2581. var j = indexOfArgEle(to);
  2582. return dist[i * N + j];
  2583. },
  2584. path: function path(from, to) {
  2585. var i = indexOfArgEle(from);
  2586. var j = indexOfArgEle(to);
  2587. var fromNode = atIndex(i);
  2588. if (i === j) {
  2589. return fromNode.collection();
  2590. }
  2591. if (next[i * N + j] == null) {
  2592. return cy.collection();
  2593. }
  2594. var path = cy.collection();
  2595. var prev = i;
  2596. var edge;
  2597. path.merge(fromNode);
  2598. while (i !== j) {
  2599. prev = i;
  2600. i = next[i * N + j];
  2601. edge = edgeNext[prev * N + i];
  2602. path.merge(edge);
  2603. path.merge(atIndex(i));
  2604. }
  2605. return path;
  2606. }
  2607. };
  2608. return res;
  2609. } // floydWarshall
  2610. }; // elesfn
  2611. var bellmanFordDefaults = defaults$g({
  2612. weight: function weight(edge) {
  2613. return 1;
  2614. },
  2615. directed: false,
  2616. root: null
  2617. });
  2618. var elesfn$q = {
  2619. // Implemented from pseudocode from wikipedia
  2620. bellmanFord: function bellmanFord(options) {
  2621. var _this = this;
  2622. var _bellmanFordDefaults = bellmanFordDefaults(options),
  2623. weight = _bellmanFordDefaults.weight,
  2624. directed = _bellmanFordDefaults.directed,
  2625. root = _bellmanFordDefaults.root;
  2626. var weightFn = weight;
  2627. var eles = this;
  2628. var cy = this.cy();
  2629. var _this$byGroup = this.byGroup(),
  2630. edges = _this$byGroup.edges,
  2631. nodes = _this$byGroup.nodes;
  2632. var numNodes = nodes.length;
  2633. var infoMap = new Map$1();
  2634. var hasNegativeWeightCycle = false;
  2635. var negativeWeightCycles = [];
  2636. root = cy.collection(root)[0]; // in case selector passed
  2637. edges.unmergeBy(function (edge) {
  2638. return edge.isLoop();
  2639. });
  2640. var numEdges = edges.length;
  2641. var getInfo = function getInfo(node) {
  2642. var obj = infoMap.get(node.id());
  2643. if (!obj) {
  2644. obj = {};
  2645. infoMap.set(node.id(), obj);
  2646. }
  2647. return obj;
  2648. };
  2649. var getNodeFromTo = function getNodeFromTo(to) {
  2650. return (string(to) ? cy.$(to) : to)[0];
  2651. };
  2652. var distanceTo = function distanceTo(to) {
  2653. return getInfo(getNodeFromTo(to)).dist;
  2654. };
  2655. var pathTo = function pathTo(to) {
  2656. var thisStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;
  2657. var end = getNodeFromTo(to);
  2658. var path = [];
  2659. var node = end;
  2660. for (;;) {
  2661. if (node == null) {
  2662. return _this.spawn();
  2663. }
  2664. var _getInfo = getInfo(node),
  2665. edge = _getInfo.edge,
  2666. pred = _getInfo.pred;
  2667. path.unshift(node[0]);
  2668. if (node.same(thisStart) && path.length > 0) {
  2669. break;
  2670. }
  2671. if (edge != null) {
  2672. path.unshift(edge);
  2673. }
  2674. node = pred;
  2675. }
  2676. return eles.spawn(path);
  2677. };
  2678. // Initializations { dist, pred, edge }
  2679. for (var i = 0; i < numNodes; i++) {
  2680. var node = nodes[i];
  2681. var info = getInfo(node);
  2682. if (node.same(root)) {
  2683. info.dist = 0;
  2684. } else {
  2685. info.dist = Infinity;
  2686. }
  2687. info.pred = null;
  2688. info.edge = null;
  2689. }
  2690. // Edges relaxation
  2691. var replacedEdge = false;
  2692. var checkForEdgeReplacement = function checkForEdgeReplacement(node1, node2, edge, info1, info2, weight) {
  2693. var dist = info1.dist + weight;
  2694. if (dist < info2.dist && !edge.same(info1.edge)) {
  2695. info2.dist = dist;
  2696. info2.pred = node1;
  2697. info2.edge = edge;
  2698. replacedEdge = true;
  2699. }
  2700. };
  2701. for (var _i = 1; _i < numNodes; _i++) {
  2702. replacedEdge = false;
  2703. for (var e = 0; e < numEdges; e++) {
  2704. var edge = edges[e];
  2705. var src = edge.source();
  2706. var tgt = edge.target();
  2707. var _weight = weightFn(edge);
  2708. var srcInfo = getInfo(src);
  2709. var tgtInfo = getInfo(tgt);
  2710. checkForEdgeReplacement(src, tgt, edge, srcInfo, tgtInfo, _weight);
  2711. // If undirected graph, we need to take into account the 'reverse' edge
  2712. if (!directed) {
  2713. checkForEdgeReplacement(tgt, src, edge, tgtInfo, srcInfo, _weight);
  2714. }
  2715. }
  2716. if (!replacedEdge) {
  2717. break;
  2718. }
  2719. }
  2720. if (replacedEdge) {
  2721. // Check for negative weight cycles
  2722. var negativeWeightCycleIds = [];
  2723. for (var _e = 0; _e < numEdges; _e++) {
  2724. var _edge = edges[_e];
  2725. var _src = _edge.source();
  2726. var _tgt = _edge.target();
  2727. var _weight2 = weightFn(_edge);
  2728. var srcDist = getInfo(_src).dist;
  2729. var tgtDist = getInfo(_tgt).dist;
  2730. if (srcDist + _weight2 < tgtDist || !directed && tgtDist + _weight2 < srcDist) {
  2731. if (!hasNegativeWeightCycle) {
  2732. warn('Graph contains a negative weight cycle for Bellman-Ford');
  2733. hasNegativeWeightCycle = true;
  2734. }
  2735. if (options.findNegativeWeightCycles !== false) {
  2736. var negativeNodes = [];
  2737. if (srcDist + _weight2 < tgtDist) {
  2738. negativeNodes.push(_src);
  2739. }
  2740. if (!directed && tgtDist + _weight2 < srcDist) {
  2741. negativeNodes.push(_tgt);
  2742. }
  2743. var numNegativeNodes = negativeNodes.length;
  2744. for (var n = 0; n < numNegativeNodes; n++) {
  2745. var start = negativeNodes[n];
  2746. var cycle = [start];
  2747. cycle.push(getInfo(start).edge);
  2748. var _node = getInfo(start).pred;
  2749. while (cycle.indexOf(_node) === -1) {
  2750. cycle.push(_node);
  2751. cycle.push(getInfo(_node).edge);
  2752. _node = getInfo(_node).pred;
  2753. }
  2754. cycle = cycle.slice(cycle.indexOf(_node));
  2755. var smallestId = cycle[0].id();
  2756. var smallestIndex = 0;
  2757. for (var c = 2; c < cycle.length; c += 2) {
  2758. if (cycle[c].id() < smallestId) {
  2759. smallestId = cycle[c].id();
  2760. smallestIndex = c;
  2761. }
  2762. }
  2763. cycle = cycle.slice(smallestIndex).concat(cycle.slice(0, smallestIndex));
  2764. cycle.push(cycle[0]);
  2765. var cycleId = cycle.map(function (el) {
  2766. return el.id();
  2767. }).join(",");
  2768. if (negativeWeightCycleIds.indexOf(cycleId) === -1) {
  2769. negativeWeightCycles.push(eles.spawn(cycle));
  2770. negativeWeightCycleIds.push(cycleId);
  2771. }
  2772. }
  2773. } else {
  2774. break;
  2775. }
  2776. }
  2777. }
  2778. }
  2779. return {
  2780. distanceTo: distanceTo,
  2781. pathTo: pathTo,
  2782. hasNegativeWeightCycle: hasNegativeWeightCycle,
  2783. negativeWeightCycles: negativeWeightCycles
  2784. };
  2785. } // bellmanFord
  2786. }; // elesfn
  2787. var sqrt2 = Math.sqrt(2);
  2788. // Function which colapses 2 (meta) nodes into one
  2789. // Updates the remaining edge lists
  2790. // Receives as a paramater the edge which causes the collapse
  2791. var collapse = function collapse(edgeIndex, nodeMap, remainingEdges) {
  2792. if (remainingEdges.length === 0) {
  2793. error("Karger-Stein must be run on a connected (sub)graph");
  2794. }
  2795. var edgeInfo = remainingEdges[edgeIndex];
  2796. var sourceIn = edgeInfo[1];
  2797. var targetIn = edgeInfo[2];
  2798. var partition1 = nodeMap[sourceIn];
  2799. var partition2 = nodeMap[targetIn];
  2800. var newEdges = remainingEdges; // re-use array
  2801. // Delete all edges between partition1 and partition2
  2802. for (var i = newEdges.length - 1; i >= 0; i--) {
  2803. var edge = newEdges[i];
  2804. var src = edge[1];
  2805. var tgt = edge[2];
  2806. if (nodeMap[src] === partition1 && nodeMap[tgt] === partition2 || nodeMap[src] === partition2 && nodeMap[tgt] === partition1) {
  2807. newEdges.splice(i, 1);
  2808. }
  2809. }
  2810. // All edges pointing to partition2 should now point to partition1
  2811. for (var _i = 0; _i < newEdges.length; _i++) {
  2812. var _edge = newEdges[_i];
  2813. if (_edge[1] === partition2) {
  2814. // Check source
  2815. newEdges[_i] = _edge.slice(); // copy
  2816. newEdges[_i][1] = partition1;
  2817. } else if (_edge[2] === partition2) {
  2818. // Check target
  2819. newEdges[_i] = _edge.slice(); // copy
  2820. newEdges[_i][2] = partition1;
  2821. }
  2822. }
  2823. // Move all nodes from partition2 to partition1
  2824. for (var _i2 = 0; _i2 < nodeMap.length; _i2++) {
  2825. if (nodeMap[_i2] === partition2) {
  2826. nodeMap[_i2] = partition1;
  2827. }
  2828. }
  2829. return newEdges;
  2830. };
  2831. // Contracts a graph until we reach a certain number of meta nodes
  2832. var contractUntil = function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) {
  2833. while (size > sizeLimit) {
  2834. // Choose an edge randomly
  2835. var edgeIndex = Math.floor(Math.random() * remainingEdges.length);
  2836. // Collapse graph based on edge
  2837. remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges);
  2838. size--;
  2839. }
  2840. return remainingEdges;
  2841. };
  2842. var elesfn$p = {
  2843. // Computes the minimum cut of an undirected graph
  2844. // Returns the correct answer with high probability
  2845. kargerStein: function kargerStein() {
  2846. var _this = this;
  2847. var _this$byGroup = this.byGroup(),
  2848. nodes = _this$byGroup.nodes,
  2849. edges = _this$byGroup.edges;
  2850. edges.unmergeBy(function (edge) {
  2851. return edge.isLoop();
  2852. });
  2853. var numNodes = nodes.length;
  2854. var numEdges = edges.length;
  2855. var numIter = Math.ceil(Math.pow(Math.log(numNodes) / Math.LN2, 2));
  2856. var stopSize = Math.floor(numNodes / sqrt2);
  2857. if (numNodes < 2) {
  2858. error('At least 2 nodes are required for Karger-Stein algorithm');
  2859. return undefined;
  2860. }
  2861. // Now store edge destination as indexes
  2862. // Format for each edge (edge index, source node index, target node index)
  2863. var edgeIndexes = [];
  2864. for (var i = 0; i < numEdges; i++) {
  2865. var e = edges[i];
  2866. edgeIndexes.push([i, nodes.indexOf(e.source()), nodes.indexOf(e.target())]);
  2867. }
  2868. // We will store the best cut found here
  2869. var minCutSize = Infinity;
  2870. var minCutEdgeIndexes = [];
  2871. var minCutNodeMap = new Array(numNodes);
  2872. // Initial meta node partition
  2873. var metaNodeMap = new Array(numNodes);
  2874. var metaNodeMap2 = new Array(numNodes);
  2875. var copyNodesMap = function copyNodesMap(from, to) {
  2876. for (var _i3 = 0; _i3 < numNodes; _i3++) {
  2877. to[_i3] = from[_i3];
  2878. }
  2879. };
  2880. // Main loop
  2881. for (var iter = 0; iter <= numIter; iter++) {
  2882. // Reset meta node partition
  2883. for (var _i4 = 0; _i4 < numNodes; _i4++) {
  2884. metaNodeMap[_i4] = _i4;
  2885. }
  2886. // Contract until stop point (stopSize nodes)
  2887. var edgesState = contractUntil(metaNodeMap, edgeIndexes.slice(), numNodes, stopSize);
  2888. var edgesState2 = edgesState.slice(); // copy
  2889. // Create a copy of the colapsed nodes state
  2890. copyNodesMap(metaNodeMap, metaNodeMap2);
  2891. // Run 2 iterations starting in the stop state
  2892. var res1 = contractUntil(metaNodeMap, edgesState, stopSize, 2);
  2893. var res2 = contractUntil(metaNodeMap2, edgesState2, stopSize, 2);
  2894. // Is any of the 2 results the best cut so far?
  2895. if (res1.length <= res2.length && res1.length < minCutSize) {
  2896. minCutSize = res1.length;
  2897. minCutEdgeIndexes = res1;
  2898. copyNodesMap(metaNodeMap, minCutNodeMap);
  2899. } else if (res2.length <= res1.length && res2.length < minCutSize) {
  2900. minCutSize = res2.length;
  2901. minCutEdgeIndexes = res2;
  2902. copyNodesMap(metaNodeMap2, minCutNodeMap);
  2903. }
  2904. } // end of main loop
  2905. // Construct result
  2906. var cut = this.spawn(minCutEdgeIndexes.map(function (e) {
  2907. return edges[e[0]];
  2908. }));
  2909. var partition1 = this.spawn();
  2910. var partition2 = this.spawn();
  2911. // traverse metaNodeMap for best cut
  2912. var witnessNodePartition = minCutNodeMap[0];
  2913. for (var _i5 = 0; _i5 < minCutNodeMap.length; _i5++) {
  2914. var partitionId = minCutNodeMap[_i5];
  2915. var node = nodes[_i5];
  2916. if (partitionId === witnessNodePartition) {
  2917. partition1.merge(node);
  2918. } else {
  2919. partition2.merge(node);
  2920. }
  2921. }
  2922. // construct components corresponding to each disjoint subset of nodes
  2923. var constructComponent = function constructComponent(subset) {
  2924. var component = _this.spawn();
  2925. subset.forEach(function (node) {
  2926. component.merge(node);
  2927. node.connectedEdges().forEach(function (edge) {
  2928. // ensure edge is within calling collection and edge is not in cut
  2929. if (_this.contains(edge) && !cut.contains(edge)) {
  2930. component.merge(edge);
  2931. }
  2932. });
  2933. });
  2934. return component;
  2935. };
  2936. var components = [constructComponent(partition1), constructComponent(partition2)];
  2937. var ret = {
  2938. cut: cut,
  2939. components: components,
  2940. // n.b. partitions are included to be compatible with the old api spec
  2941. // (could be removed in a future major version)
  2942. partition1: partition1,
  2943. partition2: partition2
  2944. };
  2945. return ret;
  2946. }
  2947. }; // elesfn
  2948. var _Math$hypot;
  2949. var copyPosition = function copyPosition(p) {
  2950. return {
  2951. x: p.x,
  2952. y: p.y
  2953. };
  2954. };
  2955. var modelToRenderedPosition$1 = function modelToRenderedPosition(p, zoom, pan) {
  2956. return {
  2957. x: p.x * zoom + pan.x,
  2958. y: p.y * zoom + pan.y
  2959. };
  2960. };
  2961. var renderedToModelPosition = function renderedToModelPosition(p, zoom, pan) {
  2962. return {
  2963. x: (p.x - pan.x) / zoom,
  2964. y: (p.y - pan.y) / zoom
  2965. };
  2966. };
  2967. var array2point = function array2point(arr) {
  2968. return {
  2969. x: arr[0],
  2970. y: arr[1]
  2971. };
  2972. };
  2973. var min = function min(arr) {
  2974. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2975. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  2976. var min = Infinity;
  2977. for (var i = begin; i < end; i++) {
  2978. var val = arr[i];
  2979. if (isFinite(val)) {
  2980. min = Math.min(val, min);
  2981. }
  2982. }
  2983. return min;
  2984. };
  2985. var max = function max(arr) {
  2986. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2987. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  2988. var max = -Infinity;
  2989. for (var i = begin; i < end; i++) {
  2990. var val = arr[i];
  2991. if (isFinite(val)) {
  2992. max = Math.max(val, max);
  2993. }
  2994. }
  2995. return max;
  2996. };
  2997. var mean = function mean(arr) {
  2998. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  2999. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  3000. var total = 0;
  3001. var n = 0;
  3002. for (var i = begin; i < end; i++) {
  3003. var val = arr[i];
  3004. if (isFinite(val)) {
  3005. total += val;
  3006. n++;
  3007. }
  3008. }
  3009. return total / n;
  3010. };
  3011. var median = function median(arr) {
  3012. var begin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3013. var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : arr.length;
  3014. var copy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  3015. var sort = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  3016. var includeHoles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  3017. if (copy) {
  3018. arr = arr.slice(begin, end);
  3019. } else {
  3020. if (end < arr.length) {
  3021. arr.splice(end, arr.length - end);
  3022. }
  3023. if (begin > 0) {
  3024. arr.splice(0, begin);
  3025. }
  3026. }
  3027. // all non finite (e.g. Infinity, NaN) elements must be -Infinity so they go to the start
  3028. var off = 0; // offset from non-finite values
  3029. for (var i = arr.length - 1; i >= 0; i--) {
  3030. var v = arr[i];
  3031. if (includeHoles) {
  3032. if (!isFinite(v)) {
  3033. arr[i] = -Infinity;
  3034. off++;
  3035. }
  3036. } else {
  3037. // just remove it if we don't want to consider holes
  3038. arr.splice(i, 1);
  3039. }
  3040. }
  3041. if (sort) {
  3042. arr.sort(function (a, b) {
  3043. return a - b;
  3044. }); // requires copy = true if you don't want to change the orig
  3045. }
  3046. var len = arr.length;
  3047. var mid = Math.floor(len / 2);
  3048. if (len % 2 !== 0) {
  3049. return arr[mid + 1 + off];
  3050. } else {
  3051. return (arr[mid - 1 + off] + arr[mid + off]) / 2;
  3052. }
  3053. };
  3054. var deg2rad = function deg2rad(deg) {
  3055. return Math.PI * deg / 180;
  3056. };
  3057. var getAngleFromDisp = function getAngleFromDisp(dispX, dispY) {
  3058. return Math.atan2(dispY, dispX) - Math.PI / 2;
  3059. };
  3060. var log2 = Math.log2 || function (n) {
  3061. return Math.log(n) / Math.log(2);
  3062. };
  3063. var signum = function signum(x) {
  3064. if (x > 0) {
  3065. return 1;
  3066. } else if (x < 0) {
  3067. return -1;
  3068. } else {
  3069. return 0;
  3070. }
  3071. };
  3072. var dist = function dist(p1, p2) {
  3073. return Math.sqrt(sqdist(p1, p2));
  3074. };
  3075. var sqdist = function sqdist(p1, p2) {
  3076. var dx = p2.x - p1.x;
  3077. var dy = p2.y - p1.y;
  3078. return dx * dx + dy * dy;
  3079. };
  3080. var inPlaceSumNormalize = function inPlaceSumNormalize(v) {
  3081. var length = v.length;
  3082. // First, get sum of all elements
  3083. var total = 0;
  3084. for (var i = 0; i < length; i++) {
  3085. total += v[i];
  3086. }
  3087. // Now, divide each by the sum of all elements
  3088. for (var _i = 0; _i < length; _i++) {
  3089. v[_i] = v[_i] / total;
  3090. }
  3091. return v;
  3092. };
  3093. // from http://en.wikipedia.org/wiki/Bézier_curve#Quadratic_curves
  3094. var qbezierAt = function qbezierAt(p0, p1, p2, t) {
  3095. return (1 - t) * (1 - t) * p0 + 2 * (1 - t) * t * p1 + t * t * p2;
  3096. };
  3097. var qbezierPtAt = function qbezierPtAt(p0, p1, p2, t) {
  3098. return {
  3099. x: qbezierAt(p0.x, p1.x, p2.x, t),
  3100. y: qbezierAt(p0.y, p1.y, p2.y, t)
  3101. };
  3102. };
  3103. var lineAt = function lineAt(p0, p1, t, d) {
  3104. var vec = {
  3105. x: p1.x - p0.x,
  3106. y: p1.y - p0.y
  3107. };
  3108. var vecDist = dist(p0, p1);
  3109. var normVec = {
  3110. x: vec.x / vecDist,
  3111. y: vec.y / vecDist
  3112. };
  3113. t = t == null ? 0 : t;
  3114. d = d != null ? d : t * vecDist;
  3115. return {
  3116. x: p0.x + normVec.x * d,
  3117. y: p0.y + normVec.y * d
  3118. };
  3119. };
  3120. var bound = function bound(min, val, max) {
  3121. return Math.max(min, Math.min(max, val));
  3122. };
  3123. // makes a full bb (x1, y1, x2, y2, w, h) from implicit params
  3124. var makeBoundingBox = function makeBoundingBox(bb) {
  3125. if (bb == null) {
  3126. return {
  3127. x1: Infinity,
  3128. y1: Infinity,
  3129. x2: -Infinity,
  3130. y2: -Infinity,
  3131. w: 0,
  3132. h: 0
  3133. };
  3134. } else if (bb.x1 != null && bb.y1 != null) {
  3135. if (bb.x2 != null && bb.y2 != null && bb.x2 >= bb.x1 && bb.y2 >= bb.y1) {
  3136. return {
  3137. x1: bb.x1,
  3138. y1: bb.y1,
  3139. x2: bb.x2,
  3140. y2: bb.y2,
  3141. w: bb.x2 - bb.x1,
  3142. h: bb.y2 - bb.y1
  3143. };
  3144. } else if (bb.w != null && bb.h != null && bb.w >= 0 && bb.h >= 0) {
  3145. return {
  3146. x1: bb.x1,
  3147. y1: bb.y1,
  3148. x2: bb.x1 + bb.w,
  3149. y2: bb.y1 + bb.h,
  3150. w: bb.w,
  3151. h: bb.h
  3152. };
  3153. }
  3154. }
  3155. };
  3156. var copyBoundingBox = function copyBoundingBox(bb) {
  3157. return {
  3158. x1: bb.x1,
  3159. x2: bb.x2,
  3160. w: bb.w,
  3161. y1: bb.y1,
  3162. y2: bb.y2,
  3163. h: bb.h
  3164. };
  3165. };
  3166. var clearBoundingBox = function clearBoundingBox(bb) {
  3167. bb.x1 = Infinity;
  3168. bb.y1 = Infinity;
  3169. bb.x2 = -Infinity;
  3170. bb.y2 = -Infinity;
  3171. bb.w = 0;
  3172. bb.h = 0;
  3173. };
  3174. var updateBoundingBox = function updateBoundingBox(bb1, bb2) {
  3175. // update bb1 with bb2 bounds
  3176. bb1.x1 = Math.min(bb1.x1, bb2.x1);
  3177. bb1.x2 = Math.max(bb1.x2, bb2.x2);
  3178. bb1.w = bb1.x2 - bb1.x1;
  3179. bb1.y1 = Math.min(bb1.y1, bb2.y1);
  3180. bb1.y2 = Math.max(bb1.y2, bb2.y2);
  3181. bb1.h = bb1.y2 - bb1.y1;
  3182. };
  3183. var expandBoundingBoxByPoint = function expandBoundingBoxByPoint(bb, x, y) {
  3184. bb.x1 = Math.min(bb.x1, x);
  3185. bb.x2 = Math.max(bb.x2, x);
  3186. bb.w = bb.x2 - bb.x1;
  3187. bb.y1 = Math.min(bb.y1, y);
  3188. bb.y2 = Math.max(bb.y2, y);
  3189. bb.h = bb.y2 - bb.y1;
  3190. };
  3191. var expandBoundingBox = function expandBoundingBox(bb) {
  3192. var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3193. bb.x1 -= padding;
  3194. bb.x2 += padding;
  3195. bb.y1 -= padding;
  3196. bb.y2 += padding;
  3197. bb.w = bb.x2 - bb.x1;
  3198. bb.h = bb.y2 - bb.y1;
  3199. return bb;
  3200. };
  3201. var expandBoundingBoxSides = function expandBoundingBoxSides(bb) {
  3202. var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0];
  3203. var top, right, bottom, left;
  3204. if (padding.length === 1) {
  3205. top = right = bottom = left = padding[0];
  3206. } else if (padding.length === 2) {
  3207. top = bottom = padding[0];
  3208. left = right = padding[1];
  3209. } else if (padding.length === 4) {
  3210. var _padding = _slicedToArray(padding, 4);
  3211. top = _padding[0];
  3212. right = _padding[1];
  3213. bottom = _padding[2];
  3214. left = _padding[3];
  3215. }
  3216. bb.x1 -= left;
  3217. bb.x2 += right;
  3218. bb.y1 -= top;
  3219. bb.y2 += bottom;
  3220. bb.w = bb.x2 - bb.x1;
  3221. bb.h = bb.y2 - bb.y1;
  3222. return bb;
  3223. };
  3224. // assign the values of bb2 into bb1
  3225. var assignBoundingBox = function assignBoundingBox(bb1, bb2) {
  3226. bb1.x1 = bb2.x1;
  3227. bb1.y1 = bb2.y1;
  3228. bb1.x2 = bb2.x2;
  3229. bb1.y2 = bb2.y2;
  3230. bb1.w = bb1.x2 - bb1.x1;
  3231. bb1.h = bb1.y2 - bb1.y1;
  3232. };
  3233. var boundingBoxesIntersect = function boundingBoxesIntersect(bb1, bb2) {
  3234. // case: one bb to right of other
  3235. if (bb1.x1 > bb2.x2) {
  3236. return false;
  3237. }
  3238. if (bb2.x1 > bb1.x2) {
  3239. return false;
  3240. }
  3241. // case: one bb to left of other
  3242. if (bb1.x2 < bb2.x1) {
  3243. return false;
  3244. }
  3245. if (bb2.x2 < bb1.x1) {
  3246. return false;
  3247. }
  3248. // case: one bb above other
  3249. if (bb1.y2 < bb2.y1) {
  3250. return false;
  3251. }
  3252. if (bb2.y2 < bb1.y1) {
  3253. return false;
  3254. }
  3255. // case: one bb below other
  3256. if (bb1.y1 > bb2.y2) {
  3257. return false;
  3258. }
  3259. if (bb2.y1 > bb1.y2) {
  3260. return false;
  3261. }
  3262. // otherwise, must have some overlap
  3263. return true;
  3264. };
  3265. var inBoundingBox = function inBoundingBox(bb, x, y) {
  3266. return bb.x1 <= x && x <= bb.x2 && bb.y1 <= y && y <= bb.y2;
  3267. };
  3268. var pointInBoundingBox = function pointInBoundingBox(bb, pt) {
  3269. return inBoundingBox(bb, pt.x, pt.y);
  3270. };
  3271. var boundingBoxInBoundingBox = function boundingBoxInBoundingBox(bb1, bb2) {
  3272. return inBoundingBox(bb1, bb2.x1, bb2.y1) && inBoundingBox(bb1, bb2.x2, bb2.y2);
  3273. };
  3274. var hypot = (_Math$hypot = Math.hypot) !== null && _Math$hypot !== undefined ? _Math$hypot : function (x, y) {
  3275. return Math.sqrt(x * x + y * y);
  3276. };
  3277. function inflatePolygon(polygon, d) {
  3278. if (polygon.length < 3) {
  3279. throw new Error('Need at least 3 vertices');
  3280. }
  3281. // Helpers
  3282. var add = function add(a, b) {
  3283. return {
  3284. x: a.x + b.x,
  3285. y: a.y + b.y
  3286. };
  3287. };
  3288. var sub = function sub(a, b) {
  3289. return {
  3290. x: a.x - b.x,
  3291. y: a.y - b.y
  3292. };
  3293. };
  3294. var scale = function scale(v, s) {
  3295. return {
  3296. x: v.x * s,
  3297. y: v.y * s
  3298. };
  3299. };
  3300. var cross = function cross(u, v) {
  3301. return u.x * v.y - u.y * v.x;
  3302. };
  3303. var normalize = function normalize(v) {
  3304. var len = hypot(v.x, v.y);
  3305. return len === 0 ? {
  3306. x: 0,
  3307. y: 0
  3308. } : {
  3309. x: v.x / len,
  3310. y: v.y / len
  3311. };
  3312. };
  3313. // Signed area (positive = CCW)
  3314. var signedArea = function signedArea(pts) {
  3315. var A = 0;
  3316. for (var i = 0; i < pts.length; i++) {
  3317. var p = pts[i],
  3318. q = pts[(i + 1) % pts.length];
  3319. A += p.x * q.y - q.x * p.y;
  3320. }
  3321. return A / 2;
  3322. };
  3323. // Line–line intersection (infinite lines)
  3324. var intersectLines = function intersectLines(p1, p2, p3, p4) {
  3325. var r = sub(p2, p1);
  3326. var s = sub(p4, p3);
  3327. var denom = cross(r, s);
  3328. if (Math.abs(denom) < 1e-9) {
  3329. // Parallel or nearly so — fallback to midpoint
  3330. return add(p1, scale(r, 0.5));
  3331. }
  3332. var t = cross(sub(p3, p1), s) / denom;
  3333. return add(p1, scale(r, t));
  3334. };
  3335. // Make a shallow copy and enforce CCW
  3336. var pts = polygon.map(function (p) {
  3337. return {
  3338. x: p.x,
  3339. y: p.y
  3340. };
  3341. });
  3342. if (signedArea(pts) < 0) pts.reverse();
  3343. var n = pts.length;
  3344. // Compute outward normals for each edge
  3345. var normals = [];
  3346. for (var i = 0; i < n; i++) {
  3347. var p = pts[i],
  3348. q = pts[(i + 1) % n];
  3349. var edge = sub(q, p);
  3350. // For CCW polygon, inward normal = (-edge.y, edge.x)
  3351. // so outward normal = (edge.y, -edge.x)
  3352. var out = normalize({
  3353. x: edge.y,
  3354. y: -edge.x
  3355. });
  3356. normals.push(out);
  3357. }
  3358. // Build offset edges
  3359. var offsetEdges = normals.map(function (nrm, i) {
  3360. var p1 = add(pts[i], scale(nrm, d));
  3361. var p2 = add(pts[(i + 1) % n], scale(nrm, d));
  3362. return {
  3363. p1: p1,
  3364. p2: p2
  3365. };
  3366. });
  3367. // Intersect consecutive offset edges
  3368. var inflated = [];
  3369. for (var _i2 = 0; _i2 < n; _i2++) {
  3370. var prevEdge = offsetEdges[(_i2 - 1 + n) % n];
  3371. var currEdge = offsetEdges[_i2];
  3372. var ip = intersectLines(prevEdge.p1, prevEdge.p2, currEdge.p1, currEdge.p2);
  3373. inflated.push(ip);
  3374. }
  3375. return inflated;
  3376. }
  3377. function miterBox(pts, centerX, centerY, width, height, strokeWidth) {
  3378. var tpts = transformPoints(pts, centerX, centerY, width, height);
  3379. var offsetPoints = inflatePolygon(tpts, strokeWidth);
  3380. var bb = makeBoundingBox();
  3381. offsetPoints.forEach(function (pt) {
  3382. return expandBoundingBoxByPoint(bb, pt.x, pt.y);
  3383. });
  3384. return bb;
  3385. }
  3386. var roundRectangleIntersectLine = function roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding) {
  3387. var radius = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'auto';
  3388. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  3389. var halfWidth = width / 2;
  3390. var halfHeight = height / 2;
  3391. cornerRadius = Math.min(cornerRadius, halfWidth, halfHeight);
  3392. var doWidth = cornerRadius !== halfWidth,
  3393. doHeight = cornerRadius !== halfHeight;
  3394. // Check intersections with straight line segments
  3395. var straightLineIntersections;
  3396. // Top segment, left to right
  3397. if (doWidth) {
  3398. var topStartX = nodeX - halfWidth + cornerRadius - padding;
  3399. var topStartY = nodeY - halfHeight - padding;
  3400. var topEndX = nodeX + halfWidth - cornerRadius + padding;
  3401. var topEndY = topStartY;
  3402. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
  3403. if (straightLineIntersections.length > 0) {
  3404. return straightLineIntersections;
  3405. }
  3406. }
  3407. // Right segment, top to bottom
  3408. if (doHeight) {
  3409. var rightStartX = nodeX + halfWidth + padding;
  3410. var rightStartY = nodeY - halfHeight + cornerRadius - padding;
  3411. var rightEndX = rightStartX;
  3412. var rightEndY = nodeY + halfHeight - cornerRadius + padding;
  3413. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, rightStartX, rightStartY, rightEndX, rightEndY, false);
  3414. if (straightLineIntersections.length > 0) {
  3415. return straightLineIntersections;
  3416. }
  3417. }
  3418. // Bottom segment, left to right
  3419. if (doWidth) {
  3420. var bottomStartX = nodeX - halfWidth + cornerRadius - padding;
  3421. var bottomStartY = nodeY + halfHeight + padding;
  3422. var bottomEndX = nodeX + halfWidth - cornerRadius + padding;
  3423. var bottomEndY = bottomStartY;
  3424. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, bottomStartX, bottomStartY, bottomEndX, bottomEndY, false);
  3425. if (straightLineIntersections.length > 0) {
  3426. return straightLineIntersections;
  3427. }
  3428. }
  3429. // Left segment, top to bottom
  3430. if (doHeight) {
  3431. var leftStartX = nodeX - halfWidth - padding;
  3432. var leftStartY = nodeY - halfHeight + cornerRadius - padding;
  3433. var leftEndX = leftStartX;
  3434. var leftEndY = nodeY + halfHeight - cornerRadius + padding;
  3435. straightLineIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, leftStartX, leftStartY, leftEndX, leftEndY, false);
  3436. if (straightLineIntersections.length > 0) {
  3437. return straightLineIntersections;
  3438. }
  3439. }
  3440. // Check intersections with arc segments
  3441. var arcIntersections;
  3442. // Top Left
  3443. {
  3444. var topLeftCenterX = nodeX - halfWidth + cornerRadius;
  3445. var topLeftCenterY = nodeY - halfHeight + cornerRadius;
  3446. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topLeftCenterX, topLeftCenterY, cornerRadius + padding);
  3447. // Ensure the intersection is on the desired quarter of the circle
  3448. if (arcIntersections.length > 0 && arcIntersections[0] <= topLeftCenterX && arcIntersections[1] <= topLeftCenterY) {
  3449. return [arcIntersections[0], arcIntersections[1]];
  3450. }
  3451. }
  3452. // Top Right
  3453. {
  3454. var topRightCenterX = nodeX + halfWidth - cornerRadius;
  3455. var topRightCenterY = nodeY - halfHeight + cornerRadius;
  3456. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, topRightCenterX, topRightCenterY, cornerRadius + padding);
  3457. // Ensure the intersection is on the desired quarter of the circle
  3458. if (arcIntersections.length > 0 && arcIntersections[0] >= topRightCenterX && arcIntersections[1] <= topRightCenterY) {
  3459. return [arcIntersections[0], arcIntersections[1]];
  3460. }
  3461. }
  3462. // Bottom Right
  3463. {
  3464. var bottomRightCenterX = nodeX + halfWidth - cornerRadius;
  3465. var bottomRightCenterY = nodeY + halfHeight - cornerRadius;
  3466. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomRightCenterX, bottomRightCenterY, cornerRadius + padding);
  3467. // Ensure the intersection is on the desired quarter of the circle
  3468. if (arcIntersections.length > 0 && arcIntersections[0] >= bottomRightCenterX && arcIntersections[1] >= bottomRightCenterY) {
  3469. return [arcIntersections[0], arcIntersections[1]];
  3470. }
  3471. }
  3472. // Bottom Left
  3473. {
  3474. var bottomLeftCenterX = nodeX - halfWidth + cornerRadius;
  3475. var bottomLeftCenterY = nodeY + halfHeight - cornerRadius;
  3476. arcIntersections = intersectLineCircle(x, y, nodeX, nodeY, bottomLeftCenterX, bottomLeftCenterY, cornerRadius + padding);
  3477. // Ensure the intersection is on the desired quarter of the circle
  3478. if (arcIntersections.length > 0 && arcIntersections[0] <= bottomLeftCenterX && arcIntersections[1] >= bottomLeftCenterY) {
  3479. return [arcIntersections[0], arcIntersections[1]];
  3480. }
  3481. }
  3482. return []; // if nothing
  3483. };
  3484. var inLineVicinity = function inLineVicinity(x, y, lx1, ly1, lx2, ly2, tolerance) {
  3485. var t = tolerance;
  3486. var x1 = Math.min(lx1, lx2);
  3487. var x2 = Math.max(lx1, lx2);
  3488. var y1 = Math.min(ly1, ly2);
  3489. var y2 = Math.max(ly1, ly2);
  3490. return x1 - t <= x && x <= x2 + t && y1 - t <= y && y <= y2 + t;
  3491. };
  3492. var inBezierVicinity = function inBezierVicinity(x, y, x1, y1, x2, y2, x3, y3, tolerance) {
  3493. var bb = {
  3494. x1: Math.min(x1, x3, x2) - tolerance,
  3495. x2: Math.max(x1, x3, x2) + tolerance,
  3496. y1: Math.min(y1, y3, y2) - tolerance,
  3497. y2: Math.max(y1, y3, y2) + tolerance
  3498. };
  3499. // if outside the rough bounding box for the bezier, then it can't be a hit
  3500. if (x < bb.x1 || x > bb.x2 || y < bb.y1 || y > bb.y2) {
  3501. // console.log('bezier out of rough bb')
  3502. return false;
  3503. } else {
  3504. // console.log('do more expensive check');
  3505. return true;
  3506. }
  3507. };
  3508. var solveQuadratic = function solveQuadratic(a, b, c, val) {
  3509. c -= val;
  3510. var r = b * b - 4 * a * c;
  3511. if (r < 0) {
  3512. return [];
  3513. }
  3514. var sqrtR = Math.sqrt(r);
  3515. var denom = 2 * a;
  3516. var root1 = (-b + sqrtR) / denom;
  3517. var root2 = (-b - sqrtR) / denom;
  3518. return [root1, root2];
  3519. };
  3520. var solveCubic = function solveCubic(a, b, c, d, result) {
  3521. // Solves a cubic function, returns root in form [r1, i1, r2, i2, r3, i3], where
  3522. // r is the real component, i is the imaginary component
  3523. // An implementation of the Cardano method from the year 1545
  3524. // http://en.wikipedia.org/wiki/Cubic_function#The_nature_of_the_roots
  3525. var epsilon = 0.00001;
  3526. // avoid division by zero while keeping the overall expression close in value
  3527. if (a === 0) {
  3528. a = epsilon;
  3529. }
  3530. b /= a;
  3531. c /= a;
  3532. d /= a;
  3533. var discriminant, q, r, dum1, s, t, term1, r13;
  3534. q = (3.0 * c - b * b) / 9.0;
  3535. r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b));
  3536. r /= 54.0;
  3537. discriminant = q * q * q + r * r;
  3538. result[1] = 0;
  3539. term1 = b / 3.0;
  3540. if (discriminant > 0) {
  3541. s = r + Math.sqrt(discriminant);
  3542. s = s < 0 ? -Math.pow(-s, 1.0 / 3.0) : Math.pow(s, 1.0 / 3.0);
  3543. t = r - Math.sqrt(discriminant);
  3544. t = t < 0 ? -Math.pow(-t, 1.0 / 3.0) : Math.pow(t, 1.0 / 3.0);
  3545. result[0] = -term1 + s + t;
  3546. term1 += (s + t) / 2.0;
  3547. result[4] = result[2] = -term1;
  3548. term1 = Math.sqrt(3.0) * (-t + s) / 2;
  3549. result[3] = term1;
  3550. result[5] = -term1;
  3551. return;
  3552. }
  3553. result[5] = result[3] = 0;
  3554. if (discriminant === 0) {
  3555. r13 = r < 0 ? -Math.pow(-r, 1.0 / 3.0) : Math.pow(r, 1.0 / 3.0);
  3556. result[0] = -term1 + 2.0 * r13;
  3557. result[4] = result[2] = -(r13 + term1);
  3558. return;
  3559. }
  3560. q = -q;
  3561. dum1 = q * q * q;
  3562. dum1 = Math.acos(r / Math.sqrt(dum1));
  3563. r13 = 2.0 * Math.sqrt(q);
  3564. result[0] = -term1 + r13 * Math.cos(dum1 / 3.0);
  3565. result[2] = -term1 + r13 * Math.cos((dum1 + 2.0 * Math.PI) / 3.0);
  3566. result[4] = -term1 + r13 * Math.cos((dum1 + 4.0 * Math.PI) / 3.0);
  3567. return;
  3568. };
  3569. var sqdistToQuadraticBezier = function sqdistToQuadraticBezier(x, y, x1, y1, x2, y2, x3, y3) {
  3570. // Find minimum distance by using the minimum of the distance
  3571. // function between the given point and the curve
  3572. // This gives the coefficients of the resulting cubic equation
  3573. // whose roots tell us where a possible minimum is
  3574. // (Coefficients are divided by 4)
  3575. 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;
  3576. 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;
  3577. 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;
  3578. var d = 1.0 * x1 * x2 - x1 * x1 + x1 * x - x2 * x + y1 * y2 - y1 * y1 + y1 * y - y2 * y;
  3579. // debug("coefficients: " + a / a + ", " + b / a + ", " + c / a + ", " + d / a);
  3580. var roots = [];
  3581. // Use the cubic solving algorithm
  3582. solveCubic(a, b, c, d, roots);
  3583. var zeroThreshold = 0.0000001;
  3584. var params = [];
  3585. for (var index = 0; index < 6; index += 2) {
  3586. if (Math.abs(roots[index + 1]) < zeroThreshold && roots[index] >= 0 && roots[index] <= 1.0) {
  3587. params.push(roots[index]);
  3588. }
  3589. }
  3590. params.push(1.0);
  3591. params.push(0.0);
  3592. var minDistanceSquared = -1;
  3593. var curX, curY, distSquared;
  3594. for (var i = 0; i < params.length; i++) {
  3595. curX = Math.pow(1.0 - params[i], 2.0) * x1 + 2.0 * (1 - params[i]) * params[i] * x2 + params[i] * params[i] * x3;
  3596. curY = Math.pow(1 - params[i], 2.0) * y1 + 2 * (1.0 - params[i]) * params[i] * y2 + params[i] * params[i] * y3;
  3597. distSquared = Math.pow(curX - x, 2) + Math.pow(curY - y, 2);
  3598. // debug('distance for param ' + params[i] + ": " + Math.sqrt(distSquared));
  3599. if (minDistanceSquared >= 0) {
  3600. if (distSquared < minDistanceSquared) {
  3601. minDistanceSquared = distSquared;
  3602. }
  3603. } else {
  3604. minDistanceSquared = distSquared;
  3605. }
  3606. }
  3607. return minDistanceSquared;
  3608. };
  3609. var sqdistToFiniteLine = function sqdistToFiniteLine(x, y, x1, y1, x2, y2) {
  3610. var offset = [x - x1, y - y1];
  3611. var line = [x2 - x1, y2 - y1];
  3612. var lineSq = line[0] * line[0] + line[1] * line[1];
  3613. var hypSq = offset[0] * offset[0] + offset[1] * offset[1];
  3614. var dotProduct = offset[0] * line[0] + offset[1] * line[1];
  3615. var adjSq = dotProduct * dotProduct / lineSq;
  3616. if (dotProduct < 0) {
  3617. return hypSq;
  3618. }
  3619. if (adjSq > lineSq) {
  3620. return (x - x2) * (x - x2) + (y - y2) * (y - y2);
  3621. }
  3622. return hypSq - adjSq;
  3623. };
  3624. var pointInsidePolygonPoints = function pointInsidePolygonPoints(x, y, points) {
  3625. var x1, y1, x2, y2;
  3626. var y3;
  3627. // Intersect with vertical line through (x, y)
  3628. var up = 0;
  3629. // let down = 0;
  3630. for (var i = 0; i < points.length / 2; i++) {
  3631. x1 = points[i * 2];
  3632. y1 = points[i * 2 + 1];
  3633. if (i + 1 < points.length / 2) {
  3634. x2 = points[(i + 1) * 2];
  3635. y2 = points[(i + 1) * 2 + 1];
  3636. } else {
  3637. x2 = points[(i + 1 - points.length / 2) * 2];
  3638. y2 = points[(i + 1 - points.length / 2) * 2 + 1];
  3639. }
  3640. if (x1 == x && x2 == x) ; else if (x1 >= x && x >= x2 || x1 <= x && x <= x2) {
  3641. y3 = (x - x1) / (x2 - x1) * (y2 - y1) + y1;
  3642. if (y3 > y) {
  3643. up++;
  3644. }
  3645. // if( y3 < y ){
  3646. // down++;
  3647. // }
  3648. } else {
  3649. continue;
  3650. }
  3651. }
  3652. if (up % 2 === 0) {
  3653. return false;
  3654. } else {
  3655. return true;
  3656. }
  3657. };
  3658. var pointInsidePolygon = function pointInsidePolygon(x, y, basePoints, centerX, centerY, width, height, direction, padding) {
  3659. var transformedPoints = new Array(basePoints.length);
  3660. // Gives negative angle
  3661. var angle;
  3662. if (direction[0] != null) {
  3663. angle = Math.atan(direction[1] / direction[0]);
  3664. if (direction[0] < 0) {
  3665. angle = angle + Math.PI / 2;
  3666. } else {
  3667. angle = -angle - Math.PI / 2;
  3668. }
  3669. } else {
  3670. angle = direction;
  3671. }
  3672. var cos = Math.cos(-angle);
  3673. var sin = Math.sin(-angle);
  3674. // console.log("base: " + basePoints);
  3675. for (var i = 0; i < transformedPoints.length / 2; i++) {
  3676. transformedPoints[i * 2] = width / 2 * (basePoints[i * 2] * cos - basePoints[i * 2 + 1] * sin);
  3677. transformedPoints[i * 2 + 1] = height / 2 * (basePoints[i * 2 + 1] * cos + basePoints[i * 2] * sin);
  3678. transformedPoints[i * 2] += centerX;
  3679. transformedPoints[i * 2 + 1] += centerY;
  3680. }
  3681. var points;
  3682. if (padding > 0) {
  3683. var expandedLineSet = expandPolygon(transformedPoints, -padding);
  3684. points = joinLines(expandedLineSet);
  3685. } else {
  3686. points = transformedPoints;
  3687. }
  3688. return pointInsidePolygonPoints(x, y, points);
  3689. };
  3690. var pointInsideRoundPolygon = function pointInsideRoundPolygon(x, y, basePoints, centerX, centerY, width, height, corners) {
  3691. var cutPolygonPoints = new Array(basePoints.length * 2);
  3692. for (var i = 0; i < corners.length; i++) {
  3693. var corner = corners[i];
  3694. cutPolygonPoints[i * 4 + 0] = corner.startX;
  3695. cutPolygonPoints[i * 4 + 1] = corner.startY;
  3696. cutPolygonPoints[i * 4 + 2] = corner.stopX;
  3697. cutPolygonPoints[i * 4 + 3] = corner.stopY;
  3698. var squaredDistance = Math.pow(corner.cx - x, 2) + Math.pow(corner.cy - y, 2);
  3699. if (squaredDistance <= Math.pow(corner.radius, 2)) {
  3700. return true;
  3701. }
  3702. }
  3703. return pointInsidePolygonPoints(x, y, cutPolygonPoints);
  3704. };
  3705. var joinLines = function joinLines(lineSet) {
  3706. var vertices = new Array(lineSet.length / 2);
  3707. var currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY;
  3708. var nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY;
  3709. for (var i = 0; i < lineSet.length / 4; i++) {
  3710. currentLineStartX = lineSet[i * 4];
  3711. currentLineStartY = lineSet[i * 4 + 1];
  3712. currentLineEndX = lineSet[i * 4 + 2];
  3713. currentLineEndY = lineSet[i * 4 + 3];
  3714. if (i < lineSet.length / 4 - 1) {
  3715. nextLineStartX = lineSet[(i + 1) * 4];
  3716. nextLineStartY = lineSet[(i + 1) * 4 + 1];
  3717. nextLineEndX = lineSet[(i + 1) * 4 + 2];
  3718. nextLineEndY = lineSet[(i + 1) * 4 + 3];
  3719. } else {
  3720. nextLineStartX = lineSet[0];
  3721. nextLineStartY = lineSet[1];
  3722. nextLineEndX = lineSet[2];
  3723. nextLineEndY = lineSet[3];
  3724. }
  3725. var intersection = finiteLinesIntersect(currentLineStartX, currentLineStartY, currentLineEndX, currentLineEndY, nextLineStartX, nextLineStartY, nextLineEndX, nextLineEndY, true);
  3726. vertices[i * 2] = intersection[0];
  3727. vertices[i * 2 + 1] = intersection[1];
  3728. }
  3729. return vertices;
  3730. };
  3731. var expandPolygon = function expandPolygon(points, pad) {
  3732. var expandedLineSet = new Array(points.length * 2);
  3733. var currentPointX, currentPointY, nextPointX, nextPointY;
  3734. for (var i = 0; i < points.length / 2; i++) {
  3735. currentPointX = points[i * 2];
  3736. currentPointY = points[i * 2 + 1];
  3737. if (i < points.length / 2 - 1) {
  3738. nextPointX = points[(i + 1) * 2];
  3739. nextPointY = points[(i + 1) * 2 + 1];
  3740. } else {
  3741. nextPointX = points[0];
  3742. nextPointY = points[1];
  3743. }
  3744. // Current line: [currentPointX, currentPointY] to [nextPointX, nextPointY]
  3745. // Assume CCW polygon winding
  3746. var offsetX = nextPointY - currentPointY;
  3747. var offsetY = -(nextPointX - currentPointX);
  3748. // Normalize
  3749. var offsetLength = Math.sqrt(offsetX * offsetX + offsetY * offsetY);
  3750. var normalizedOffsetX = offsetX / offsetLength;
  3751. var normalizedOffsetY = offsetY / offsetLength;
  3752. expandedLineSet[i * 4] = currentPointX + normalizedOffsetX * pad;
  3753. expandedLineSet[i * 4 + 1] = currentPointY + normalizedOffsetY * pad;
  3754. expandedLineSet[i * 4 + 2] = nextPointX + normalizedOffsetX * pad;
  3755. expandedLineSet[i * 4 + 3] = nextPointY + normalizedOffsetY * pad;
  3756. }
  3757. return expandedLineSet;
  3758. };
  3759. var intersectLineEllipse = function intersectLineEllipse(x, y, centerX, centerY, ellipseWradius, ellipseHradius) {
  3760. var dispX = centerX - x;
  3761. var dispY = centerY - y;
  3762. dispX /= ellipseWradius;
  3763. dispY /= ellipseHradius;
  3764. var len = Math.sqrt(dispX * dispX + dispY * dispY);
  3765. var newLength = len - 1;
  3766. if (newLength < 0) {
  3767. return [];
  3768. }
  3769. var lenProportion = newLength / len;
  3770. return [(centerX - x) * lenProportion + x, (centerY - y) * lenProportion + y];
  3771. };
  3772. var checkInEllipse = function checkInEllipse(x, y, width, height, centerX, centerY, padding) {
  3773. x -= centerX;
  3774. y -= centerY;
  3775. x /= width / 2 + padding;
  3776. y /= height / 2 + padding;
  3777. return x * x + y * y <= 1;
  3778. };
  3779. // Returns intersections of increasing distance from line's start point
  3780. var intersectLineCircle = function intersectLineCircle(x1, y1, x2, y2, centerX, centerY, radius) {
  3781. // Calculate d, direction vector of line
  3782. var d = [x2 - x1, y2 - y1]; // Direction vector of line
  3783. var f = [x1 - centerX, y1 - centerY];
  3784. var a = d[0] * d[0] + d[1] * d[1];
  3785. var b = 2 * (f[0] * d[0] + f[1] * d[1]);
  3786. var c = f[0] * f[0] + f[1] * f[1] - radius * radius;
  3787. var discriminant = b * b - 4 * a * c;
  3788. if (discriminant < 0) {
  3789. return [];
  3790. }
  3791. var t1 = (-b + Math.sqrt(discriminant)) / (2 * a);
  3792. var t2 = (-b - Math.sqrt(discriminant)) / (2 * a);
  3793. var tMin = Math.min(t1, t2);
  3794. var tMax = Math.max(t1, t2);
  3795. var inRangeParams = [];
  3796. if (tMin >= 0 && tMin <= 1) {
  3797. inRangeParams.push(tMin);
  3798. }
  3799. if (tMax >= 0 && tMax <= 1) {
  3800. inRangeParams.push(tMax);
  3801. }
  3802. if (inRangeParams.length === 0) {
  3803. return [];
  3804. }
  3805. var nearIntersectionX = inRangeParams[0] * d[0] + x1;
  3806. var nearIntersectionY = inRangeParams[0] * d[1] + y1;
  3807. if (inRangeParams.length > 1) {
  3808. if (inRangeParams[0] == inRangeParams[1]) {
  3809. return [nearIntersectionX, nearIntersectionY];
  3810. } else {
  3811. var farIntersectionX = inRangeParams[1] * d[0] + x1;
  3812. var farIntersectionY = inRangeParams[1] * d[1] + y1;
  3813. return [nearIntersectionX, nearIntersectionY, farIntersectionX, farIntersectionY];
  3814. }
  3815. } else {
  3816. return [nearIntersectionX, nearIntersectionY];
  3817. }
  3818. };
  3819. var midOfThree = function midOfThree(a, b, c) {
  3820. if (b <= a && a <= c || c <= a && a <= b) {
  3821. return a;
  3822. } else if (a <= b && b <= c || c <= b && b <= a) {
  3823. return b;
  3824. } else {
  3825. return c;
  3826. }
  3827. };
  3828. // (x1,y1)=>(x2,y2) intersect with (x3,y3)=>(x4,y4)
  3829. var finiteLinesIntersect = function finiteLinesIntersect(x1, y1, x2, y2, x3, y3, x4, y4, infiniteLines) {
  3830. var dx13 = x1 - x3;
  3831. var dx21 = x2 - x1;
  3832. var dx43 = x4 - x3;
  3833. var dy13 = y1 - y3;
  3834. var dy21 = y2 - y1;
  3835. var dy43 = y4 - y3;
  3836. var ua_t = dx43 * dy13 - dy43 * dx13;
  3837. var ub_t = dx21 * dy13 - dy21 * dx13;
  3838. var u_b = dy43 * dx21 - dx43 * dy21;
  3839. if (u_b !== 0) {
  3840. var ua = ua_t / u_b;
  3841. var ub = ub_t / u_b;
  3842. var flptThreshold = 0.001;
  3843. var _min = 0 - flptThreshold;
  3844. var _max = 1 + flptThreshold;
  3845. if (_min <= ua && ua <= _max && _min <= ub && ub <= _max) {
  3846. return [x1 + ua * dx21, y1 + ua * dy21];
  3847. } else {
  3848. if (!infiniteLines) {
  3849. return [];
  3850. } else {
  3851. return [x1 + ua * dx21, y1 + ua * dy21];
  3852. }
  3853. }
  3854. } else {
  3855. if (ua_t === 0 || ub_t === 0) {
  3856. // Parallel, coincident lines. Check if overlap
  3857. // Check endpoint of second line
  3858. if (midOfThree(x1, x2, x4) === x4) {
  3859. return [x4, y4];
  3860. }
  3861. // Check start point of second line
  3862. if (midOfThree(x1, x2, x3) === x3) {
  3863. return [x3, y3];
  3864. }
  3865. // Endpoint of first line
  3866. if (midOfThree(x3, x4, x2) === x2) {
  3867. return [x2, y2];
  3868. }
  3869. return [];
  3870. } else {
  3871. // Parallel, non-coincident
  3872. return [];
  3873. }
  3874. }
  3875. };
  3876. var transformPoints = function transformPoints(points, centerX, centerY, width, height) {
  3877. var ret = [];
  3878. var halfW = width / 2;
  3879. var halfH = height / 2;
  3880. var x = centerX;
  3881. var y = centerY;
  3882. ret.push({
  3883. x: x + halfW * points[0],
  3884. y: y + halfH * points[1]
  3885. });
  3886. for (var i = 1; i < points.length / 2; i++) {
  3887. ret.push({
  3888. x: x + halfW * points[i * 2],
  3889. y: y + halfH * points[i * 2 + 1]
  3890. });
  3891. }
  3892. return ret;
  3893. };
  3894. // math.polygonIntersectLine( x, y, basePoints, centerX, centerY, width, height, padding )
  3895. // intersect a node polygon (pts transformed)
  3896. //
  3897. // math.polygonIntersectLine( x, y, basePoints, centerX, centerY )
  3898. // intersect the points (no transform)
  3899. var polygonIntersectLine = function polygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding) {
  3900. var intersections = [];
  3901. var intersection;
  3902. var transformedPoints = new Array(basePoints.length);
  3903. var doTransform = true;
  3904. if (width == null) {
  3905. doTransform = false;
  3906. }
  3907. var points;
  3908. if (doTransform) {
  3909. for (var i = 0; i < transformedPoints.length / 2; i++) {
  3910. transformedPoints[i * 2] = basePoints[i * 2] * width + centerX;
  3911. transformedPoints[i * 2 + 1] = basePoints[i * 2 + 1] * height + centerY;
  3912. }
  3913. if (padding > 0) {
  3914. var expandedLineSet = expandPolygon(transformedPoints, -padding);
  3915. points = joinLines(expandedLineSet);
  3916. } else {
  3917. points = transformedPoints;
  3918. }
  3919. } else {
  3920. points = basePoints;
  3921. }
  3922. var currentX, currentY, nextX, nextY;
  3923. for (var _i3 = 0; _i3 < points.length / 2; _i3++) {
  3924. currentX = points[_i3 * 2];
  3925. currentY = points[_i3 * 2 + 1];
  3926. if (_i3 < points.length / 2 - 1) {
  3927. nextX = points[(_i3 + 1) * 2];
  3928. nextY = points[(_i3 + 1) * 2 + 1];
  3929. } else {
  3930. nextX = points[0];
  3931. nextY = points[1];
  3932. }
  3933. intersection = finiteLinesIntersect(x, y, centerX, centerY, currentX, currentY, nextX, nextY);
  3934. if (intersection.length !== 0) {
  3935. intersections.push(intersection[0], intersection[1]);
  3936. }
  3937. }
  3938. return intersections;
  3939. };
  3940. var roundPolygonIntersectLine = function roundPolygonIntersectLine(x, y, basePoints, centerX, centerY, width, height, padding, corners) {
  3941. var intersections = [];
  3942. var intersection;
  3943. var lines = new Array(basePoints.length * 2);
  3944. corners.forEach(function (corner, i) {
  3945. if (i === 0) {
  3946. lines[lines.length - 2] = corner.startX;
  3947. lines[lines.length - 1] = corner.startY;
  3948. } else {
  3949. lines[i * 4 - 2] = corner.startX;
  3950. lines[i * 4 - 1] = corner.startY;
  3951. }
  3952. lines[i * 4] = corner.stopX;
  3953. lines[i * 4 + 1] = corner.stopY;
  3954. intersection = intersectLineCircle(x, y, centerX, centerY, corner.cx, corner.cy, corner.radius);
  3955. if (intersection.length !== 0) {
  3956. intersections.push(intersection[0], intersection[1]);
  3957. }
  3958. });
  3959. for (var i = 0; i < lines.length / 4; i++) {
  3960. intersection = finiteLinesIntersect(x, y, centerX, centerY, lines[i * 4], lines[i * 4 + 1], lines[i * 4 + 2], lines[i * 4 + 3], false);
  3961. if (intersection.length !== 0) {
  3962. intersections.push(intersection[0], intersection[1]);
  3963. }
  3964. }
  3965. if (intersections.length > 2) {
  3966. var lowestIntersection = [intersections[0], intersections[1]];
  3967. var lowestSquaredDistance = Math.pow(lowestIntersection[0] - x, 2) + Math.pow(lowestIntersection[1] - y, 2);
  3968. for (var _i4 = 1; _i4 < intersections.length / 2; _i4++) {
  3969. var squaredDistance = Math.pow(intersections[_i4 * 2] - x, 2) + Math.pow(intersections[_i4 * 2 + 1] - y, 2);
  3970. if (squaredDistance <= lowestSquaredDistance) {
  3971. lowestIntersection[0] = intersections[_i4 * 2];
  3972. lowestIntersection[1] = intersections[_i4 * 2 + 1];
  3973. lowestSquaredDistance = squaredDistance;
  3974. }
  3975. }
  3976. return lowestIntersection;
  3977. }
  3978. return intersections;
  3979. };
  3980. var shortenIntersection = function shortenIntersection(intersection, offset, amount) {
  3981. var disp = [intersection[0] - offset[0], intersection[1] - offset[1]];
  3982. var length = Math.sqrt(disp[0] * disp[0] + disp[1] * disp[1]);
  3983. var lenRatio = (length - amount) / length;
  3984. if (lenRatio < 0) {
  3985. lenRatio = 0.00001;
  3986. }
  3987. return [offset[0] + lenRatio * disp[0], offset[1] + lenRatio * disp[1]];
  3988. };
  3989. var generateUnitNgonPointsFitToSquare = function generateUnitNgonPointsFitToSquare(sides, rotationRadians) {
  3990. var points = generateUnitNgonPoints(sides, rotationRadians);
  3991. points = fitPolygonToSquare(points);
  3992. return points;
  3993. };
  3994. var fitPolygonToSquare = function fitPolygonToSquare(points) {
  3995. var x, y;
  3996. var sides = points.length / 2;
  3997. var minX = Infinity,
  3998. minY = Infinity,
  3999. maxX = -Infinity,
  4000. maxY = -Infinity;
  4001. for (var i = 0; i < sides; i++) {
  4002. x = points[2 * i];
  4003. y = points[2 * i + 1];
  4004. minX = Math.min(minX, x);
  4005. maxX = Math.max(maxX, x);
  4006. minY = Math.min(minY, y);
  4007. maxY = Math.max(maxY, y);
  4008. }
  4009. // stretch factors
  4010. var sx = 2 / (maxX - minX);
  4011. var sy = 2 / (maxY - minY);
  4012. for (var _i5 = 0; _i5 < sides; _i5++) {
  4013. x = points[2 * _i5] = points[2 * _i5] * sx;
  4014. y = points[2 * _i5 + 1] = points[2 * _i5 + 1] * sy;
  4015. minX = Math.min(minX, x);
  4016. maxX = Math.max(maxX, x);
  4017. minY = Math.min(minY, y);
  4018. maxY = Math.max(maxY, y);
  4019. }
  4020. if (minY < -1) {
  4021. for (var _i6 = 0; _i6 < sides; _i6++) {
  4022. y = points[2 * _i6 + 1] = points[2 * _i6 + 1] + (-1 - minY);
  4023. }
  4024. }
  4025. return points;
  4026. };
  4027. var generateUnitNgonPoints = function generateUnitNgonPoints(sides, rotationRadians) {
  4028. var increment = 1.0 / sides * 2 * Math.PI;
  4029. var startAngle = sides % 2 === 0 ? Math.PI / 2.0 + increment / 2.0 : Math.PI / 2.0;
  4030. startAngle += rotationRadians;
  4031. var points = new Array(sides * 2);
  4032. var currentAngle;
  4033. for (var i = 0; i < sides; i++) {
  4034. currentAngle = i * increment + startAngle;
  4035. points[2 * i] = Math.cos(currentAngle); // x
  4036. points[2 * i + 1] = Math.sin(-currentAngle); // y
  4037. }
  4038. return points;
  4039. };
  4040. // Set the default radius, unless half of width or height is smaller than default
  4041. var getRoundRectangleRadius = function getRoundRectangleRadius(width, height) {
  4042. return Math.min(width / 4, height / 4, 8);
  4043. };
  4044. // Set the default radius
  4045. var getRoundPolygonRadius = function getRoundPolygonRadius(width, height) {
  4046. return Math.min(width / 10, height / 10, 8);
  4047. };
  4048. var getCutRectangleCornerLength = function getCutRectangleCornerLength() {
  4049. return 8;
  4050. };
  4051. var bezierPtsToQuadCoeff = function bezierPtsToQuadCoeff(p0, p1, p2) {
  4052. return [p0 - 2 * p1 + p2, 2 * (p1 - p0), p0];
  4053. };
  4054. // get curve width, height, and control point position offsets as a percentage of node height / width
  4055. var getBarrelCurveConstants = function getBarrelCurveConstants(width, height) {
  4056. return {
  4057. heightOffset: Math.min(15, 0.05 * height),
  4058. widthOffset: Math.min(100, 0.25 * width),
  4059. ctrlPtOffsetPct: 0.05
  4060. };
  4061. };
  4062. // Separating Axis Theorem (SAT) to determine if two polygons intersect.
  4063. // The function takes two polygons as input and returns a boolean value indicating
  4064. // whether the two polygons intersect.
  4065. function satPolygonIntersection(poly1, poly2) {
  4066. function getAxes(polygon) {
  4067. var axes = [];
  4068. for (var i = 0; i < polygon.length; i++) {
  4069. var p1 = polygon[i];
  4070. var p2 = polygon[(i + 1) % polygon.length];
  4071. var edge = {
  4072. x: p2.x - p1.x,
  4073. y: p2.y - p1.y
  4074. };
  4075. var normal = {
  4076. x: -edge.y,
  4077. y: edge.x
  4078. };
  4079. var length = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
  4080. axes.push({
  4081. x: normal.x / length,
  4082. y: normal.y / length
  4083. });
  4084. }
  4085. return axes;
  4086. }
  4087. function project(polygon, axis) {
  4088. var min = Infinity;
  4089. var max = -Infinity;
  4090. var _iterator = _createForOfIteratorHelper(polygon),
  4091. _step;
  4092. try {
  4093. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  4094. var point = _step.value;
  4095. var projection = point.x * axis.x + point.y * axis.y;
  4096. min = Math.min(min, projection);
  4097. max = Math.max(max, projection);
  4098. }
  4099. } catch (err) {
  4100. _iterator.e(err);
  4101. } finally {
  4102. _iterator.f();
  4103. }
  4104. return {
  4105. min: min,
  4106. max: max
  4107. };
  4108. }
  4109. function overlaps(proj1, proj2) {
  4110. return !(proj1.max < proj2.min || proj2.max < proj1.min);
  4111. }
  4112. var axes = [].concat(_toConsumableArray(getAxes(poly1)), _toConsumableArray(getAxes(poly2)));
  4113. var _iterator2 = _createForOfIteratorHelper(axes),
  4114. _step2;
  4115. try {
  4116. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  4117. var axis = _step2.value;
  4118. var proj1 = project(poly1, axis);
  4119. var proj2 = project(poly2, axis);
  4120. if (!overlaps(proj1, proj2)) {
  4121. return false; // No overlap, so the polygons do not intersect
  4122. }
  4123. }
  4124. } catch (err) {
  4125. _iterator2.e(err);
  4126. } finally {
  4127. _iterator2.f();
  4128. }
  4129. return true; // polygons intersect
  4130. }
  4131. var pageRankDefaults = defaults$g({
  4132. dampingFactor: 0.8,
  4133. precision: 0.000001,
  4134. iterations: 200,
  4135. weight: function weight(edge) {
  4136. return 1;
  4137. }
  4138. });
  4139. var elesfn$o = {
  4140. pageRank: function pageRank(options) {
  4141. var _pageRankDefaults = pageRankDefaults(options),
  4142. dampingFactor = _pageRankDefaults.dampingFactor,
  4143. precision = _pageRankDefaults.precision,
  4144. iterations = _pageRankDefaults.iterations,
  4145. weight = _pageRankDefaults.weight;
  4146. var cy = this._private.cy;
  4147. var _this$byGroup = this.byGroup(),
  4148. nodes = _this$byGroup.nodes,
  4149. edges = _this$byGroup.edges;
  4150. var numNodes = nodes.length;
  4151. var numNodesSqd = numNodes * numNodes;
  4152. var numEdges = edges.length;
  4153. // Construct transposed adjacency matrix
  4154. // First lets have a zeroed matrix of the right size
  4155. // We'll also keep track of the sum of each column
  4156. var matrix = new Array(numNodesSqd);
  4157. var columnSum = new Array(numNodes);
  4158. var additionalProb = (1 - dampingFactor) / numNodes;
  4159. // Create null matrix
  4160. for (var i = 0; i < numNodes; i++) {
  4161. for (var j = 0; j < numNodes; j++) {
  4162. var n = i * numNodes + j;
  4163. matrix[n] = 0;
  4164. }
  4165. columnSum[i] = 0;
  4166. }
  4167. // Now, process edges
  4168. for (var _i = 0; _i < numEdges; _i++) {
  4169. var edge = edges[_i];
  4170. var srcId = edge.data('source');
  4171. var tgtId = edge.data('target');
  4172. // Don't include loops in the matrix
  4173. if (srcId === tgtId) {
  4174. continue;
  4175. }
  4176. var s = nodes.indexOfId(srcId);
  4177. var t = nodes.indexOfId(tgtId);
  4178. var w = weight(edge);
  4179. var _n = t * numNodes + s;
  4180. // Update matrix
  4181. matrix[_n] += w;
  4182. // Update column sum
  4183. columnSum[s] += w;
  4184. }
  4185. // Add additional probability based on damping factor
  4186. // Also, take into account columns that have sum = 0
  4187. var p = 1.0 / numNodes + additionalProb; // Shorthand
  4188. // Traverse matrix, column by column
  4189. for (var _j = 0; _j < numNodes; _j++) {
  4190. if (columnSum[_j] === 0) {
  4191. // No 'links' out from node jth, assume equal probability for each possible node
  4192. for (var _i2 = 0; _i2 < numNodes; _i2++) {
  4193. var _n2 = _i2 * numNodes + _j;
  4194. matrix[_n2] = p;
  4195. }
  4196. } else {
  4197. // Node jth has outgoing link, compute normalized probabilities
  4198. for (var _i3 = 0; _i3 < numNodes; _i3++) {
  4199. var _n3 = _i3 * numNodes + _j;
  4200. matrix[_n3] = matrix[_n3] / columnSum[_j] + additionalProb;
  4201. }
  4202. }
  4203. }
  4204. // Compute dominant eigenvector using power method
  4205. var eigenvector = new Array(numNodes);
  4206. var temp = new Array(numNodes);
  4207. var previous;
  4208. // Start with a vector of all 1's
  4209. // Also, initialize a null vector which will be used as shorthand
  4210. for (var _i4 = 0; _i4 < numNodes; _i4++) {
  4211. eigenvector[_i4] = 1;
  4212. }
  4213. for (var iter = 0; iter < iterations; iter++) {
  4214. // Temp array with all 0's
  4215. for (var _i5 = 0; _i5 < numNodes; _i5++) {
  4216. temp[_i5] = 0;
  4217. }
  4218. // Multiply matrix with previous result
  4219. for (var _i6 = 0; _i6 < numNodes; _i6++) {
  4220. for (var _j2 = 0; _j2 < numNodes; _j2++) {
  4221. var _n4 = _i6 * numNodes + _j2;
  4222. temp[_i6] += matrix[_n4] * eigenvector[_j2];
  4223. }
  4224. }
  4225. inPlaceSumNormalize(temp);
  4226. previous = eigenvector;
  4227. eigenvector = temp;
  4228. temp = previous;
  4229. var diff = 0;
  4230. // Compute difference (squared module) of both vectors
  4231. for (var _i7 = 0; _i7 < numNodes; _i7++) {
  4232. var delta = previous[_i7] - eigenvector[_i7];
  4233. diff += delta * delta;
  4234. }
  4235. // If difference is less than the desired threshold, stop iterating
  4236. if (diff < precision) {
  4237. break;
  4238. }
  4239. }
  4240. // Construct result
  4241. var res = {
  4242. rank: function rank(node) {
  4243. node = cy.collection(node)[0];
  4244. return eigenvector[nodes.indexOf(node)];
  4245. }
  4246. };
  4247. return res;
  4248. } // pageRank
  4249. }; // elesfn
  4250. var defaults$f = defaults$g({
  4251. root: null,
  4252. weight: function weight(edge) {
  4253. return 1;
  4254. },
  4255. directed: false,
  4256. alpha: 0
  4257. });
  4258. var elesfn$n = {
  4259. degreeCentralityNormalized: function degreeCentralityNormalized(options) {
  4260. options = defaults$f(options);
  4261. var cy = this.cy();
  4262. var nodes = this.nodes();
  4263. var numNodes = nodes.length;
  4264. if (!options.directed) {
  4265. var degrees = {};
  4266. var maxDegree = 0;
  4267. for (var i = 0; i < numNodes; i++) {
  4268. var node = nodes[i];
  4269. // add current node to the current options object and call degreeCentrality
  4270. options.root = node;
  4271. var currDegree = this.degreeCentrality(options);
  4272. if (maxDegree < currDegree.degree) {
  4273. maxDegree = currDegree.degree;
  4274. }
  4275. degrees[node.id()] = currDegree.degree;
  4276. }
  4277. return {
  4278. degree: function degree(node) {
  4279. if (maxDegree === 0) {
  4280. return 0;
  4281. }
  4282. if (string(node)) {
  4283. // from is a selector string
  4284. node = cy.filter(node);
  4285. }
  4286. return degrees[node.id()] / maxDegree;
  4287. }
  4288. };
  4289. } else {
  4290. var indegrees = {};
  4291. var outdegrees = {};
  4292. var maxIndegree = 0;
  4293. var maxOutdegree = 0;
  4294. for (var _i = 0; _i < numNodes; _i++) {
  4295. var _node = nodes[_i];
  4296. var id = _node.id();
  4297. // add current node to the current options object and call degreeCentrality
  4298. options.root = _node;
  4299. var _currDegree = this.degreeCentrality(options);
  4300. if (maxIndegree < _currDegree.indegree) maxIndegree = _currDegree.indegree;
  4301. if (maxOutdegree < _currDegree.outdegree) maxOutdegree = _currDegree.outdegree;
  4302. indegrees[id] = _currDegree.indegree;
  4303. outdegrees[id] = _currDegree.outdegree;
  4304. }
  4305. return {
  4306. indegree: function indegree(node) {
  4307. if (maxIndegree == 0) {
  4308. return 0;
  4309. }
  4310. if (string(node)) {
  4311. // from is a selector string
  4312. node = cy.filter(node);
  4313. }
  4314. return indegrees[node.id()] / maxIndegree;
  4315. },
  4316. outdegree: function outdegree(node) {
  4317. if (maxOutdegree === 0) {
  4318. return 0;
  4319. }
  4320. if (string(node)) {
  4321. // from is a selector string
  4322. node = cy.filter(node);
  4323. }
  4324. return outdegrees[node.id()] / maxOutdegree;
  4325. }
  4326. };
  4327. }
  4328. },
  4329. // degreeCentralityNormalized
  4330. // Implemented from the algorithm in Opsahl's paper
  4331. // "Node centrality in weighted networks: Generalizing degree and shortest paths"
  4332. // check the heading 2 "Degree"
  4333. degreeCentrality: function degreeCentrality(options) {
  4334. options = defaults$f(options);
  4335. var cy = this.cy();
  4336. var callingEles = this;
  4337. var _options = options,
  4338. root = _options.root,
  4339. weight = _options.weight,
  4340. directed = _options.directed,
  4341. alpha = _options.alpha;
  4342. root = cy.collection(root)[0];
  4343. if (!directed) {
  4344. var connEdges = root.connectedEdges().intersection(callingEles);
  4345. var k = connEdges.length;
  4346. var s = 0;
  4347. // Now, sum edge weights
  4348. for (var i = 0; i < connEdges.length; i++) {
  4349. s += weight(connEdges[i]);
  4350. }
  4351. return {
  4352. degree: Math.pow(k, 1 - alpha) * Math.pow(s, alpha)
  4353. };
  4354. } else {
  4355. var edges = root.connectedEdges();
  4356. var incoming = edges.filter(function (edge) {
  4357. return edge.target().same(root) && callingEles.has(edge);
  4358. });
  4359. var outgoing = edges.filter(function (edge) {
  4360. return edge.source().same(root) && callingEles.has(edge);
  4361. });
  4362. var k_in = incoming.length;
  4363. var k_out = outgoing.length;
  4364. var s_in = 0;
  4365. var s_out = 0;
  4366. // Now, sum incoming edge weights
  4367. for (var _i2 = 0; _i2 < incoming.length; _i2++) {
  4368. s_in += weight(incoming[_i2]);
  4369. }
  4370. // Now, sum outgoing edge weights
  4371. for (var _i3 = 0; _i3 < outgoing.length; _i3++) {
  4372. s_out += weight(outgoing[_i3]);
  4373. }
  4374. return {
  4375. indegree: Math.pow(k_in, 1 - alpha) * Math.pow(s_in, alpha),
  4376. outdegree: Math.pow(k_out, 1 - alpha) * Math.pow(s_out, alpha)
  4377. };
  4378. }
  4379. } // degreeCentrality
  4380. }; // elesfn
  4381. // nice, short mathematical alias
  4382. elesfn$n.dc = elesfn$n.degreeCentrality;
  4383. elesfn$n.dcn = elesfn$n.degreeCentralityNormalised = elesfn$n.degreeCentralityNormalized;
  4384. var defaults$e = defaults$g({
  4385. harmonic: true,
  4386. weight: function weight() {
  4387. return 1;
  4388. },
  4389. directed: false,
  4390. root: null
  4391. });
  4392. var elesfn$m = {
  4393. closenessCentralityNormalized: function closenessCentralityNormalized(options) {
  4394. var _defaults = defaults$e(options),
  4395. harmonic = _defaults.harmonic,
  4396. weight = _defaults.weight,
  4397. directed = _defaults.directed;
  4398. var cy = this.cy();
  4399. var closenesses = {};
  4400. var maxCloseness = 0;
  4401. var nodes = this.nodes();
  4402. var fw = this.floydWarshall({
  4403. weight: weight,
  4404. directed: directed
  4405. });
  4406. // Compute closeness for every node and find the maximum closeness
  4407. for (var i = 0; i < nodes.length; i++) {
  4408. var currCloseness = 0;
  4409. var node_i = nodes[i];
  4410. for (var j = 0; j < nodes.length; j++) {
  4411. if (i !== j) {
  4412. var d = fw.distance(node_i, nodes[j]);
  4413. if (harmonic) {
  4414. currCloseness += 1 / d;
  4415. } else {
  4416. currCloseness += d;
  4417. }
  4418. }
  4419. }
  4420. if (!harmonic) {
  4421. currCloseness = 1 / currCloseness;
  4422. }
  4423. if (maxCloseness < currCloseness) {
  4424. maxCloseness = currCloseness;
  4425. }
  4426. closenesses[node_i.id()] = currCloseness;
  4427. }
  4428. return {
  4429. closeness: function closeness(node) {
  4430. if (maxCloseness == 0) {
  4431. return 0;
  4432. }
  4433. if (string(node)) {
  4434. // from is a selector string
  4435. node = cy.filter(node)[0].id();
  4436. } else {
  4437. // from is a node
  4438. node = node.id();
  4439. }
  4440. return closenesses[node] / maxCloseness;
  4441. }
  4442. };
  4443. },
  4444. // Implemented from pseudocode from wikipedia
  4445. closenessCentrality: function closenessCentrality(options) {
  4446. var _defaults2 = defaults$e(options),
  4447. root = _defaults2.root,
  4448. weight = _defaults2.weight,
  4449. directed = _defaults2.directed,
  4450. harmonic = _defaults2.harmonic;
  4451. root = this.filter(root)[0];
  4452. // we need distance from this node to every other node
  4453. var dijkstra = this.dijkstra({
  4454. root: root,
  4455. weight: weight,
  4456. directed: directed
  4457. });
  4458. var totalDistance = 0;
  4459. var nodes = this.nodes();
  4460. for (var i = 0; i < nodes.length; i++) {
  4461. var n = nodes[i];
  4462. if (!n.same(root)) {
  4463. var d = dijkstra.distanceTo(n);
  4464. if (harmonic) {
  4465. totalDistance += 1 / d;
  4466. } else {
  4467. totalDistance += d;
  4468. }
  4469. }
  4470. }
  4471. return harmonic ? totalDistance : 1 / totalDistance;
  4472. } // closenessCentrality
  4473. }; // elesfn
  4474. // nice, short mathematical alias
  4475. elesfn$m.cc = elesfn$m.closenessCentrality;
  4476. elesfn$m.ccn = elesfn$m.closenessCentralityNormalised = elesfn$m.closenessCentralityNormalized;
  4477. var defaults$d = defaults$g({
  4478. weight: null,
  4479. directed: false
  4480. });
  4481. var elesfn$l = {
  4482. // Implemented from the algorithm in the paper "On Variants of Shortest-Path Betweenness Centrality and their Generic Computation" by Ulrik Brandes
  4483. betweennessCentrality: function betweennessCentrality(options) {
  4484. var _defaults = defaults$d(options),
  4485. directed = _defaults.directed,
  4486. weight = _defaults.weight;
  4487. var weighted = weight != null;
  4488. var cy = this.cy();
  4489. // starting
  4490. var V = this.nodes();
  4491. var A = {};
  4492. var _C = {};
  4493. var max = 0;
  4494. var C = {
  4495. set: function set(key, val) {
  4496. _C[key] = val;
  4497. if (val > max) {
  4498. max = val;
  4499. }
  4500. },
  4501. get: function get(key) {
  4502. return _C[key];
  4503. }
  4504. };
  4505. // A contains the neighborhoods of every node
  4506. for (var i = 0; i < V.length; i++) {
  4507. var v = V[i];
  4508. var vid = v.id();
  4509. if (directed) {
  4510. A[vid] = v.outgoers().nodes(); // get outgoers of every node
  4511. } else {
  4512. A[vid] = v.openNeighborhood().nodes(); // get neighbors of every node
  4513. }
  4514. C.set(vid, 0);
  4515. }
  4516. var _loop = function _loop() {
  4517. var sid = V[s].id();
  4518. var S = []; // stack
  4519. var P = {};
  4520. var g = {};
  4521. var d = {};
  4522. var Q = new Heap(function (a, b) {
  4523. return d[a] - d[b];
  4524. }); // queue
  4525. // init dictionaries
  4526. for (var _i = 0; _i < V.length; _i++) {
  4527. var _vid = V[_i].id();
  4528. P[_vid] = [];
  4529. g[_vid] = 0;
  4530. d[_vid] = Infinity;
  4531. }
  4532. g[sid] = 1; // sigma
  4533. d[sid] = 0; // distance to s
  4534. Q.push(sid);
  4535. while (!Q.empty()) {
  4536. var _v = Q.pop();
  4537. S.push(_v);
  4538. if (weighted) {
  4539. for (var j = 0; j < A[_v].length; j++) {
  4540. var w = A[_v][j];
  4541. var vEle = cy.getElementById(_v);
  4542. var edge = undefined;
  4543. if (vEle.edgesTo(w).length > 0) {
  4544. edge = vEle.edgesTo(w)[0];
  4545. } else {
  4546. edge = w.edgesTo(vEle)[0];
  4547. }
  4548. var edgeWeight = weight(edge);
  4549. w = w.id();
  4550. if (d[w] > d[_v] + edgeWeight) {
  4551. d[w] = d[_v] + edgeWeight;
  4552. if (Q.nodes.indexOf(w) < 0) {
  4553. //if w is not in Q
  4554. Q.push(w);
  4555. } else {
  4556. // update position if w is in Q
  4557. Q.updateItem(w);
  4558. }
  4559. g[w] = 0;
  4560. P[w] = [];
  4561. }
  4562. if (d[w] == d[_v] + edgeWeight) {
  4563. g[w] = g[w] + g[_v];
  4564. P[w].push(_v);
  4565. }
  4566. }
  4567. } else {
  4568. for (var _j = 0; _j < A[_v].length; _j++) {
  4569. var _w = A[_v][_j].id();
  4570. if (d[_w] == Infinity) {
  4571. Q.push(_w);
  4572. d[_w] = d[_v] + 1;
  4573. }
  4574. if (d[_w] == d[_v] + 1) {
  4575. g[_w] = g[_w] + g[_v];
  4576. P[_w].push(_v);
  4577. }
  4578. }
  4579. }
  4580. }
  4581. var e = {};
  4582. for (var _i2 = 0; _i2 < V.length; _i2++) {
  4583. e[V[_i2].id()] = 0;
  4584. }
  4585. while (S.length > 0) {
  4586. var _w2 = S.pop();
  4587. for (var _j2 = 0; _j2 < P[_w2].length; _j2++) {
  4588. var _v2 = P[_w2][_j2];
  4589. e[_v2] = e[_v2] + g[_v2] / g[_w2] * (1 + e[_w2]);
  4590. }
  4591. if (_w2 != V[s].id()) {
  4592. C.set(_w2, C.get(_w2) + e[_w2]);
  4593. }
  4594. }
  4595. };
  4596. for (var s = 0; s < V.length; s++) {
  4597. _loop();
  4598. }
  4599. var ret = {
  4600. betweenness: function betweenness(node) {
  4601. var id = cy.collection(node).id();
  4602. return C.get(id);
  4603. },
  4604. betweennessNormalized: function betweennessNormalized(node) {
  4605. if (max == 0) {
  4606. return 0;
  4607. }
  4608. var id = cy.collection(node).id();
  4609. return C.get(id) / max;
  4610. }
  4611. };
  4612. // alias
  4613. ret.betweennessNormalised = ret.betweennessNormalized;
  4614. return ret;
  4615. } // betweennessCentrality
  4616. }; // elesfn
  4617. // nice, short mathematical alias
  4618. elesfn$l.bc = elesfn$l.betweennessCentrality;
  4619. // Implemented by Zoe Xi @zoexi for GSOC 2016
  4620. // https://github.com/cytoscape/cytoscape.js-markov-cluster
  4621. /* eslint-disable no-unused-vars */
  4622. var defaults$c = defaults$g({
  4623. expandFactor: 2,
  4624. // affects time of computation and cluster granularity to some extent: M * M
  4625. inflateFactor: 2,
  4626. // affects cluster granularity (the greater the value, the more clusters): M(i,j) / E(j)
  4627. multFactor: 1,
  4628. // optional self loops for each node. Use a neutral value to improve cluster computations.
  4629. maxIterations: 20,
  4630. // maximum number of iterations of the MCL algorithm in a single run
  4631. attributes: [
  4632. // attributes/features used to group nodes, ie. similarity values between nodes
  4633. function (edge) {
  4634. return 1;
  4635. }]
  4636. });
  4637. /* eslint-enable */
  4638. var setOptions$3 = function setOptions(options) {
  4639. return defaults$c(options);
  4640. };
  4641. /* eslint-enable */
  4642. var getSimilarity$1 = function getSimilarity(edge, attributes) {
  4643. var total = 0;
  4644. for (var i = 0; i < attributes.length; i++) {
  4645. total += attributes[i](edge);
  4646. }
  4647. return total;
  4648. };
  4649. var addLoops = function addLoops(M, n, val) {
  4650. for (var i = 0; i < n; i++) {
  4651. M[i * n + i] = val;
  4652. }
  4653. };
  4654. var normalize = function normalize(M, n) {
  4655. var sum;
  4656. for (var col = 0; col < n; col++) {
  4657. sum = 0;
  4658. for (var row = 0; row < n; row++) {
  4659. sum += M[row * n + col];
  4660. }
  4661. for (var _row = 0; _row < n; _row++) {
  4662. M[_row * n + col] = M[_row * n + col] / sum;
  4663. }
  4664. }
  4665. };
  4666. // TODO: blocked matrix multiplication?
  4667. var mmult = function mmult(A, B, n) {
  4668. var C = new Array(n * n);
  4669. for (var i = 0; i < n; i++) {
  4670. for (var j = 0; j < n; j++) {
  4671. C[i * n + j] = 0;
  4672. }
  4673. for (var k = 0; k < n; k++) {
  4674. for (var _j = 0; _j < n; _j++) {
  4675. C[i * n + _j] += A[i * n + k] * B[k * n + _j];
  4676. }
  4677. }
  4678. }
  4679. return C;
  4680. };
  4681. var expand = function expand(M, n, expandFactor /** power **/) {
  4682. var _M = M.slice(0);
  4683. for (var p = 1; p < expandFactor; p++) {
  4684. M = mmult(M, _M, n);
  4685. }
  4686. return M;
  4687. };
  4688. var inflate = function inflate(M, n, inflateFactor /** r **/) {
  4689. var _M = new Array(n * n);
  4690. // M(i,j) ^ inflatePower
  4691. for (var i = 0; i < n * n; i++) {
  4692. _M[i] = Math.pow(M[i], inflateFactor);
  4693. }
  4694. normalize(_M, n);
  4695. return _M;
  4696. };
  4697. var hasConverged = function hasConverged(M, _M, n2, roundFactor) {
  4698. // Check that both matrices have the same elements (i,j)
  4699. for (var i = 0; i < n2; i++) {
  4700. var v1 = Math.round(M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor); // truncate to 'roundFactor' decimal places
  4701. var v2 = Math.round(_M[i] * Math.pow(10, roundFactor)) / Math.pow(10, roundFactor);
  4702. if (v1 !== v2) {
  4703. return false;
  4704. }
  4705. }
  4706. return true;
  4707. };
  4708. var assign$2 = function assign(M, n, nodes, cy) {
  4709. var clusters = [];
  4710. for (var i = 0; i < n; i++) {
  4711. var cluster = [];
  4712. for (var j = 0; j < n; j++) {
  4713. // Row-wise attractors and elements that they attract belong in same cluster
  4714. if (Math.round(M[i * n + j] * 1000) / 1000 > 0) {
  4715. cluster.push(nodes[j]);
  4716. }
  4717. }
  4718. if (cluster.length !== 0) {
  4719. clusters.push(cy.collection(cluster));
  4720. }
  4721. }
  4722. return clusters;
  4723. };
  4724. var isDuplicate = function isDuplicate(c1, c2) {
  4725. for (var i = 0; i < c1.length; i++) {
  4726. if (!c2[i] || c1[i].id() !== c2[i].id()) {
  4727. return false;
  4728. }
  4729. }
  4730. return true;
  4731. };
  4732. var removeDuplicates = function removeDuplicates(clusters) {
  4733. for (var i = 0; i < clusters.length; i++) {
  4734. for (var j = 0; j < clusters.length; j++) {
  4735. if (i != j && isDuplicate(clusters[i], clusters[j])) {
  4736. clusters.splice(j, 1);
  4737. }
  4738. }
  4739. }
  4740. return clusters;
  4741. };
  4742. var markovClustering = function markovClustering(options) {
  4743. var nodes = this.nodes();
  4744. var edges = this.edges();
  4745. var cy = this.cy();
  4746. // Set parameters of algorithm:
  4747. var opts = setOptions$3(options);
  4748. // Map each node to its position in node array
  4749. var id2position = {};
  4750. for (var i = 0; i < nodes.length; i++) {
  4751. id2position[nodes[i].id()] = i;
  4752. }
  4753. // Generate stochastic matrix M from input graph G (should be symmetric/undirected)
  4754. var n = nodes.length,
  4755. n2 = n * n;
  4756. var M = new Array(n2),
  4757. _M;
  4758. for (var _i = 0; _i < n2; _i++) {
  4759. M[_i] = 0;
  4760. }
  4761. for (var e = 0; e < edges.length; e++) {
  4762. var edge = edges[e];
  4763. var _i2 = id2position[edge.source().id()];
  4764. var j = id2position[edge.target().id()];
  4765. var sim = getSimilarity$1(edge, opts.attributes);
  4766. M[_i2 * n + j] += sim; // G should be symmetric and undirected
  4767. M[j * n + _i2] += sim;
  4768. }
  4769. // Begin Markov cluster algorithm
  4770. // Step 1: Add self loops to each node, ie. add multFactor to matrix diagonal
  4771. addLoops(M, n, opts.multFactor);
  4772. // Step 2: M = normalize( M );
  4773. normalize(M, n);
  4774. var isStillMoving = true;
  4775. var iterations = 0;
  4776. while (isStillMoving && iterations < opts.maxIterations) {
  4777. isStillMoving = false;
  4778. // Step 3:
  4779. _M = expand(M, n, opts.expandFactor);
  4780. // Step 4:
  4781. M = inflate(_M, n, opts.inflateFactor);
  4782. // Step 5: check to see if ~steady state has been reached
  4783. if (!hasConverged(M, _M, n2, 4)) {
  4784. isStillMoving = true;
  4785. }
  4786. iterations++;
  4787. }
  4788. // Build clusters from matrix
  4789. var clusters = assign$2(M, n, nodes, cy);
  4790. // Remove duplicate clusters due to symmetry of graph and M matrix
  4791. clusters = removeDuplicates(clusters);
  4792. return clusters;
  4793. };
  4794. var markovClustering$1 = {
  4795. markovClustering: markovClustering,
  4796. mcl: markovClustering
  4797. };
  4798. // Common distance metrics for clustering algorithms
  4799. // https://en.wikipedia.org/wiki/Hierarchical_clustering#Metric
  4800. var identity$1 = function identity(x) {
  4801. return x;
  4802. };
  4803. var absDiff = function absDiff(p, q) {
  4804. return Math.abs(q - p);
  4805. };
  4806. var addAbsDiff = function addAbsDiff(total, p, q) {
  4807. return total + absDiff(p, q);
  4808. };
  4809. var addSquaredDiff = function addSquaredDiff(total, p, q) {
  4810. return total + Math.pow(q - p, 2);
  4811. };
  4812. var sqrt = function sqrt(x) {
  4813. return Math.sqrt(x);
  4814. };
  4815. var maxAbsDiff = function maxAbsDiff(currentMax, p, q) {
  4816. return Math.max(currentMax, absDiff(p, q));
  4817. };
  4818. var getDistance = function getDistance(length, getP, getQ, init, visit) {
  4819. var post = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : identity$1;
  4820. var ret = init;
  4821. var p, q;
  4822. for (var dim = 0; dim < length; dim++) {
  4823. p = getP(dim);
  4824. q = getQ(dim);
  4825. ret = visit(ret, p, q);
  4826. }
  4827. return post(ret);
  4828. };
  4829. var distances = {
  4830. euclidean: function euclidean(length, getP, getQ) {
  4831. if (length >= 2) {
  4832. return getDistance(length, getP, getQ, 0, addSquaredDiff, sqrt);
  4833. } else {
  4834. // for single attr case, more efficient to avoid sqrt
  4835. return getDistance(length, getP, getQ, 0, addAbsDiff);
  4836. }
  4837. },
  4838. squaredEuclidean: function squaredEuclidean(length, getP, getQ) {
  4839. return getDistance(length, getP, getQ, 0, addSquaredDiff);
  4840. },
  4841. manhattan: function manhattan(length, getP, getQ) {
  4842. return getDistance(length, getP, getQ, 0, addAbsDiff);
  4843. },
  4844. max: function max(length, getP, getQ) {
  4845. return getDistance(length, getP, getQ, -Infinity, maxAbsDiff);
  4846. }
  4847. };
  4848. // in case the user accidentally doesn't use camel case
  4849. distances['squared-euclidean'] = distances['squaredEuclidean'];
  4850. distances['squaredeuclidean'] = distances['squaredEuclidean'];
  4851. function clusteringDistance (method, length, getP, getQ, nodeP, nodeQ) {
  4852. var impl;
  4853. if (fn$6(method)) {
  4854. impl = method;
  4855. } else {
  4856. impl = distances[method] || distances.euclidean;
  4857. }
  4858. if (length === 0 && fn$6(method)) {
  4859. return impl(nodeP, nodeQ);
  4860. } else {
  4861. return impl(length, getP, getQ, nodeP, nodeQ);
  4862. }
  4863. }
  4864. var defaults$b = defaults$g({
  4865. k: 2,
  4866. m: 2,
  4867. sensitivityThreshold: 0.0001,
  4868. distance: 'euclidean',
  4869. maxIterations: 10,
  4870. attributes: [],
  4871. testMode: false,
  4872. testCentroids: null
  4873. });
  4874. var setOptions$2 = function setOptions(options) {
  4875. return defaults$b(options);
  4876. };
  4877. var getDist = function getDist(type, node, centroid, attributes, mode) {
  4878. var noNodeP = mode !== 'kMedoids';
  4879. var getP = noNodeP ? function (i) {
  4880. return centroid[i];
  4881. } : function (i) {
  4882. return attributes[i](centroid);
  4883. };
  4884. var getQ = function getQ(i) {
  4885. return attributes[i](node);
  4886. };
  4887. var nodeP = centroid;
  4888. var nodeQ = node;
  4889. return clusteringDistance(type, attributes.length, getP, getQ, nodeP, nodeQ);
  4890. };
  4891. var randomCentroids = function randomCentroids(nodes, k, attributes) {
  4892. var ndim = attributes.length;
  4893. var min = new Array(ndim);
  4894. var max = new Array(ndim);
  4895. var centroids = new Array(k);
  4896. var centroid = null;
  4897. // Find min, max values for each attribute dimension
  4898. for (var i = 0; i < ndim; i++) {
  4899. min[i] = nodes.min(attributes[i]).value;
  4900. max[i] = nodes.max(attributes[i]).value;
  4901. }
  4902. // Build k centroids, each represented as an n-dim feature vector
  4903. for (var c = 0; c < k; c++) {
  4904. centroid = [];
  4905. for (var _i = 0; _i < ndim; _i++) {
  4906. centroid[_i] = Math.random() * (max[_i] - min[_i]) + min[_i]; // random initial value
  4907. }
  4908. centroids[c] = centroid;
  4909. }
  4910. return centroids;
  4911. };
  4912. var classify = function classify(node, centroids, distance, attributes, type) {
  4913. var min = Infinity;
  4914. var index = 0;
  4915. for (var i = 0; i < centroids.length; i++) {
  4916. var dist = getDist(distance, node, centroids[i], attributes, type);
  4917. if (dist < min) {
  4918. min = dist;
  4919. index = i;
  4920. }
  4921. }
  4922. return index;
  4923. };
  4924. var buildCluster = function buildCluster(centroid, nodes, assignment) {
  4925. var cluster = [];
  4926. var node = null;
  4927. for (var n = 0; n < nodes.length; n++) {
  4928. node = nodes[n];
  4929. if (assignment[node.id()] === centroid) {
  4930. //console.log("Node " + node.id() + " is associated with medoid #: " + m);
  4931. cluster.push(node);
  4932. }
  4933. }
  4934. return cluster;
  4935. };
  4936. var haveValuesConverged = function haveValuesConverged(v1, v2, sensitivityThreshold) {
  4937. return Math.abs(v2 - v1) <= sensitivityThreshold;
  4938. };
  4939. var haveMatricesConverged = function haveMatricesConverged(v1, v2, sensitivityThreshold) {
  4940. for (var i = 0; i < v1.length; i++) {
  4941. for (var j = 0; j < v1[i].length; j++) {
  4942. var diff = Math.abs(v1[i][j] - v2[i][j]);
  4943. if (diff > sensitivityThreshold) {
  4944. return false;
  4945. }
  4946. }
  4947. }
  4948. return true;
  4949. };
  4950. var seenBefore = function seenBefore(node, medoids, n) {
  4951. for (var i = 0; i < n; i++) {
  4952. if (node === medoids[i]) return true;
  4953. }
  4954. return false;
  4955. };
  4956. var randomMedoids = function randomMedoids(nodes, k) {
  4957. var medoids = new Array(k);
  4958. // For small data sets, the probability of medoid conflict is greater,
  4959. // so we need to check to see if we've already seen or chose this node before.
  4960. if (nodes.length < 50) {
  4961. // Randomly select k medoids from the n nodes
  4962. for (var i = 0; i < k; i++) {
  4963. var node = nodes[Math.floor(Math.random() * nodes.length)];
  4964. // If we've already chosen this node to be a medoid, don't choose it again (for small data sets).
  4965. // Instead choose a different random node.
  4966. while (seenBefore(node, medoids, i)) {
  4967. node = nodes[Math.floor(Math.random() * nodes.length)];
  4968. }
  4969. medoids[i] = node;
  4970. }
  4971. } else {
  4972. // Relatively large data set, so pretty safe to not check and just select random nodes
  4973. for (var _i2 = 0; _i2 < k; _i2++) {
  4974. medoids[_i2] = nodes[Math.floor(Math.random() * nodes.length)];
  4975. }
  4976. }
  4977. return medoids;
  4978. };
  4979. var findCost = function findCost(potentialNewMedoid, cluster, attributes) {
  4980. var cost = 0;
  4981. for (var n = 0; n < cluster.length; n++) {
  4982. cost += getDist('manhattan', cluster[n], potentialNewMedoid, attributes, 'kMedoids');
  4983. }
  4984. return cost;
  4985. };
  4986. var kMeans = function kMeans(options) {
  4987. var cy = this.cy();
  4988. var nodes = this.nodes();
  4989. var node = null;
  4990. // Set parameters of algorithm: # of clusters, distance metric, etc.
  4991. var opts = setOptions$2(options);
  4992. // Begin k-means algorithm
  4993. var clusters = new Array(opts.k);
  4994. var assignment = {};
  4995. var centroids;
  4996. // Step 1: Initialize centroid positions
  4997. if (opts.testMode) {
  4998. if (typeof opts.testCentroids === 'number') {
  4999. // TODO: implement a seeded random number generator.
  5000. opts.testCentroids;
  5001. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5002. } else if (_typeof(opts.testCentroids) === 'object') {
  5003. centroids = opts.testCentroids;
  5004. } else {
  5005. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5006. }
  5007. } else {
  5008. centroids = randomCentroids(nodes, opts.k, opts.attributes);
  5009. }
  5010. var isStillMoving = true;
  5011. var iterations = 0;
  5012. while (isStillMoving && iterations < opts.maxIterations) {
  5013. // Step 2: Assign nodes to the nearest centroid
  5014. for (var n = 0; n < nodes.length; n++) {
  5015. node = nodes[n];
  5016. // Determine which cluster this node belongs to: node id => cluster #
  5017. assignment[node.id()] = classify(node, centroids, opts.distance, opts.attributes, 'kMeans');
  5018. }
  5019. // Step 3: For each of the k clusters, update its centroid
  5020. isStillMoving = false;
  5021. for (var c = 0; c < opts.k; c++) {
  5022. // Get all nodes that belong to this cluster
  5023. var cluster = buildCluster(c, nodes, assignment);
  5024. if (cluster.length === 0) {
  5025. // If cluster is empty, break out early & move to next cluster
  5026. continue;
  5027. }
  5028. // Update centroids by calculating avg of all nodes within the cluster.
  5029. var ndim = opts.attributes.length;
  5030. var centroid = centroids[c]; // [ dim_1, dim_2, dim_3, ... , dim_n ]
  5031. var newCentroid = new Array(ndim);
  5032. var sum = new Array(ndim);
  5033. for (var d = 0; d < ndim; d++) {
  5034. sum[d] = 0.0;
  5035. for (var i = 0; i < cluster.length; i++) {
  5036. node = cluster[i];
  5037. sum[d] += opts.attributes[d](node);
  5038. }
  5039. newCentroid[d] = sum[d] / cluster.length;
  5040. // Check to see if algorithm has converged, i.e. when centroids no longer change
  5041. if (!haveValuesConverged(newCentroid[d], centroid[d], opts.sensitivityThreshold)) {
  5042. isStillMoving = true;
  5043. }
  5044. }
  5045. centroids[c] = newCentroid;
  5046. clusters[c] = cy.collection(cluster);
  5047. }
  5048. iterations++;
  5049. }
  5050. return clusters;
  5051. };
  5052. var kMedoids = function kMedoids(options) {
  5053. var cy = this.cy();
  5054. var nodes = this.nodes();
  5055. var node = null;
  5056. var opts = setOptions$2(options);
  5057. // Begin k-medoids algorithm
  5058. var clusters = new Array(opts.k);
  5059. var medoids;
  5060. var assignment = {};
  5061. var curCost;
  5062. var minCosts = new Array(opts.k); // minimum cost configuration for each cluster
  5063. // Step 1: Initialize k medoids
  5064. if (opts.testMode) {
  5065. if (typeof opts.testCentroids === 'number') ; else if (_typeof(opts.testCentroids) === 'object') {
  5066. medoids = opts.testCentroids;
  5067. } else {
  5068. medoids = randomMedoids(nodes, opts.k);
  5069. }
  5070. } else {
  5071. medoids = randomMedoids(nodes, opts.k);
  5072. }
  5073. var isStillMoving = true;
  5074. var iterations = 0;
  5075. while (isStillMoving && iterations < opts.maxIterations) {
  5076. // Step 2: Assign nodes to the nearest medoid
  5077. for (var n = 0; n < nodes.length; n++) {
  5078. node = nodes[n];
  5079. // Determine which cluster this node belongs to: node id => cluster #
  5080. assignment[node.id()] = classify(node, medoids, opts.distance, opts.attributes, 'kMedoids');
  5081. }
  5082. isStillMoving = false;
  5083. // Step 3: For each medoid m, and for each node associated with mediod m,
  5084. // select the node with the lowest configuration cost as new medoid.
  5085. for (var m = 0; m < medoids.length; m++) {
  5086. // Get all nodes that belong to this medoid
  5087. var cluster = buildCluster(m, nodes, assignment);
  5088. if (cluster.length === 0) {
  5089. // If cluster is empty, break out early & move to next cluster
  5090. continue;
  5091. }
  5092. minCosts[m] = findCost(medoids[m], cluster, opts.attributes); // original cost
  5093. // Select different medoid if its configuration has the lowest cost
  5094. for (var _n = 0; _n < cluster.length; _n++) {
  5095. curCost = findCost(cluster[_n], cluster, opts.attributes);
  5096. if (curCost < minCosts[m]) {
  5097. minCosts[m] = curCost;
  5098. medoids[m] = cluster[_n];
  5099. isStillMoving = true;
  5100. }
  5101. }
  5102. clusters[m] = cy.collection(cluster);
  5103. }
  5104. iterations++;
  5105. }
  5106. return clusters;
  5107. };
  5108. var updateCentroids = function updateCentroids(centroids, nodes, U, weight, opts) {
  5109. var numerator, denominator;
  5110. for (var n = 0; n < nodes.length; n++) {
  5111. for (var c = 0; c < centroids.length; c++) {
  5112. weight[n][c] = Math.pow(U[n][c], opts.m);
  5113. }
  5114. }
  5115. for (var _c = 0; _c < centroids.length; _c++) {
  5116. for (var dim = 0; dim < opts.attributes.length; dim++) {
  5117. numerator = 0;
  5118. denominator = 0;
  5119. for (var _n2 = 0; _n2 < nodes.length; _n2++) {
  5120. numerator += weight[_n2][_c] * opts.attributes[dim](nodes[_n2]);
  5121. denominator += weight[_n2][_c];
  5122. }
  5123. centroids[_c][dim] = numerator / denominator;
  5124. }
  5125. }
  5126. };
  5127. var updateMembership = function updateMembership(U, _U, centroids, nodes, opts) {
  5128. // Save previous step
  5129. for (var i = 0; i < U.length; i++) {
  5130. _U[i] = U[i].slice();
  5131. }
  5132. var sum, numerator, denominator;
  5133. var pow = 2 / (opts.m - 1);
  5134. for (var c = 0; c < centroids.length; c++) {
  5135. for (var n = 0; n < nodes.length; n++) {
  5136. sum = 0;
  5137. for (var k = 0; k < centroids.length; k++) {
  5138. // against all other centroids
  5139. numerator = getDist(opts.distance, nodes[n], centroids[c], opts.attributes, 'cmeans');
  5140. denominator = getDist(opts.distance, nodes[n], centroids[k], opts.attributes, 'cmeans');
  5141. sum += Math.pow(numerator / denominator, pow);
  5142. }
  5143. U[n][c] = 1 / sum;
  5144. }
  5145. }
  5146. };
  5147. var assign$1 = function assign(nodes, U, opts, cy) {
  5148. var clusters = new Array(opts.k);
  5149. for (var c = 0; c < clusters.length; c++) {
  5150. clusters[c] = [];
  5151. }
  5152. var max;
  5153. var index;
  5154. for (var n = 0; n < U.length; n++) {
  5155. // for each node (U is N x C matrix)
  5156. max = -Infinity;
  5157. index = -1;
  5158. // Determine which cluster the node is most likely to belong in
  5159. for (var _c2 = 0; _c2 < U[0].length; _c2++) {
  5160. if (U[n][_c2] > max) {
  5161. max = U[n][_c2];
  5162. index = _c2;
  5163. }
  5164. }
  5165. clusters[index].push(nodes[n]);
  5166. }
  5167. // Turn every array into a collection of nodes
  5168. for (var _c3 = 0; _c3 < clusters.length; _c3++) {
  5169. clusters[_c3] = cy.collection(clusters[_c3]);
  5170. }
  5171. return clusters;
  5172. };
  5173. var fuzzyCMeans = function fuzzyCMeans(options) {
  5174. var cy = this.cy();
  5175. var nodes = this.nodes();
  5176. var opts = setOptions$2(options);
  5177. // Begin fuzzy c-means algorithm
  5178. var clusters;
  5179. var centroids;
  5180. var U;
  5181. var _U;
  5182. var weight;
  5183. // Step 1: Initialize letiables.
  5184. _U = new Array(nodes.length);
  5185. for (var i = 0; i < nodes.length; i++) {
  5186. // N x C matrix
  5187. _U[i] = new Array(opts.k);
  5188. }
  5189. U = new Array(nodes.length);
  5190. for (var _i3 = 0; _i3 < nodes.length; _i3++) {
  5191. // N x C matrix
  5192. U[_i3] = new Array(opts.k);
  5193. }
  5194. for (var _i4 = 0; _i4 < nodes.length; _i4++) {
  5195. var total = 0;
  5196. for (var j = 0; j < opts.k; j++) {
  5197. U[_i4][j] = Math.random();
  5198. total += U[_i4][j];
  5199. }
  5200. for (var _j = 0; _j < opts.k; _j++) {
  5201. U[_i4][_j] = U[_i4][_j] / total;
  5202. }
  5203. }
  5204. centroids = new Array(opts.k);
  5205. for (var _i5 = 0; _i5 < opts.k; _i5++) {
  5206. centroids[_i5] = new Array(opts.attributes.length);
  5207. }
  5208. weight = new Array(nodes.length);
  5209. for (var _i6 = 0; _i6 < nodes.length; _i6++) {
  5210. // N x C matrix
  5211. weight[_i6] = new Array(opts.k);
  5212. }
  5213. // end init FCM
  5214. var isStillMoving = true;
  5215. var iterations = 0;
  5216. while (isStillMoving && iterations < opts.maxIterations) {
  5217. isStillMoving = false;
  5218. // Step 2: Calculate the centroids for each step.
  5219. updateCentroids(centroids, nodes, U, weight, opts);
  5220. // Step 3: Update the partition matrix U.
  5221. updateMembership(U, _U, centroids, nodes, opts);
  5222. // Step 4: Check for convergence.
  5223. if (!haveMatricesConverged(U, _U, opts.sensitivityThreshold)) {
  5224. isStillMoving = true;
  5225. }
  5226. iterations++;
  5227. }
  5228. // Assign nodes to clusters with highest probability.
  5229. clusters = assign$1(nodes, U, opts, cy);
  5230. return {
  5231. clusters: clusters,
  5232. degreeOfMembership: U
  5233. };
  5234. };
  5235. var kClustering = {
  5236. kMeans: kMeans,
  5237. kMedoids: kMedoids,
  5238. fuzzyCMeans: fuzzyCMeans,
  5239. fcm: fuzzyCMeans
  5240. };
  5241. // Implemented by Zoe Xi @zoexi for GSOC 2016
  5242. // https://github.com/cytoscape/cytoscape.js-hierarchical
  5243. var defaults$a = defaults$g({
  5244. distance: 'euclidean',
  5245. // distance metric to compare nodes
  5246. linkage: 'min',
  5247. // linkage criterion : how to determine the distance between clusters of nodes
  5248. mode: 'threshold',
  5249. // mode:'threshold' => clusters must be threshold distance apart
  5250. threshold: Infinity,
  5251. // the distance threshold
  5252. // mode:'dendrogram' => the nodes are organised as leaves in a tree (siblings are close), merging makes clusters
  5253. addDendrogram: false,
  5254. // whether to add the dendrogram to the graph for viz
  5255. dendrogramDepth: 0,
  5256. // depth at which dendrogram branches are merged into the returned clusters
  5257. attributes: [] // array of attr functions
  5258. });
  5259. var linkageAliases = {
  5260. 'single': 'min',
  5261. 'complete': 'max'
  5262. };
  5263. var setOptions$1 = function setOptions(options) {
  5264. var opts = defaults$a(options);
  5265. var preferredAlias = linkageAliases[opts.linkage];
  5266. if (preferredAlias != null) {
  5267. opts.linkage = preferredAlias;
  5268. }
  5269. return opts;
  5270. };
  5271. var mergeClosest = function mergeClosest(clusters, index, dists, mins, opts) {
  5272. // Find two closest clusters from cached mins
  5273. var minKey = 0;
  5274. var min = Infinity;
  5275. var dist;
  5276. var attrs = opts.attributes;
  5277. var getDist = function getDist(n1, n2) {
  5278. return clusteringDistance(opts.distance, attrs.length, function (i) {
  5279. return attrs[i](n1);
  5280. }, function (i) {
  5281. return attrs[i](n2);
  5282. }, n1, n2);
  5283. };
  5284. for (var i = 0; i < clusters.length; i++) {
  5285. var key = clusters[i].key;
  5286. var _dist = dists[key][mins[key]];
  5287. if (_dist < min) {
  5288. minKey = key;
  5289. min = _dist;
  5290. }
  5291. }
  5292. if (opts.mode === 'threshold' && min >= opts.threshold || opts.mode === 'dendrogram' && clusters.length === 1) {
  5293. return false;
  5294. }
  5295. var c1 = index[minKey];
  5296. var c2 = index[mins[minKey]];
  5297. var merged;
  5298. // Merge two closest clusters
  5299. if (opts.mode === 'dendrogram') {
  5300. merged = {
  5301. left: c1,
  5302. right: c2,
  5303. key: c1.key
  5304. };
  5305. } else {
  5306. merged = {
  5307. value: c1.value.concat(c2.value),
  5308. key: c1.key
  5309. };
  5310. }
  5311. clusters[c1.index] = merged;
  5312. clusters.splice(c2.index, 1);
  5313. index[c1.key] = merged;
  5314. // Update distances with new merged cluster
  5315. for (var _i = 0; _i < clusters.length; _i++) {
  5316. var cur = clusters[_i];
  5317. if (c1.key === cur.key) {
  5318. dist = Infinity;
  5319. } else if (opts.linkage === 'min') {
  5320. dist = dists[c1.key][cur.key];
  5321. if (dists[c1.key][cur.key] > dists[c2.key][cur.key]) {
  5322. dist = dists[c2.key][cur.key];
  5323. }
  5324. } else if (opts.linkage === 'max') {
  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 === 'mean') {
  5330. dist = (dists[c1.key][cur.key] * c1.size + dists[c2.key][cur.key] * c2.size) / (c1.size + c2.size);
  5331. } else {
  5332. if (opts.mode === 'dendrogram') dist = getDist(cur.value, c1.value);else dist = getDist(cur.value[0], c1.value[0]);
  5333. }
  5334. dists[c1.key][cur.key] = dists[cur.key][c1.key] = dist; // distance matrix is symmetric
  5335. }
  5336. // Update cached mins
  5337. for (var _i2 = 0; _i2 < clusters.length; _i2++) {
  5338. var key1 = clusters[_i2].key;
  5339. if (mins[key1] === c1.key || mins[key1] === c2.key) {
  5340. var _min = key1;
  5341. for (var j = 0; j < clusters.length; j++) {
  5342. var key2 = clusters[j].key;
  5343. if (dists[key1][key2] < dists[key1][_min]) {
  5344. _min = key2;
  5345. }
  5346. }
  5347. mins[key1] = _min;
  5348. }
  5349. clusters[_i2].index = _i2;
  5350. }
  5351. // Clean up meta data used for clustering
  5352. c1.key = c2.key = c1.index = c2.index = null;
  5353. return true;
  5354. };
  5355. var _getAllChildren = function getAllChildren(root, arr, cy) {
  5356. if (!root) return;
  5357. if (root.value) {
  5358. arr.push(root.value);
  5359. } else {
  5360. if (root.left) _getAllChildren(root.left, arr);
  5361. if (root.right) _getAllChildren(root.right, arr);
  5362. }
  5363. };
  5364. var _buildDendrogram = function buildDendrogram(root, cy) {
  5365. if (!root) return '';
  5366. if (root.left && root.right) {
  5367. var leftStr = _buildDendrogram(root.left, cy);
  5368. var rightStr = _buildDendrogram(root.right, cy);
  5369. var node = cy.add({
  5370. group: 'nodes',
  5371. data: {
  5372. id: leftStr + ',' + rightStr
  5373. }
  5374. });
  5375. cy.add({
  5376. group: 'edges',
  5377. data: {
  5378. source: leftStr,
  5379. target: node.id()
  5380. }
  5381. });
  5382. cy.add({
  5383. group: 'edges',
  5384. data: {
  5385. source: rightStr,
  5386. target: node.id()
  5387. }
  5388. });
  5389. return node.id();
  5390. } else if (root.value) {
  5391. return root.value.id();
  5392. }
  5393. };
  5394. var _buildClustersFromTree = function buildClustersFromTree(root, k, cy) {
  5395. if (!root) return [];
  5396. var left = [],
  5397. right = [],
  5398. leaves = [];
  5399. if (k === 0) {
  5400. // don't cut tree, simply return all nodes as 1 single cluster
  5401. if (root.left) _getAllChildren(root.left, left);
  5402. if (root.right) _getAllChildren(root.right, right);
  5403. leaves = left.concat(right);
  5404. return [cy.collection(leaves)];
  5405. } else if (k === 1) {
  5406. // cut at root
  5407. if (root.value) {
  5408. // leaf node
  5409. return [cy.collection(root.value)];
  5410. } else {
  5411. if (root.left) _getAllChildren(root.left, left);
  5412. if (root.right) _getAllChildren(root.right, right);
  5413. return [cy.collection(left), cy.collection(right)];
  5414. }
  5415. } else {
  5416. if (root.value) {
  5417. return [cy.collection(root.value)];
  5418. } else {
  5419. if (root.left) left = _buildClustersFromTree(root.left, k - 1, cy);
  5420. if (root.right) right = _buildClustersFromTree(root.right, k - 1, cy);
  5421. return left.concat(right);
  5422. }
  5423. }
  5424. };
  5425. var hierarchicalClustering = function hierarchicalClustering(options) {
  5426. var cy = this.cy();
  5427. var nodes = this.nodes();
  5428. // Set parameters of algorithm: linkage type, distance metric, etc.
  5429. var opts = setOptions$1(options);
  5430. var attrs = opts.attributes;
  5431. var getDist = function getDist(n1, n2) {
  5432. return clusteringDistance(opts.distance, attrs.length, function (i) {
  5433. return attrs[i](n1);
  5434. }, function (i) {
  5435. return attrs[i](n2);
  5436. }, n1, n2);
  5437. };
  5438. // Begin hierarchical algorithm
  5439. var clusters = [];
  5440. var dists = []; // distances between each pair of clusters
  5441. var mins = []; // closest cluster for each cluster
  5442. var index = []; // hash of all clusters by key
  5443. // In agglomerative (bottom-up) clustering, each node starts as its own cluster
  5444. for (var n = 0; n < nodes.length; n++) {
  5445. var cluster = {
  5446. value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],
  5447. key: n,
  5448. index: n
  5449. };
  5450. clusters[n] = cluster;
  5451. index[n] = cluster;
  5452. dists[n] = [];
  5453. mins[n] = 0;
  5454. }
  5455. // Calculate the distance between each pair of clusters
  5456. for (var i = 0; i < clusters.length; i++) {
  5457. for (var j = 0; j <= i; j++) {
  5458. var dist = undefined;
  5459. if (opts.mode === 'dendrogram') {
  5460. // modes store cluster values differently
  5461. dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);
  5462. } else {
  5463. dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);
  5464. }
  5465. dists[i][j] = dist;
  5466. dists[j][i] = dist;
  5467. if (dist < dists[i][mins[i]]) {
  5468. mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j
  5469. }
  5470. }
  5471. }
  5472. // Find the closest pair of clusters and merge them into a single cluster.
  5473. // Update distances between new cluster and each of the old clusters, and loop until threshold reached.
  5474. var merged = mergeClosest(clusters, index, dists, mins, opts);
  5475. while (merged) {
  5476. merged = mergeClosest(clusters, index, dists, mins, opts);
  5477. }
  5478. var retClusters;
  5479. // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges
  5480. // in addition to returning the clusters.
  5481. if (opts.mode === 'dendrogram') {
  5482. retClusters = _buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);
  5483. if (opts.addDendrogram) _buildDendrogram(clusters[0], cy);
  5484. } else {
  5485. // Regular mode simply returns the clusters
  5486. retClusters = new Array(clusters.length);
  5487. clusters.forEach(function (cluster, i) {
  5488. // Clean up meta data used for clustering
  5489. cluster.key = cluster.index = null;
  5490. retClusters[i] = cy.collection(cluster.value);
  5491. });
  5492. }
  5493. return retClusters;
  5494. };
  5495. var hierarchicalClustering$1 = {
  5496. hierarchicalClustering: hierarchicalClustering,
  5497. hca: hierarchicalClustering
  5498. };
  5499. // Implemented by Zoe Xi @zoexi for GSOC 2016
  5500. // https://github.com/cytoscape/cytoscape.js-affinity-propagation
  5501. var defaults$9 = defaults$g({
  5502. distance: 'euclidean',
  5503. // distance metric to compare attributes between two nodes
  5504. preference: 'median',
  5505. // suitability of a data point to serve as an exemplar
  5506. damping: 0.8,
  5507. // damping factor between [0.5, 1)
  5508. maxIterations: 1000,
  5509. // max number of iterations to run
  5510. minIterations: 100,
  5511. // min number of iterations to run in order for clustering to stop
  5512. attributes: [// functions to quantify the similarity between any two points
  5513. // e.g. node => node.data('weight')
  5514. ]
  5515. });
  5516. var setOptions = function setOptions(options) {
  5517. var dmp = options.damping;
  5518. var pref = options.preference;
  5519. if (!(0.5 <= dmp && dmp < 1)) {
  5520. error("Damping must range on [0.5, 1). Got: ".concat(dmp));
  5521. }
  5522. var validPrefs = ['median', 'mean', 'min', 'max'];
  5523. if (!(validPrefs.some(function (v) {
  5524. return v === pref;
  5525. }) || number$1(pref))) {
  5526. error("Preference must be one of [".concat(validPrefs.map(function (p) {
  5527. return "'".concat(p, "'");
  5528. }).join(', '), "] or a number. Got: ").concat(pref));
  5529. }
  5530. return defaults$9(options);
  5531. };
  5532. var getSimilarity = function getSimilarity(type, n1, n2, attributes) {
  5533. var attr = function attr(n, i) {
  5534. return attributes[i](n);
  5535. };
  5536. // nb negative because similarity should have an inverse relationship to distance
  5537. return -clusteringDistance(type, attributes.length, function (i) {
  5538. return attr(n1, i);
  5539. }, function (i) {
  5540. return attr(n2, i);
  5541. }, n1, n2);
  5542. };
  5543. var getPreference = function getPreference(S, preference) {
  5544. // larger preference = greater # of clusters
  5545. var p = null;
  5546. if (preference === 'median') {
  5547. p = median(S);
  5548. } else if (preference === 'mean') {
  5549. p = mean(S);
  5550. } else if (preference === 'min') {
  5551. p = min(S);
  5552. } else if (preference === 'max') {
  5553. p = max(S);
  5554. } else {
  5555. // Custom preference number, as set by user
  5556. p = preference;
  5557. }
  5558. return p;
  5559. };
  5560. var findExemplars = function findExemplars(n, R, A) {
  5561. var indices = [];
  5562. for (var i = 0; i < n; i++) {
  5563. if (R[i * n + i] + A[i * n + i] > 0) {
  5564. indices.push(i);
  5565. }
  5566. }
  5567. return indices;
  5568. };
  5569. var assignClusters = function assignClusters(n, S, exemplars) {
  5570. var clusters = [];
  5571. for (var i = 0; i < n; i++) {
  5572. var index = -1;
  5573. var max = -Infinity;
  5574. for (var ei = 0; ei < exemplars.length; ei++) {
  5575. var e = exemplars[ei];
  5576. if (S[i * n + e] > max) {
  5577. index = e;
  5578. max = S[i * n + e];
  5579. }
  5580. }
  5581. if (index > 0) {
  5582. clusters.push(index);
  5583. }
  5584. }
  5585. for (var _ei = 0; _ei < exemplars.length; _ei++) {
  5586. clusters[exemplars[_ei]] = exemplars[_ei];
  5587. }
  5588. return clusters;
  5589. };
  5590. var assign = function assign(n, S, exemplars) {
  5591. var clusters = assignClusters(n, S, exemplars);
  5592. for (var ei = 0; ei < exemplars.length; ei++) {
  5593. var ii = [];
  5594. for (var c = 0; c < clusters.length; c++) {
  5595. if (clusters[c] === exemplars[ei]) {
  5596. ii.push(c);
  5597. }
  5598. }
  5599. var maxI = -1;
  5600. var maxSum = -Infinity;
  5601. for (var i = 0; i < ii.length; i++) {
  5602. var sum = 0;
  5603. for (var j = 0; j < ii.length; j++) {
  5604. sum += S[ii[j] * n + ii[i]];
  5605. }
  5606. if (sum > maxSum) {
  5607. maxI = i;
  5608. maxSum = sum;
  5609. }
  5610. }
  5611. exemplars[ei] = ii[maxI];
  5612. }
  5613. clusters = assignClusters(n, S, exemplars);
  5614. return clusters;
  5615. };
  5616. var affinityPropagation = function affinityPropagation(options) {
  5617. var cy = this.cy();
  5618. var nodes = this.nodes();
  5619. var opts = setOptions(options);
  5620. // Map each node to its position in node array
  5621. var id2position = {};
  5622. for (var i = 0; i < nodes.length; i++) {
  5623. id2position[nodes[i].id()] = i;
  5624. }
  5625. // Begin affinity propagation algorithm
  5626. var n; // number of data points
  5627. var n2; // size of matrices
  5628. var S; // similarity matrix (1D array)
  5629. var p; // preference/suitability of a data point to serve as an exemplar
  5630. var R; // responsibility matrix (1D array)
  5631. var A; // availability matrix (1D array)
  5632. n = nodes.length;
  5633. n2 = n * n;
  5634. // Initialize and build S similarity matrix
  5635. S = new Array(n2);
  5636. for (var _i = 0; _i < n2; _i++) {
  5637. S[_i] = -Infinity; // for cases where two data points shouldn't be linked together
  5638. }
  5639. for (var _i2 = 0; _i2 < n; _i2++) {
  5640. for (var j = 0; j < n; j++) {
  5641. if (_i2 !== j) {
  5642. S[_i2 * n + j] = getSimilarity(opts.distance, nodes[_i2], nodes[j], opts.attributes);
  5643. }
  5644. }
  5645. }
  5646. // Place preferences on the diagonal of S
  5647. p = getPreference(S, opts.preference);
  5648. for (var _i3 = 0; _i3 < n; _i3++) {
  5649. S[_i3 * n + _i3] = p;
  5650. }
  5651. // Initialize R responsibility matrix
  5652. R = new Array(n2);
  5653. for (var _i4 = 0; _i4 < n2; _i4++) {
  5654. R[_i4] = 0.0;
  5655. }
  5656. // Initialize A availability matrix
  5657. A = new Array(n2);
  5658. for (var _i5 = 0; _i5 < n2; _i5++) {
  5659. A[_i5] = 0.0;
  5660. }
  5661. var old = new Array(n);
  5662. var Rp = new Array(n);
  5663. var se = new Array(n);
  5664. for (var _i6 = 0; _i6 < n; _i6++) {
  5665. old[_i6] = 0.0;
  5666. Rp[_i6] = 0.0;
  5667. se[_i6] = 0;
  5668. }
  5669. var e = new Array(n * opts.minIterations);
  5670. for (var _i7 = 0; _i7 < e.length; _i7++) {
  5671. e[_i7] = 0;
  5672. }
  5673. var iter;
  5674. for (iter = 0; iter < opts.maxIterations; iter++) {
  5675. // main algorithmic loop
  5676. // Update R responsibility matrix
  5677. for (var _i8 = 0; _i8 < n; _i8++) {
  5678. var max = -Infinity,
  5679. max2 = -Infinity,
  5680. maxI = -1,
  5681. AS = 0.0;
  5682. for (var _j = 0; _j < n; _j++) {
  5683. old[_j] = R[_i8 * n + _j];
  5684. AS = A[_i8 * n + _j] + S[_i8 * n + _j];
  5685. if (AS >= max) {
  5686. max2 = max;
  5687. max = AS;
  5688. maxI = _j;
  5689. } else if (AS > max2) {
  5690. max2 = AS;
  5691. }
  5692. }
  5693. for (var _j2 = 0; _j2 < n; _j2++) {
  5694. R[_i8 * n + _j2] = (1 - opts.damping) * (S[_i8 * n + _j2] - max) + opts.damping * old[_j2];
  5695. }
  5696. R[_i8 * n + maxI] = (1 - opts.damping) * (S[_i8 * n + maxI] - max2) + opts.damping * old[maxI];
  5697. }
  5698. // Update A availability matrix
  5699. for (var _i9 = 0; _i9 < n; _i9++) {
  5700. var sum = 0;
  5701. for (var _j3 = 0; _j3 < n; _j3++) {
  5702. old[_j3] = A[_j3 * n + _i9];
  5703. Rp[_j3] = Math.max(0, R[_j3 * n + _i9]);
  5704. sum += Rp[_j3];
  5705. }
  5706. sum -= Rp[_i9];
  5707. Rp[_i9] = R[_i9 * n + _i9];
  5708. sum += Rp[_i9];
  5709. for (var _j4 = 0; _j4 < n; _j4++) {
  5710. A[_j4 * n + _i9] = (1 - opts.damping) * Math.min(0, sum - Rp[_j4]) + opts.damping * old[_j4];
  5711. }
  5712. A[_i9 * n + _i9] = (1 - opts.damping) * (sum - Rp[_i9]) + opts.damping * old[_i9];
  5713. }
  5714. // Check for convergence
  5715. var K = 0;
  5716. for (var _i10 = 0; _i10 < n; _i10++) {
  5717. var E = A[_i10 * n + _i10] + R[_i10 * n + _i10] > 0 ? 1 : 0;
  5718. e[iter % opts.minIterations * n + _i10] = E;
  5719. K += E;
  5720. }
  5721. if (K > 0 && (iter >= opts.minIterations - 1 || iter == opts.maxIterations - 1)) {
  5722. var _sum = 0;
  5723. for (var _i11 = 0; _i11 < n; _i11++) {
  5724. se[_i11] = 0;
  5725. for (var _j5 = 0; _j5 < opts.minIterations; _j5++) {
  5726. se[_i11] += e[_j5 * n + _i11];
  5727. }
  5728. if (se[_i11] === 0 || se[_i11] === opts.minIterations) {
  5729. _sum++;
  5730. }
  5731. }
  5732. if (_sum === n) {
  5733. // then we have convergence
  5734. break;
  5735. }
  5736. }
  5737. }
  5738. // Identify exemplars (cluster centers)
  5739. var exemplarsIndices = findExemplars(n, R, A);
  5740. // Assign nodes to clusters
  5741. var clusterIndices = assign(n, S, exemplarsIndices);
  5742. var clusters = {};
  5743. for (var c = 0; c < exemplarsIndices.length; c++) {
  5744. clusters[exemplarsIndices[c]] = [];
  5745. }
  5746. for (var _i12 = 0; _i12 < nodes.length; _i12++) {
  5747. var pos = id2position[nodes[_i12].id()];
  5748. var clusterIndex = clusterIndices[pos];
  5749. if (clusterIndex != null) {
  5750. // the node may have not been assigned a cluster if no valid attributes were specified
  5751. clusters[clusterIndex].push(nodes[_i12]);
  5752. }
  5753. }
  5754. var retClusters = new Array(exemplarsIndices.length);
  5755. for (var _c = 0; _c < exemplarsIndices.length; _c++) {
  5756. retClusters[_c] = cy.collection(clusters[exemplarsIndices[_c]]);
  5757. }
  5758. return retClusters;
  5759. };
  5760. var affinityPropagation$1 = {
  5761. affinityPropagation: affinityPropagation,
  5762. ap: affinityPropagation
  5763. };
  5764. var hierholzerDefaults = defaults$g({
  5765. root: undefined,
  5766. directed: false
  5767. });
  5768. var elesfn$k = {
  5769. hierholzer: function hierholzer(options) {
  5770. if (!plainObject(options)) {
  5771. var args = arguments;
  5772. options = {
  5773. root: args[0],
  5774. directed: args[1]
  5775. };
  5776. }
  5777. var _hierholzerDefaults = hierholzerDefaults(options),
  5778. root = _hierholzerDefaults.root,
  5779. directed = _hierholzerDefaults.directed;
  5780. var eles = this;
  5781. var dflag = false;
  5782. var oddIn;
  5783. var oddOut;
  5784. var startVertex;
  5785. if (root) startVertex = string(root) ? this.filter(root)[0].id() : root[0].id();
  5786. var nodes = {};
  5787. var edges = {};
  5788. if (directed) {
  5789. eles.forEach(function (ele) {
  5790. var id = ele.id();
  5791. if (ele.isNode()) {
  5792. var ind = ele.indegree(true);
  5793. var outd = ele.outdegree(true);
  5794. var d1 = ind - outd;
  5795. var d2 = outd - ind;
  5796. if (d1 == 1) {
  5797. if (oddIn) dflag = true;else oddIn = id;
  5798. } else if (d2 == 1) {
  5799. if (oddOut) dflag = true;else oddOut = id;
  5800. } else if (d2 > 1 || d1 > 1) {
  5801. dflag = true;
  5802. }
  5803. nodes[id] = [];
  5804. ele.outgoers().forEach(function (e) {
  5805. if (e.isEdge()) nodes[id].push(e.id());
  5806. });
  5807. } else {
  5808. edges[id] = [undefined, ele.target().id()];
  5809. }
  5810. });
  5811. } else {
  5812. eles.forEach(function (ele) {
  5813. var id = ele.id();
  5814. if (ele.isNode()) {
  5815. var d = ele.degree(true);
  5816. if (d % 2) {
  5817. if (!oddIn) oddIn = id;else if (!oddOut) oddOut = id;else dflag = true;
  5818. }
  5819. nodes[id] = [];
  5820. ele.connectedEdges().forEach(function (e) {
  5821. return nodes[id].push(e.id());
  5822. });
  5823. } else {
  5824. edges[id] = [ele.source().id(), ele.target().id()];
  5825. }
  5826. });
  5827. }
  5828. var result = {
  5829. found: false,
  5830. trail: undefined
  5831. };
  5832. if (dflag) return result;else if (oddOut && oddIn) {
  5833. if (directed) {
  5834. if (startVertex && oddOut != startVertex) {
  5835. return result;
  5836. }
  5837. startVertex = oddOut;
  5838. } else {
  5839. if (startVertex && oddOut != startVertex && oddIn != startVertex) {
  5840. return result;
  5841. } else if (!startVertex) {
  5842. startVertex = oddOut;
  5843. }
  5844. }
  5845. } else {
  5846. if (!startVertex) startVertex = eles[0].id();
  5847. }
  5848. var walk = function walk(v) {
  5849. var currentNode = v;
  5850. var subtour = [v];
  5851. var adj, adjTail, adjHead;
  5852. while (nodes[currentNode].length) {
  5853. adj = nodes[currentNode].shift();
  5854. adjTail = edges[adj][0];
  5855. adjHead = edges[adj][1];
  5856. if (currentNode != adjHead) {
  5857. nodes[adjHead] = nodes[adjHead].filter(function (e) {
  5858. return e != adj;
  5859. });
  5860. currentNode = adjHead;
  5861. } else if (!directed && currentNode != adjTail) {
  5862. nodes[adjTail] = nodes[adjTail].filter(function (e) {
  5863. return e != adj;
  5864. });
  5865. currentNode = adjTail;
  5866. }
  5867. subtour.unshift(adj);
  5868. subtour.unshift(currentNode);
  5869. }
  5870. return subtour;
  5871. };
  5872. var trail = [];
  5873. var subtour = [];
  5874. subtour = walk(startVertex);
  5875. while (subtour.length != 1) {
  5876. if (nodes[subtour[0]].length == 0) {
  5877. trail.unshift(eles.getElementById(subtour.shift()));
  5878. trail.unshift(eles.getElementById(subtour.shift()));
  5879. } else {
  5880. subtour = walk(subtour.shift()).concat(subtour);
  5881. }
  5882. }
  5883. trail.unshift(eles.getElementById(subtour.shift())); // final node
  5884. for (var d in nodes) {
  5885. if (nodes[d].length) {
  5886. return result;
  5887. }
  5888. }
  5889. result.found = true;
  5890. result.trail = this.spawn(trail, true);
  5891. return result;
  5892. }
  5893. };
  5894. var hopcroftTarjanBiconnected = function hopcroftTarjanBiconnected() {
  5895. var eles = this;
  5896. var nodes = {};
  5897. var id = 0;
  5898. var edgeCount = 0;
  5899. var components = [];
  5900. var stack = [];
  5901. var visitedEdges = {};
  5902. var buildComponent = function buildComponent(x, y) {
  5903. var i = stack.length - 1;
  5904. var cutset = [];
  5905. var component = eles.spawn();
  5906. while (stack[i].x != x || stack[i].y != y) {
  5907. cutset.push(stack.pop().edge);
  5908. i--;
  5909. }
  5910. cutset.push(stack.pop().edge);
  5911. cutset.forEach(function (edge) {
  5912. var connectedNodes = edge.connectedNodes().intersection(eles);
  5913. component.merge(edge);
  5914. connectedNodes.forEach(function (node) {
  5915. var nodeId = node.id();
  5916. var connectedEdges = node.connectedEdges().intersection(eles);
  5917. component.merge(node);
  5918. if (!nodes[nodeId].cutVertex) {
  5919. component.merge(connectedEdges);
  5920. } else {
  5921. component.merge(connectedEdges.filter(function (edge) {
  5922. return edge.isLoop();
  5923. }));
  5924. }
  5925. });
  5926. });
  5927. components.push(component);
  5928. };
  5929. var _biconnectedSearch = function biconnectedSearch(root, currentNode, parent) {
  5930. if (root === parent) edgeCount += 1;
  5931. nodes[currentNode] = {
  5932. id: id,
  5933. low: id++,
  5934. cutVertex: false
  5935. };
  5936. var edges = eles.getElementById(currentNode).connectedEdges().intersection(eles);
  5937. if (edges.size() === 0) {
  5938. components.push(eles.spawn(eles.getElementById(currentNode)));
  5939. } else {
  5940. var sourceId, targetId, otherNodeId, edgeId;
  5941. edges.forEach(function (edge) {
  5942. sourceId = edge.source().id();
  5943. targetId = edge.target().id();
  5944. otherNodeId = sourceId === currentNode ? targetId : sourceId;
  5945. if (otherNodeId !== parent) {
  5946. edgeId = edge.id();
  5947. if (!visitedEdges[edgeId]) {
  5948. visitedEdges[edgeId] = true;
  5949. stack.push({
  5950. x: currentNode,
  5951. y: otherNodeId,
  5952. edge: edge
  5953. });
  5954. }
  5955. if (!(otherNodeId in nodes)) {
  5956. _biconnectedSearch(root, otherNodeId, currentNode);
  5957. nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].low);
  5958. if (nodes[currentNode].id <= nodes[otherNodeId].low) {
  5959. nodes[currentNode].cutVertex = true;
  5960. buildComponent(currentNode, otherNodeId);
  5961. }
  5962. } else {
  5963. nodes[currentNode].low = Math.min(nodes[currentNode].low, nodes[otherNodeId].id);
  5964. }
  5965. }
  5966. });
  5967. }
  5968. };
  5969. eles.forEach(function (ele) {
  5970. if (ele.isNode()) {
  5971. var nodeId = ele.id();
  5972. if (!(nodeId in nodes)) {
  5973. edgeCount = 0;
  5974. _biconnectedSearch(nodeId, nodeId);
  5975. nodes[nodeId].cutVertex = edgeCount > 1;
  5976. }
  5977. }
  5978. });
  5979. var cutVertices = Object.keys(nodes).filter(function (id) {
  5980. return nodes[id].cutVertex;
  5981. }).map(function (id) {
  5982. return eles.getElementById(id);
  5983. });
  5984. return {
  5985. cut: eles.spawn(cutVertices),
  5986. components: components
  5987. };
  5988. };
  5989. var hopcroftTarjanBiconnected$1 = {
  5990. hopcroftTarjanBiconnected: hopcroftTarjanBiconnected,
  5991. htbc: hopcroftTarjanBiconnected,
  5992. htb: hopcroftTarjanBiconnected,
  5993. hopcroftTarjanBiconnectedComponents: hopcroftTarjanBiconnected
  5994. };
  5995. var tarjanStronglyConnected = function tarjanStronglyConnected() {
  5996. var eles = this;
  5997. var nodes = {};
  5998. var index = 0;
  5999. var components = [];
  6000. var stack = [];
  6001. var cut = eles.spawn(eles);
  6002. var _stronglyConnectedSearch = function stronglyConnectedSearch(sourceNodeId) {
  6003. stack.push(sourceNodeId);
  6004. nodes[sourceNodeId] = {
  6005. index: index,
  6006. low: index++,
  6007. explored: false
  6008. };
  6009. var connectedEdges = eles.getElementById(sourceNodeId).connectedEdges().intersection(eles);
  6010. connectedEdges.forEach(function (edge) {
  6011. var targetNodeId = edge.target().id();
  6012. if (targetNodeId !== sourceNodeId) {
  6013. if (!(targetNodeId in nodes)) {
  6014. _stronglyConnectedSearch(targetNodeId);
  6015. }
  6016. if (!nodes[targetNodeId].explored) {
  6017. nodes[sourceNodeId].low = Math.min(nodes[sourceNodeId].low, nodes[targetNodeId].low);
  6018. }
  6019. }
  6020. });
  6021. if (nodes[sourceNodeId].index === nodes[sourceNodeId].low) {
  6022. var componentNodes = eles.spawn();
  6023. for (;;) {
  6024. var nodeId = stack.pop();
  6025. componentNodes.merge(eles.getElementById(nodeId));
  6026. nodes[nodeId].low = nodes[sourceNodeId].index;
  6027. nodes[nodeId].explored = true;
  6028. if (nodeId === sourceNodeId) {
  6029. break;
  6030. }
  6031. }
  6032. var componentEdges = componentNodes.edgesWith(componentNodes);
  6033. var component = componentNodes.merge(componentEdges);
  6034. components.push(component);
  6035. cut = cut.difference(component);
  6036. }
  6037. };
  6038. eles.forEach(function (ele) {
  6039. if (ele.isNode()) {
  6040. var nodeId = ele.id();
  6041. if (!(nodeId in nodes)) {
  6042. _stronglyConnectedSearch(nodeId);
  6043. }
  6044. }
  6045. });
  6046. return {
  6047. cut: cut,
  6048. components: components
  6049. };
  6050. };
  6051. var tarjanStronglyConnected$1 = {
  6052. tarjanStronglyConnected: tarjanStronglyConnected,
  6053. tsc: tarjanStronglyConnected,
  6054. tscc: tarjanStronglyConnected,
  6055. tarjanStronglyConnectedComponents: tarjanStronglyConnected
  6056. };
  6057. var elesfn$j = {};
  6058. [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) {
  6059. extend(elesfn$j, props);
  6060. });
  6061. /*!
  6062. Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
  6063. Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
  6064. Licensed under The MIT License (http://opensource.org/licenses/MIT)
  6065. */
  6066. /* promise states [Promises/A+ 2.1] */
  6067. var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
  6068. var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
  6069. var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
  6070. /* promise object constructor */
  6071. var _api = function api(executor) {
  6072. /* optionally support non-constructor/plain-function call */
  6073. if (!(this instanceof _api)) return new _api(executor);
  6074. /* initialize object */
  6075. this.id = 'Thenable/1.0.7';
  6076. this.state = STATE_PENDING; /* initial state */
  6077. this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */
  6078. this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */
  6079. this.onFulfilled = []; /* initial handlers */
  6080. this.onRejected = []; /* initial handlers */
  6081. /* provide optional information-hiding proxy */
  6082. this.proxy = {
  6083. then: this.then.bind(this)
  6084. };
  6085. /* support optional executor function */
  6086. if (typeof executor === 'function') executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
  6087. };
  6088. /* promise API methods */
  6089. _api.prototype = {
  6090. /* promise resolving methods */
  6091. fulfill: function fulfill(value) {
  6092. return deliver(this, STATE_FULFILLED, 'fulfillValue', value);
  6093. },
  6094. reject: function reject(value) {
  6095. return deliver(this, STATE_REJECTED, 'rejectReason', value);
  6096. },
  6097. /* "The then Method" [Promises/A+ 1.1, 1.2, 2.2] */
  6098. then: function then(onFulfilled, onRejected) {
  6099. var curr = this;
  6100. var next = new _api(); /* [Promises/A+ 2.2.7] */
  6101. curr.onFulfilled.push(resolver(onFulfilled, next, 'fulfill')); /* [Promises/A+ 2.2.2/2.2.6] */
  6102. curr.onRejected.push(resolver(onRejected, next, 'reject')); /* [Promises/A+ 2.2.3/2.2.6] */
  6103. execute(curr);
  6104. return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */
  6105. }
  6106. };
  6107. /* deliver an action */
  6108. var deliver = function deliver(curr, state, name, value) {
  6109. if (curr.state === STATE_PENDING) {
  6110. curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */
  6111. curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */
  6112. execute(curr);
  6113. }
  6114. return curr;
  6115. };
  6116. /* execute all handlers */
  6117. var execute = function execute(curr) {
  6118. if (curr.state === STATE_FULFILLED) execute_handlers(curr, 'onFulfilled', curr.fulfillValue);else if (curr.state === STATE_REJECTED) execute_handlers(curr, 'onRejected', curr.rejectReason);
  6119. };
  6120. /* execute particular set of handlers */
  6121. var execute_handlers = function execute_handlers(curr, name, value) {
  6122. /* global setImmediate: true */
  6123. /* global setTimeout: true */
  6124. /* short-circuit processing */
  6125. if (curr[name].length === 0) return;
  6126. /* iterate over all handlers, exactly once */
  6127. var handlers = curr[name];
  6128. curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */
  6129. var func = function func() {
  6130. for (var i = 0; i < handlers.length; i++) handlers[i](value); /* [Promises/A+ 2.2.5] */
  6131. };
  6132. /* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */
  6133. if (typeof setImmediate === 'function') setImmediate(func);else setTimeout(func, 0);
  6134. };
  6135. /* generate a resolver function */
  6136. var resolver = function resolver(cb, next, method) {
  6137. return function (value) {
  6138. if (typeof cb !== 'function') /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */
  6139. next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */else {
  6140. var result;
  6141. try {
  6142. result = cb(value);
  6143. } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */ catch (e) {
  6144. next.reject(e); /* [Promises/A+ 2.2.7.2] */
  6145. return;
  6146. }
  6147. _resolve(next, result); /* [Promises/A+ 2.2.7.1] */
  6148. }
  6149. };
  6150. };
  6151. /* "Promise Resolution Procedure" */ /* [Promises/A+ 2.3] */
  6152. var _resolve = function resolve(promise, x) {
  6153. /* sanity check arguments */ /* [Promises/A+ 2.3.1] */
  6154. if (promise === x || promise.proxy === x) {
  6155. promise.reject(new TypeError('cannot resolve promise with itself'));
  6156. return;
  6157. }
  6158. /* surgically check for a "then" method
  6159. (mainly to just call the "getter" of "then" only once) */
  6160. var then;
  6161. if (_typeof(x) === 'object' && x !== null || typeof x === 'function') {
  6162. try {
  6163. then = x.then;
  6164. } /* [Promises/A+ 2.3.3.1, 3.5] */ catch (e) {
  6165. promise.reject(e); /* [Promises/A+ 2.3.3.2] */
  6166. return;
  6167. }
  6168. }
  6169. /* handle own Thenables [Promises/A+ 2.3.2]
  6170. and similar "thenables" [Promises/A+ 2.3.3] */
  6171. if (typeof then === 'function') {
  6172. var resolved = false;
  6173. try {
  6174. /* call retrieved "then" method */ /* [Promises/A+ 2.3.3.3] */
  6175. then.call(x, /* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */
  6176. function (y) {
  6177. if (resolved) return;
  6178. resolved = true; /* [Promises/A+ 2.3.3.3.3] */
  6179. if (y === x) /* [Promises/A+ 3.6] */
  6180. promise.reject(new TypeError('circular thenable chain'));else _resolve(promise, y);
  6181. }, /* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */
  6182. function (r) {
  6183. if (resolved) return;
  6184. resolved = true; /* [Promises/A+ 2.3.3.3.3] */
  6185. promise.reject(r);
  6186. });
  6187. } catch (e) {
  6188. if (!resolved) /* [Promises/A+ 2.3.3.3.3] */
  6189. promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */
  6190. }
  6191. return;
  6192. }
  6193. /* handle other values */
  6194. promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */
  6195. };
  6196. // so we always have Promise.all()
  6197. _api.all = function (ps) {
  6198. return new _api(function (resolveAll, rejectAll) {
  6199. var vals = new Array(ps.length);
  6200. var doneCount = 0;
  6201. var fulfill = function fulfill(i, val) {
  6202. vals[i] = val;
  6203. doneCount++;
  6204. if (doneCount === ps.length) {
  6205. resolveAll(vals);
  6206. }
  6207. };
  6208. for (var i = 0; i < ps.length; i++) {
  6209. (function (i) {
  6210. var p = ps[i];
  6211. var isPromise = p != null && p.then != null;
  6212. if (isPromise) {
  6213. p.then(function (val) {
  6214. fulfill(i, val);
  6215. }, function (err) {
  6216. rejectAll(err);
  6217. });
  6218. } else {
  6219. var val = p;
  6220. fulfill(i, val);
  6221. }
  6222. })(i);
  6223. }
  6224. });
  6225. };
  6226. _api.resolve = function (val) {
  6227. return new _api(function (resolve, reject) {
  6228. resolve(val);
  6229. });
  6230. };
  6231. _api.reject = function (val) {
  6232. return new _api(function (resolve, reject) {
  6233. reject(val);
  6234. });
  6235. };
  6236. var Promise$1 = typeof Promise !== 'undefined' ? Promise : _api; // eslint-disable-line no-undef
  6237. var Animation = function Animation(target, opts, opts2) {
  6238. var isCore = core(target);
  6239. var isEle = !isCore;
  6240. var _p = this._private = extend({
  6241. duration: 1000
  6242. }, opts, opts2);
  6243. _p.target = target;
  6244. _p.style = _p.style || _p.css;
  6245. _p.started = false;
  6246. _p.playing = false;
  6247. _p.hooked = false;
  6248. _p.applying = false;
  6249. _p.progress = 0;
  6250. _p.completes = [];
  6251. _p.frames = [];
  6252. if (_p.complete && fn$6(_p.complete)) {
  6253. _p.completes.push(_p.complete);
  6254. }
  6255. if (isEle) {
  6256. var pos = target.position();
  6257. _p.startPosition = _p.startPosition || {
  6258. x: pos.x,
  6259. y: pos.y
  6260. };
  6261. _p.startStyle = _p.startStyle || target.cy().style().getAnimationStartStyle(target, _p.style);
  6262. }
  6263. if (isCore) {
  6264. var pan = target.pan();
  6265. _p.startPan = {
  6266. x: pan.x,
  6267. y: pan.y
  6268. };
  6269. _p.startZoom = target.zoom();
  6270. }
  6271. // for future timeline/animations impl
  6272. this.length = 1;
  6273. this[0] = this;
  6274. };
  6275. var anifn = Animation.prototype;
  6276. extend(anifn, {
  6277. instanceString: function instanceString() {
  6278. return 'animation';
  6279. },
  6280. hook: function hook() {
  6281. var _p = this._private;
  6282. if (!_p.hooked) {
  6283. // add to target's animation queue
  6284. var q;
  6285. var tAni = _p.target._private.animation;
  6286. if (_p.queue) {
  6287. q = tAni.queue;
  6288. } else {
  6289. q = tAni.current;
  6290. }
  6291. q.push(this);
  6292. // add to the animation loop pool
  6293. if (elementOrCollection(_p.target)) {
  6294. _p.target.cy().addToAnimationPool(_p.target);
  6295. }
  6296. _p.hooked = true;
  6297. }
  6298. return this;
  6299. },
  6300. play: function play() {
  6301. var _p = this._private;
  6302. // autorewind
  6303. if (_p.progress === 1) {
  6304. _p.progress = 0;
  6305. }
  6306. _p.playing = true;
  6307. _p.started = false; // needs to be started by animation loop
  6308. _p.stopped = false;
  6309. this.hook();
  6310. // the animation loop will start the animation...
  6311. return this;
  6312. },
  6313. playing: function playing() {
  6314. return this._private.playing;
  6315. },
  6316. apply: function apply() {
  6317. var _p = this._private;
  6318. _p.applying = true;
  6319. _p.started = false; // needs to be started by animation loop
  6320. _p.stopped = false;
  6321. this.hook();
  6322. // the animation loop will apply the animation at this progress
  6323. return this;
  6324. },
  6325. applying: function applying() {
  6326. return this._private.applying;
  6327. },
  6328. pause: function pause() {
  6329. var _p = this._private;
  6330. _p.playing = false;
  6331. _p.started = false;
  6332. return this;
  6333. },
  6334. stop: function stop() {
  6335. var _p = this._private;
  6336. _p.playing = false;
  6337. _p.started = false;
  6338. _p.stopped = true; // to be removed from animation queues
  6339. return this;
  6340. },
  6341. rewind: function rewind() {
  6342. return this.progress(0);
  6343. },
  6344. fastforward: function fastforward() {
  6345. return this.progress(1);
  6346. },
  6347. time: function time(t) {
  6348. var _p = this._private;
  6349. if (t === undefined) {
  6350. return _p.progress * _p.duration;
  6351. } else {
  6352. return this.progress(t / _p.duration);
  6353. }
  6354. },
  6355. progress: function progress(p) {
  6356. var _p = this._private;
  6357. var wasPlaying = _p.playing;
  6358. if (p === undefined) {
  6359. return _p.progress;
  6360. } else {
  6361. if (wasPlaying) {
  6362. this.pause();
  6363. }
  6364. _p.progress = p;
  6365. _p.started = false;
  6366. if (wasPlaying) {
  6367. this.play();
  6368. }
  6369. }
  6370. return this;
  6371. },
  6372. completed: function completed() {
  6373. return this._private.progress === 1;
  6374. },
  6375. reverse: function reverse() {
  6376. var _p = this._private;
  6377. var wasPlaying = _p.playing;
  6378. if (wasPlaying) {
  6379. this.pause();
  6380. }
  6381. _p.progress = 1 - _p.progress;
  6382. _p.started = false;
  6383. var swap = function swap(a, b) {
  6384. var _pa = _p[a];
  6385. if (_pa == null) {
  6386. return;
  6387. }
  6388. _p[a] = _p[b];
  6389. _p[b] = _pa;
  6390. };
  6391. swap('zoom', 'startZoom');
  6392. swap('pan', 'startPan');
  6393. swap('position', 'startPosition');
  6394. // swap styles
  6395. if (_p.style) {
  6396. for (var i = 0; i < _p.style.length; i++) {
  6397. var prop = _p.style[i];
  6398. var name = prop.name;
  6399. var startStyleProp = _p.startStyle[name];
  6400. _p.startStyle[name] = prop;
  6401. _p.style[i] = startStyleProp;
  6402. }
  6403. }
  6404. if (wasPlaying) {
  6405. this.play();
  6406. }
  6407. return this;
  6408. },
  6409. promise: function promise(type) {
  6410. var _p = this._private;
  6411. var arr;
  6412. switch (type) {
  6413. case 'frame':
  6414. arr = _p.frames;
  6415. break;
  6416. default:
  6417. case 'complete':
  6418. case 'completed':
  6419. arr = _p.completes;
  6420. }
  6421. return new Promise$1(function (resolve, reject) {
  6422. arr.push(function () {
  6423. resolve();
  6424. });
  6425. });
  6426. }
  6427. });
  6428. anifn.complete = anifn.completed;
  6429. anifn.run = anifn.play;
  6430. anifn.running = anifn.playing;
  6431. var define$3 = {
  6432. animated: function animated() {
  6433. return function animatedImpl() {
  6434. var self = this;
  6435. var selfIsArrayLike = self.length !== undefined;
  6436. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6437. var cy = this._private.cy || this;
  6438. if (!cy.styleEnabled()) {
  6439. return false;
  6440. }
  6441. var ele = all[0];
  6442. if (ele) {
  6443. return ele._private.animation.current.length > 0;
  6444. }
  6445. };
  6446. },
  6447. // animated
  6448. clearQueue: function clearQueue() {
  6449. return function clearQueueImpl() {
  6450. var self = this;
  6451. var selfIsArrayLike = self.length !== undefined;
  6452. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6453. var cy = this._private.cy || this;
  6454. if (!cy.styleEnabled()) {
  6455. return this;
  6456. }
  6457. for (var i = 0; i < all.length; i++) {
  6458. var ele = all[i];
  6459. ele._private.animation.queue = [];
  6460. }
  6461. return this;
  6462. };
  6463. },
  6464. // clearQueue
  6465. delay: function delay() {
  6466. return function delayImpl(time, complete) {
  6467. var cy = this._private.cy || this;
  6468. if (!cy.styleEnabled()) {
  6469. return this;
  6470. }
  6471. return this.animate({
  6472. delay: time,
  6473. duration: time,
  6474. complete: complete
  6475. });
  6476. };
  6477. },
  6478. // delay
  6479. delayAnimation: function delayAnimation() {
  6480. return function delayAnimationImpl(time, complete) {
  6481. var cy = this._private.cy || this;
  6482. if (!cy.styleEnabled()) {
  6483. return this;
  6484. }
  6485. return this.animation({
  6486. delay: time,
  6487. duration: time,
  6488. complete: complete
  6489. });
  6490. };
  6491. },
  6492. // delay
  6493. animation: function animation() {
  6494. return function animationImpl(properties, params) {
  6495. var self = this;
  6496. var selfIsArrayLike = self.length !== undefined;
  6497. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6498. var cy = this._private.cy || this;
  6499. var isCore = !selfIsArrayLike;
  6500. var isEles = !isCore;
  6501. if (!cy.styleEnabled()) {
  6502. return this;
  6503. }
  6504. var style = cy.style();
  6505. properties = extend({}, properties, params);
  6506. var propertiesEmpty = Object.keys(properties).length === 0;
  6507. if (propertiesEmpty) {
  6508. return new Animation(all[0], properties); // nothing to animate
  6509. }
  6510. if (properties.duration === undefined) {
  6511. properties.duration = 400;
  6512. }
  6513. switch (properties.duration) {
  6514. case 'slow':
  6515. properties.duration = 600;
  6516. break;
  6517. case 'fast':
  6518. properties.duration = 200;
  6519. break;
  6520. }
  6521. if (isEles) {
  6522. properties.style = style.getPropsList(properties.style || properties.css);
  6523. properties.css = undefined;
  6524. }
  6525. if (isEles && properties.renderedPosition != null) {
  6526. var rpos = properties.renderedPosition;
  6527. var pan = cy.pan();
  6528. var zoom = cy.zoom();
  6529. properties.position = renderedToModelPosition(rpos, zoom, pan);
  6530. }
  6531. // override pan w/ panBy if set
  6532. if (isCore && properties.panBy != null) {
  6533. var panBy = properties.panBy;
  6534. var cyPan = cy.pan();
  6535. properties.pan = {
  6536. x: cyPan.x + panBy.x,
  6537. y: cyPan.y + panBy.y
  6538. };
  6539. }
  6540. // override pan w/ center if set
  6541. var center = properties.center || properties.centre;
  6542. if (isCore && center != null) {
  6543. var centerPan = cy.getCenterPan(center.eles, properties.zoom);
  6544. if (centerPan != null) {
  6545. properties.pan = centerPan;
  6546. }
  6547. }
  6548. // override pan & zoom w/ fit if set
  6549. if (isCore && properties.fit != null) {
  6550. var fit = properties.fit;
  6551. var fitVp = cy.getFitViewport(fit.eles || fit.boundingBox, fit.padding);
  6552. if (fitVp != null) {
  6553. properties.pan = fitVp.pan;
  6554. properties.zoom = fitVp.zoom;
  6555. }
  6556. }
  6557. // override zoom (& potentially pan) w/ zoom obj if set
  6558. if (isCore && plainObject(properties.zoom)) {
  6559. var vp = cy.getZoomedViewport(properties.zoom);
  6560. if (vp != null) {
  6561. if (vp.zoomed) {
  6562. properties.zoom = vp.zoom;
  6563. }
  6564. if (vp.panned) {
  6565. properties.pan = vp.pan;
  6566. }
  6567. } else {
  6568. properties.zoom = null; // an inavalid zoom (e.g. no delta) gets automatically destroyed
  6569. }
  6570. }
  6571. return new Animation(all[0], properties);
  6572. };
  6573. },
  6574. // animate
  6575. animate: function animate() {
  6576. return function animateImpl(properties, params) {
  6577. var self = this;
  6578. var selfIsArrayLike = self.length !== undefined;
  6579. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6580. var cy = this._private.cy || this;
  6581. if (!cy.styleEnabled()) {
  6582. return this;
  6583. }
  6584. if (params) {
  6585. properties = extend({}, properties, params);
  6586. }
  6587. // manually hook and run the animation
  6588. for (var i = 0; i < all.length; i++) {
  6589. var ele = all[i];
  6590. var queue = ele.animated() && (properties.queue === undefined || properties.queue);
  6591. var ani = ele.animation(properties, queue ? {
  6592. queue: true
  6593. } : undefined);
  6594. ani.play();
  6595. }
  6596. return this; // chaining
  6597. };
  6598. },
  6599. // animate
  6600. stop: function stop() {
  6601. return function stopImpl(clearQueue, jumpToEnd) {
  6602. var self = this;
  6603. var selfIsArrayLike = self.length !== undefined;
  6604. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  6605. var cy = this._private.cy || this;
  6606. if (!cy.styleEnabled()) {
  6607. return this;
  6608. }
  6609. for (var i = 0; i < all.length; i++) {
  6610. var ele = all[i];
  6611. var _p = ele._private;
  6612. var anis = _p.animation.current;
  6613. for (var j = 0; j < anis.length; j++) {
  6614. var ani = anis[j];
  6615. var ani_p = ani._private;
  6616. if (jumpToEnd) {
  6617. // next iteration of the animation loop, the animation
  6618. // will go straight to the end and be removed
  6619. ani_p.duration = 0;
  6620. }
  6621. }
  6622. // clear the queue of future animations
  6623. if (clearQueue) {
  6624. _p.animation.queue = [];
  6625. }
  6626. if (!jumpToEnd) {
  6627. _p.animation.current = [];
  6628. }
  6629. }
  6630. // we have to notify (the animation loop doesn't do it for us on `stop`)
  6631. cy.notify('draw');
  6632. return this;
  6633. };
  6634. } // stop
  6635. }; // define
  6636. /**
  6637. * Checks if `value` is classified as an `Array` object.
  6638. *
  6639. * @static
  6640. * @memberOf _
  6641. * @since 0.1.0
  6642. * @category Lang
  6643. * @param {*} value The value to check.
  6644. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  6645. * @example
  6646. *
  6647. * _.isArray([1, 2, 3]);
  6648. * // => true
  6649. *
  6650. * _.isArray(document.body.children);
  6651. * // => false
  6652. *
  6653. * _.isArray('abc');
  6654. * // => false
  6655. *
  6656. * _.isArray(_.noop);
  6657. * // => false
  6658. */
  6659. var isArray_1;
  6660. var hasRequiredIsArray;
  6661. function requireIsArray () {
  6662. if (hasRequiredIsArray) return isArray_1;
  6663. hasRequiredIsArray = 1;
  6664. var isArray = Array.isArray;
  6665. isArray_1 = isArray;
  6666. return isArray_1;
  6667. }
  6668. var _isKey;
  6669. var hasRequired_isKey;
  6670. function require_isKey () {
  6671. if (hasRequired_isKey) return _isKey;
  6672. hasRequired_isKey = 1;
  6673. var isArray = requireIsArray(),
  6674. isSymbol = requireIsSymbol();
  6675. /** Used to match property names within property paths. */
  6676. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  6677. reIsPlainProp = /^\w*$/;
  6678. /**
  6679. * Checks if `value` is a property name and not a property path.
  6680. *
  6681. * @private
  6682. * @param {*} value The value to check.
  6683. * @param {Object} [object] The object to query keys on.
  6684. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  6685. */
  6686. function isKey(value, object) {
  6687. if (isArray(value)) {
  6688. return false;
  6689. }
  6690. var type = typeof value;
  6691. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  6692. value == null || isSymbol(value)) {
  6693. return true;
  6694. }
  6695. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  6696. (object != null && value in Object(object));
  6697. }
  6698. _isKey = isKey;
  6699. return _isKey;
  6700. }
  6701. var isFunction_1;
  6702. var hasRequiredIsFunction;
  6703. function requireIsFunction () {
  6704. if (hasRequiredIsFunction) return isFunction_1;
  6705. hasRequiredIsFunction = 1;
  6706. var baseGetTag = require_baseGetTag(),
  6707. isObject = requireIsObject();
  6708. /** `Object#toString` result references. */
  6709. var asyncTag = '[object AsyncFunction]',
  6710. funcTag = '[object Function]',
  6711. genTag = '[object GeneratorFunction]',
  6712. proxyTag = '[object Proxy]';
  6713. /**
  6714. * Checks if `value` is classified as a `Function` object.
  6715. *
  6716. * @static
  6717. * @memberOf _
  6718. * @since 0.1.0
  6719. * @category Lang
  6720. * @param {*} value The value to check.
  6721. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  6722. * @example
  6723. *
  6724. * _.isFunction(_);
  6725. * // => true
  6726. *
  6727. * _.isFunction(/abc/);
  6728. * // => false
  6729. */
  6730. function isFunction(value) {
  6731. if (!isObject(value)) {
  6732. return false;
  6733. }
  6734. // The use of `Object#toString` avoids issues with the `typeof` operator
  6735. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  6736. var tag = baseGetTag(value);
  6737. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  6738. }
  6739. isFunction_1 = isFunction;
  6740. return isFunction_1;
  6741. }
  6742. var _coreJsData;
  6743. var hasRequired_coreJsData;
  6744. function require_coreJsData () {
  6745. if (hasRequired_coreJsData) return _coreJsData;
  6746. hasRequired_coreJsData = 1;
  6747. var root = require_root();
  6748. /** Used to detect overreaching core-js shims. */
  6749. var coreJsData = root['__core-js_shared__'];
  6750. _coreJsData = coreJsData;
  6751. return _coreJsData;
  6752. }
  6753. var _isMasked;
  6754. var hasRequired_isMasked;
  6755. function require_isMasked () {
  6756. if (hasRequired_isMasked) return _isMasked;
  6757. hasRequired_isMasked = 1;
  6758. var coreJsData = require_coreJsData();
  6759. /** Used to detect methods masquerading as native. */
  6760. var maskSrcKey = (function() {
  6761. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  6762. return uid ? ('Symbol(src)_1.' + uid) : '';
  6763. }());
  6764. /**
  6765. * Checks if `func` has its source masked.
  6766. *
  6767. * @private
  6768. * @param {Function} func The function to check.
  6769. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  6770. */
  6771. function isMasked(func) {
  6772. return !!maskSrcKey && (maskSrcKey in func);
  6773. }
  6774. _isMasked = isMasked;
  6775. return _isMasked;
  6776. }
  6777. /** Used for built-in method references. */
  6778. var _toSource;
  6779. var hasRequired_toSource;
  6780. function require_toSource () {
  6781. if (hasRequired_toSource) return _toSource;
  6782. hasRequired_toSource = 1;
  6783. var funcProto = Function.prototype;
  6784. /** Used to resolve the decompiled source of functions. */
  6785. var funcToString = funcProto.toString;
  6786. /**
  6787. * Converts `func` to its source code.
  6788. *
  6789. * @private
  6790. * @param {Function} func The function to convert.
  6791. * @returns {string} Returns the source code.
  6792. */
  6793. function toSource(func) {
  6794. if (func != null) {
  6795. try {
  6796. return funcToString.call(func);
  6797. } catch (e) {}
  6798. try {
  6799. return (func + '');
  6800. } catch (e) {}
  6801. }
  6802. return '';
  6803. }
  6804. _toSource = toSource;
  6805. return _toSource;
  6806. }
  6807. var _baseIsNative;
  6808. var hasRequired_baseIsNative;
  6809. function require_baseIsNative () {
  6810. if (hasRequired_baseIsNative) return _baseIsNative;
  6811. hasRequired_baseIsNative = 1;
  6812. var isFunction = requireIsFunction(),
  6813. isMasked = require_isMasked(),
  6814. isObject = requireIsObject(),
  6815. toSource = require_toSource();
  6816. /**
  6817. * Used to match `RegExp`
  6818. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  6819. */
  6820. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  6821. /** Used to detect host constructors (Safari). */
  6822. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  6823. /** Used for built-in method references. */
  6824. var funcProto = Function.prototype,
  6825. objectProto = Object.prototype;
  6826. /** Used to resolve the decompiled source of functions. */
  6827. var funcToString = funcProto.toString;
  6828. /** Used to check objects for own properties. */
  6829. var hasOwnProperty = objectProto.hasOwnProperty;
  6830. /** Used to detect if a method is native. */
  6831. var reIsNative = RegExp('^' +
  6832. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  6833. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  6834. );
  6835. /**
  6836. * The base implementation of `_.isNative` without bad shim checks.
  6837. *
  6838. * @private
  6839. * @param {*} value The value to check.
  6840. * @returns {boolean} Returns `true` if `value` is a native function,
  6841. * else `false`.
  6842. */
  6843. function baseIsNative(value) {
  6844. if (!isObject(value) || isMasked(value)) {
  6845. return false;
  6846. }
  6847. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  6848. return pattern.test(toSource(value));
  6849. }
  6850. _baseIsNative = baseIsNative;
  6851. return _baseIsNative;
  6852. }
  6853. /**
  6854. * Gets the value at `key` of `object`.
  6855. *
  6856. * @private
  6857. * @param {Object} [object] The object to query.
  6858. * @param {string} key The key of the property to get.
  6859. * @returns {*} Returns the property value.
  6860. */
  6861. var _getValue;
  6862. var hasRequired_getValue;
  6863. function require_getValue () {
  6864. if (hasRequired_getValue) return _getValue;
  6865. hasRequired_getValue = 1;
  6866. function getValue(object, key) {
  6867. return object == null ? undefined : object[key];
  6868. }
  6869. _getValue = getValue;
  6870. return _getValue;
  6871. }
  6872. var _getNative;
  6873. var hasRequired_getNative;
  6874. function require_getNative () {
  6875. if (hasRequired_getNative) return _getNative;
  6876. hasRequired_getNative = 1;
  6877. var baseIsNative = require_baseIsNative(),
  6878. getValue = require_getValue();
  6879. /**
  6880. * Gets the native function at `key` of `object`.
  6881. *
  6882. * @private
  6883. * @param {Object} object The object to query.
  6884. * @param {string} key The key of the method to get.
  6885. * @returns {*} Returns the function if it's native, else `undefined`.
  6886. */
  6887. function getNative(object, key) {
  6888. var value = getValue(object, key);
  6889. return baseIsNative(value) ? value : undefined;
  6890. }
  6891. _getNative = getNative;
  6892. return _getNative;
  6893. }
  6894. var _nativeCreate;
  6895. var hasRequired_nativeCreate;
  6896. function require_nativeCreate () {
  6897. if (hasRequired_nativeCreate) return _nativeCreate;
  6898. hasRequired_nativeCreate = 1;
  6899. var getNative = require_getNative();
  6900. /* Built-in method references that are verified to be native. */
  6901. var nativeCreate = getNative(Object, 'create');
  6902. _nativeCreate = nativeCreate;
  6903. return _nativeCreate;
  6904. }
  6905. var _hashClear;
  6906. var hasRequired_hashClear;
  6907. function require_hashClear () {
  6908. if (hasRequired_hashClear) return _hashClear;
  6909. hasRequired_hashClear = 1;
  6910. var nativeCreate = require_nativeCreate();
  6911. /**
  6912. * Removes all key-value entries from the hash.
  6913. *
  6914. * @private
  6915. * @name clear
  6916. * @memberOf Hash
  6917. */
  6918. function hashClear() {
  6919. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  6920. this.size = 0;
  6921. }
  6922. _hashClear = hashClear;
  6923. return _hashClear;
  6924. }
  6925. /**
  6926. * Removes `key` and its value from the hash.
  6927. *
  6928. * @private
  6929. * @name delete
  6930. * @memberOf Hash
  6931. * @param {Object} hash The hash to modify.
  6932. * @param {string} key The key of the value to remove.
  6933. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  6934. */
  6935. var _hashDelete;
  6936. var hasRequired_hashDelete;
  6937. function require_hashDelete () {
  6938. if (hasRequired_hashDelete) return _hashDelete;
  6939. hasRequired_hashDelete = 1;
  6940. function hashDelete(key) {
  6941. var result = this.has(key) && delete this.__data__[key];
  6942. this.size -= result ? 1 : 0;
  6943. return result;
  6944. }
  6945. _hashDelete = hashDelete;
  6946. return _hashDelete;
  6947. }
  6948. var _hashGet;
  6949. var hasRequired_hashGet;
  6950. function require_hashGet () {
  6951. if (hasRequired_hashGet) return _hashGet;
  6952. hasRequired_hashGet = 1;
  6953. var nativeCreate = require_nativeCreate();
  6954. /** Used to stand-in for `undefined` hash values. */
  6955. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  6956. /** Used for built-in method references. */
  6957. var objectProto = Object.prototype;
  6958. /** Used to check objects for own properties. */
  6959. var hasOwnProperty = objectProto.hasOwnProperty;
  6960. /**
  6961. * Gets the hash value for `key`.
  6962. *
  6963. * @private
  6964. * @name get
  6965. * @memberOf Hash
  6966. * @param {string} key The key of the value to get.
  6967. * @returns {*} Returns the entry value.
  6968. */
  6969. function hashGet(key) {
  6970. var data = this.__data__;
  6971. if (nativeCreate) {
  6972. var result = data[key];
  6973. return result === HASH_UNDEFINED ? undefined : result;
  6974. }
  6975. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  6976. }
  6977. _hashGet = hashGet;
  6978. return _hashGet;
  6979. }
  6980. var _hashHas;
  6981. var hasRequired_hashHas;
  6982. function require_hashHas () {
  6983. if (hasRequired_hashHas) return _hashHas;
  6984. hasRequired_hashHas = 1;
  6985. var nativeCreate = require_nativeCreate();
  6986. /** Used for built-in method references. */
  6987. var objectProto = Object.prototype;
  6988. /** Used to check objects for own properties. */
  6989. var hasOwnProperty = objectProto.hasOwnProperty;
  6990. /**
  6991. * Checks if a hash value for `key` exists.
  6992. *
  6993. * @private
  6994. * @name has
  6995. * @memberOf Hash
  6996. * @param {string} key The key of the entry to check.
  6997. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  6998. */
  6999. function hashHas(key) {
  7000. var data = this.__data__;
  7001. return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
  7002. }
  7003. _hashHas = hashHas;
  7004. return _hashHas;
  7005. }
  7006. var _hashSet;
  7007. var hasRequired_hashSet;
  7008. function require_hashSet () {
  7009. if (hasRequired_hashSet) return _hashSet;
  7010. hasRequired_hashSet = 1;
  7011. var nativeCreate = require_nativeCreate();
  7012. /** Used to stand-in for `undefined` hash values. */
  7013. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  7014. /**
  7015. * Sets the hash `key` to `value`.
  7016. *
  7017. * @private
  7018. * @name set
  7019. * @memberOf Hash
  7020. * @param {string} key The key of the value to set.
  7021. * @param {*} value The value to set.
  7022. * @returns {Object} Returns the hash instance.
  7023. */
  7024. function hashSet(key, value) {
  7025. var data = this.__data__;
  7026. this.size += this.has(key) ? 0 : 1;
  7027. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  7028. return this;
  7029. }
  7030. _hashSet = hashSet;
  7031. return _hashSet;
  7032. }
  7033. var _Hash;
  7034. var hasRequired_Hash;
  7035. function require_Hash () {
  7036. if (hasRequired_Hash) return _Hash;
  7037. hasRequired_Hash = 1;
  7038. var hashClear = require_hashClear(),
  7039. hashDelete = require_hashDelete(),
  7040. hashGet = require_hashGet(),
  7041. hashHas = require_hashHas(),
  7042. hashSet = require_hashSet();
  7043. /**
  7044. * Creates a hash object.
  7045. *
  7046. * @private
  7047. * @constructor
  7048. * @param {Array} [entries] The key-value pairs to cache.
  7049. */
  7050. function Hash(entries) {
  7051. var index = -1,
  7052. length = entries == null ? 0 : entries.length;
  7053. this.clear();
  7054. while (++index < length) {
  7055. var entry = entries[index];
  7056. this.set(entry[0], entry[1]);
  7057. }
  7058. }
  7059. // Add methods to `Hash`.
  7060. Hash.prototype.clear = hashClear;
  7061. Hash.prototype['delete'] = hashDelete;
  7062. Hash.prototype.get = hashGet;
  7063. Hash.prototype.has = hashHas;
  7064. Hash.prototype.set = hashSet;
  7065. _Hash = Hash;
  7066. return _Hash;
  7067. }
  7068. /**
  7069. * Removes all key-value entries from the list cache.
  7070. *
  7071. * @private
  7072. * @name clear
  7073. * @memberOf ListCache
  7074. */
  7075. var _listCacheClear;
  7076. var hasRequired_listCacheClear;
  7077. function require_listCacheClear () {
  7078. if (hasRequired_listCacheClear) return _listCacheClear;
  7079. hasRequired_listCacheClear = 1;
  7080. function listCacheClear() {
  7081. this.__data__ = [];
  7082. this.size = 0;
  7083. }
  7084. _listCacheClear = listCacheClear;
  7085. return _listCacheClear;
  7086. }
  7087. /**
  7088. * Performs a
  7089. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7090. * comparison between two values to determine if they are equivalent.
  7091. *
  7092. * @static
  7093. * @memberOf _
  7094. * @since 4.0.0
  7095. * @category Lang
  7096. * @param {*} value The value to compare.
  7097. * @param {*} other The other value to compare.
  7098. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  7099. * @example
  7100. *
  7101. * var object = { 'a': 1 };
  7102. * var other = { 'a': 1 };
  7103. *
  7104. * _.eq(object, object);
  7105. * // => true
  7106. *
  7107. * _.eq(object, other);
  7108. * // => false
  7109. *
  7110. * _.eq('a', 'a');
  7111. * // => true
  7112. *
  7113. * _.eq('a', Object('a'));
  7114. * // => false
  7115. *
  7116. * _.eq(NaN, NaN);
  7117. * // => true
  7118. */
  7119. var eq_1;
  7120. var hasRequiredEq;
  7121. function requireEq () {
  7122. if (hasRequiredEq) return eq_1;
  7123. hasRequiredEq = 1;
  7124. function eq(value, other) {
  7125. return value === other || (value !== value && other !== other);
  7126. }
  7127. eq_1 = eq;
  7128. return eq_1;
  7129. }
  7130. var _assocIndexOf;
  7131. var hasRequired_assocIndexOf;
  7132. function require_assocIndexOf () {
  7133. if (hasRequired_assocIndexOf) return _assocIndexOf;
  7134. hasRequired_assocIndexOf = 1;
  7135. var eq = requireEq();
  7136. /**
  7137. * Gets the index at which the `key` is found in `array` of key-value pairs.
  7138. *
  7139. * @private
  7140. * @param {Array} array The array to inspect.
  7141. * @param {*} key The key to search for.
  7142. * @returns {number} Returns the index of the matched value, else `-1`.
  7143. */
  7144. function assocIndexOf(array, key) {
  7145. var length = array.length;
  7146. while (length--) {
  7147. if (eq(array[length][0], key)) {
  7148. return length;
  7149. }
  7150. }
  7151. return -1;
  7152. }
  7153. _assocIndexOf = assocIndexOf;
  7154. return _assocIndexOf;
  7155. }
  7156. var _listCacheDelete;
  7157. var hasRequired_listCacheDelete;
  7158. function require_listCacheDelete () {
  7159. if (hasRequired_listCacheDelete) return _listCacheDelete;
  7160. hasRequired_listCacheDelete = 1;
  7161. var assocIndexOf = require_assocIndexOf();
  7162. /** Used for built-in method references. */
  7163. var arrayProto = Array.prototype;
  7164. /** Built-in value references. */
  7165. var splice = arrayProto.splice;
  7166. /**
  7167. * Removes `key` and its value from the list cache.
  7168. *
  7169. * @private
  7170. * @name delete
  7171. * @memberOf ListCache
  7172. * @param {string} key The key of the value to remove.
  7173. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7174. */
  7175. function listCacheDelete(key) {
  7176. var data = this.__data__,
  7177. index = assocIndexOf(data, key);
  7178. if (index < 0) {
  7179. return false;
  7180. }
  7181. var lastIndex = data.length - 1;
  7182. if (index == lastIndex) {
  7183. data.pop();
  7184. } else {
  7185. splice.call(data, index, 1);
  7186. }
  7187. --this.size;
  7188. return true;
  7189. }
  7190. _listCacheDelete = listCacheDelete;
  7191. return _listCacheDelete;
  7192. }
  7193. var _listCacheGet;
  7194. var hasRequired_listCacheGet;
  7195. function require_listCacheGet () {
  7196. if (hasRequired_listCacheGet) return _listCacheGet;
  7197. hasRequired_listCacheGet = 1;
  7198. var assocIndexOf = require_assocIndexOf();
  7199. /**
  7200. * Gets the list cache value for `key`.
  7201. *
  7202. * @private
  7203. * @name get
  7204. * @memberOf ListCache
  7205. * @param {string} key The key of the value to get.
  7206. * @returns {*} Returns the entry value.
  7207. */
  7208. function listCacheGet(key) {
  7209. var data = this.__data__,
  7210. index = assocIndexOf(data, key);
  7211. return index < 0 ? undefined : data[index][1];
  7212. }
  7213. _listCacheGet = listCacheGet;
  7214. return _listCacheGet;
  7215. }
  7216. var _listCacheHas;
  7217. var hasRequired_listCacheHas;
  7218. function require_listCacheHas () {
  7219. if (hasRequired_listCacheHas) return _listCacheHas;
  7220. hasRequired_listCacheHas = 1;
  7221. var assocIndexOf = require_assocIndexOf();
  7222. /**
  7223. * Checks if a list cache value for `key` exists.
  7224. *
  7225. * @private
  7226. * @name has
  7227. * @memberOf ListCache
  7228. * @param {string} key The key of the entry to check.
  7229. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7230. */
  7231. function listCacheHas(key) {
  7232. return assocIndexOf(this.__data__, key) > -1;
  7233. }
  7234. _listCacheHas = listCacheHas;
  7235. return _listCacheHas;
  7236. }
  7237. var _listCacheSet;
  7238. var hasRequired_listCacheSet;
  7239. function require_listCacheSet () {
  7240. if (hasRequired_listCacheSet) return _listCacheSet;
  7241. hasRequired_listCacheSet = 1;
  7242. var assocIndexOf = require_assocIndexOf();
  7243. /**
  7244. * Sets the list cache `key` to `value`.
  7245. *
  7246. * @private
  7247. * @name set
  7248. * @memberOf ListCache
  7249. * @param {string} key The key of the value to set.
  7250. * @param {*} value The value to set.
  7251. * @returns {Object} Returns the list cache instance.
  7252. */
  7253. function listCacheSet(key, value) {
  7254. var data = this.__data__,
  7255. index = assocIndexOf(data, key);
  7256. if (index < 0) {
  7257. ++this.size;
  7258. data.push([key, value]);
  7259. } else {
  7260. data[index][1] = value;
  7261. }
  7262. return this;
  7263. }
  7264. _listCacheSet = listCacheSet;
  7265. return _listCacheSet;
  7266. }
  7267. var _ListCache;
  7268. var hasRequired_ListCache;
  7269. function require_ListCache () {
  7270. if (hasRequired_ListCache) return _ListCache;
  7271. hasRequired_ListCache = 1;
  7272. var listCacheClear = require_listCacheClear(),
  7273. listCacheDelete = require_listCacheDelete(),
  7274. listCacheGet = require_listCacheGet(),
  7275. listCacheHas = require_listCacheHas(),
  7276. listCacheSet = require_listCacheSet();
  7277. /**
  7278. * Creates an list cache object.
  7279. *
  7280. * @private
  7281. * @constructor
  7282. * @param {Array} [entries] The key-value pairs to cache.
  7283. */
  7284. function ListCache(entries) {
  7285. var index = -1,
  7286. length = entries == null ? 0 : entries.length;
  7287. this.clear();
  7288. while (++index < length) {
  7289. var entry = entries[index];
  7290. this.set(entry[0], entry[1]);
  7291. }
  7292. }
  7293. // Add methods to `ListCache`.
  7294. ListCache.prototype.clear = listCacheClear;
  7295. ListCache.prototype['delete'] = listCacheDelete;
  7296. ListCache.prototype.get = listCacheGet;
  7297. ListCache.prototype.has = listCacheHas;
  7298. ListCache.prototype.set = listCacheSet;
  7299. _ListCache = ListCache;
  7300. return _ListCache;
  7301. }
  7302. var _Map;
  7303. var hasRequired_Map;
  7304. function require_Map () {
  7305. if (hasRequired_Map) return _Map;
  7306. hasRequired_Map = 1;
  7307. var getNative = require_getNative(),
  7308. root = require_root();
  7309. /* Built-in method references that are verified to be native. */
  7310. var Map = getNative(root, 'Map');
  7311. _Map = Map;
  7312. return _Map;
  7313. }
  7314. var _mapCacheClear;
  7315. var hasRequired_mapCacheClear;
  7316. function require_mapCacheClear () {
  7317. if (hasRequired_mapCacheClear) return _mapCacheClear;
  7318. hasRequired_mapCacheClear = 1;
  7319. var Hash = require_Hash(),
  7320. ListCache = require_ListCache(),
  7321. Map = require_Map();
  7322. /**
  7323. * Removes all key-value entries from the map.
  7324. *
  7325. * @private
  7326. * @name clear
  7327. * @memberOf MapCache
  7328. */
  7329. function mapCacheClear() {
  7330. this.size = 0;
  7331. this.__data__ = {
  7332. 'hash': new Hash,
  7333. 'map': new (Map || ListCache),
  7334. 'string': new Hash
  7335. };
  7336. }
  7337. _mapCacheClear = mapCacheClear;
  7338. return _mapCacheClear;
  7339. }
  7340. /**
  7341. * Checks if `value` is suitable for use as unique object key.
  7342. *
  7343. * @private
  7344. * @param {*} value The value to check.
  7345. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  7346. */
  7347. var _isKeyable;
  7348. var hasRequired_isKeyable;
  7349. function require_isKeyable () {
  7350. if (hasRequired_isKeyable) return _isKeyable;
  7351. hasRequired_isKeyable = 1;
  7352. function isKeyable(value) {
  7353. var type = typeof value;
  7354. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  7355. ? (value !== '__proto__')
  7356. : (value === null);
  7357. }
  7358. _isKeyable = isKeyable;
  7359. return _isKeyable;
  7360. }
  7361. var _getMapData;
  7362. var hasRequired_getMapData;
  7363. function require_getMapData () {
  7364. if (hasRequired_getMapData) return _getMapData;
  7365. hasRequired_getMapData = 1;
  7366. var isKeyable = require_isKeyable();
  7367. /**
  7368. * Gets the data for `map`.
  7369. *
  7370. * @private
  7371. * @param {Object} map The map to query.
  7372. * @param {string} key The reference key.
  7373. * @returns {*} Returns the map data.
  7374. */
  7375. function getMapData(map, key) {
  7376. var data = map.__data__;
  7377. return isKeyable(key)
  7378. ? data[typeof key == 'string' ? 'string' : 'hash']
  7379. : data.map;
  7380. }
  7381. _getMapData = getMapData;
  7382. return _getMapData;
  7383. }
  7384. var _mapCacheDelete;
  7385. var hasRequired_mapCacheDelete;
  7386. function require_mapCacheDelete () {
  7387. if (hasRequired_mapCacheDelete) return _mapCacheDelete;
  7388. hasRequired_mapCacheDelete = 1;
  7389. var getMapData = require_getMapData();
  7390. /**
  7391. * Removes `key` and its value from the map.
  7392. *
  7393. * @private
  7394. * @name delete
  7395. * @memberOf MapCache
  7396. * @param {string} key The key of the value to remove.
  7397. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7398. */
  7399. function mapCacheDelete(key) {
  7400. var result = getMapData(this, key)['delete'](key);
  7401. this.size -= result ? 1 : 0;
  7402. return result;
  7403. }
  7404. _mapCacheDelete = mapCacheDelete;
  7405. return _mapCacheDelete;
  7406. }
  7407. var _mapCacheGet;
  7408. var hasRequired_mapCacheGet;
  7409. function require_mapCacheGet () {
  7410. if (hasRequired_mapCacheGet) return _mapCacheGet;
  7411. hasRequired_mapCacheGet = 1;
  7412. var getMapData = require_getMapData();
  7413. /**
  7414. * Gets the map value for `key`.
  7415. *
  7416. * @private
  7417. * @name get
  7418. * @memberOf MapCache
  7419. * @param {string} key The key of the value to get.
  7420. * @returns {*} Returns the entry value.
  7421. */
  7422. function mapCacheGet(key) {
  7423. return getMapData(this, key).get(key);
  7424. }
  7425. _mapCacheGet = mapCacheGet;
  7426. return _mapCacheGet;
  7427. }
  7428. var _mapCacheHas;
  7429. var hasRequired_mapCacheHas;
  7430. function require_mapCacheHas () {
  7431. if (hasRequired_mapCacheHas) return _mapCacheHas;
  7432. hasRequired_mapCacheHas = 1;
  7433. var getMapData = require_getMapData();
  7434. /**
  7435. * Checks if a map value for `key` exists.
  7436. *
  7437. * @private
  7438. * @name has
  7439. * @memberOf MapCache
  7440. * @param {string} key The key of the entry to check.
  7441. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7442. */
  7443. function mapCacheHas(key) {
  7444. return getMapData(this, key).has(key);
  7445. }
  7446. _mapCacheHas = mapCacheHas;
  7447. return _mapCacheHas;
  7448. }
  7449. var _mapCacheSet;
  7450. var hasRequired_mapCacheSet;
  7451. function require_mapCacheSet () {
  7452. if (hasRequired_mapCacheSet) return _mapCacheSet;
  7453. hasRequired_mapCacheSet = 1;
  7454. var getMapData = require_getMapData();
  7455. /**
  7456. * Sets the map `key` to `value`.
  7457. *
  7458. * @private
  7459. * @name set
  7460. * @memberOf MapCache
  7461. * @param {string} key The key of the value to set.
  7462. * @param {*} value The value to set.
  7463. * @returns {Object} Returns the map cache instance.
  7464. */
  7465. function mapCacheSet(key, value) {
  7466. var data = getMapData(this, key),
  7467. size = data.size;
  7468. data.set(key, value);
  7469. this.size += data.size == size ? 0 : 1;
  7470. return this;
  7471. }
  7472. _mapCacheSet = mapCacheSet;
  7473. return _mapCacheSet;
  7474. }
  7475. var _MapCache;
  7476. var hasRequired_MapCache;
  7477. function require_MapCache () {
  7478. if (hasRequired_MapCache) return _MapCache;
  7479. hasRequired_MapCache = 1;
  7480. var mapCacheClear = require_mapCacheClear(),
  7481. mapCacheDelete = require_mapCacheDelete(),
  7482. mapCacheGet = require_mapCacheGet(),
  7483. mapCacheHas = require_mapCacheHas(),
  7484. mapCacheSet = require_mapCacheSet();
  7485. /**
  7486. * Creates a map cache object to store key-value pairs.
  7487. *
  7488. * @private
  7489. * @constructor
  7490. * @param {Array} [entries] The key-value pairs to cache.
  7491. */
  7492. function MapCache(entries) {
  7493. var index = -1,
  7494. length = entries == null ? 0 : entries.length;
  7495. this.clear();
  7496. while (++index < length) {
  7497. var entry = entries[index];
  7498. this.set(entry[0], entry[1]);
  7499. }
  7500. }
  7501. // Add methods to `MapCache`.
  7502. MapCache.prototype.clear = mapCacheClear;
  7503. MapCache.prototype['delete'] = mapCacheDelete;
  7504. MapCache.prototype.get = mapCacheGet;
  7505. MapCache.prototype.has = mapCacheHas;
  7506. MapCache.prototype.set = mapCacheSet;
  7507. _MapCache = MapCache;
  7508. return _MapCache;
  7509. }
  7510. var memoize_1;
  7511. var hasRequiredMemoize;
  7512. function requireMemoize () {
  7513. if (hasRequiredMemoize) return memoize_1;
  7514. hasRequiredMemoize = 1;
  7515. var MapCache = require_MapCache();
  7516. /** Error message constants. */
  7517. var FUNC_ERROR_TEXT = 'Expected a function';
  7518. /**
  7519. * Creates a function that memoizes the result of `func`. If `resolver` is
  7520. * provided, it determines the cache key for storing the result based on the
  7521. * arguments provided to the memoized function. By default, the first argument
  7522. * provided to the memoized function is used as the map cache key. The `func`
  7523. * is invoked with the `this` binding of the memoized function.
  7524. *
  7525. * **Note:** The cache is exposed as the `cache` property on the memoized
  7526. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  7527. * constructor with one whose instances implement the
  7528. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  7529. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  7530. *
  7531. * @static
  7532. * @memberOf _
  7533. * @since 0.1.0
  7534. * @category Function
  7535. * @param {Function} func The function to have its output memoized.
  7536. * @param {Function} [resolver] The function to resolve the cache key.
  7537. * @returns {Function} Returns the new memoized function.
  7538. * @example
  7539. *
  7540. * var object = { 'a': 1, 'b': 2 };
  7541. * var other = { 'c': 3, 'd': 4 };
  7542. *
  7543. * var values = _.memoize(_.values);
  7544. * values(object);
  7545. * // => [1, 2]
  7546. *
  7547. * values(other);
  7548. * // => [3, 4]
  7549. *
  7550. * object.a = 2;
  7551. * values(object);
  7552. * // => [1, 2]
  7553. *
  7554. * // Modify the result cache.
  7555. * values.cache.set(object, ['a', 'b']);
  7556. * values(object);
  7557. * // => ['a', 'b']
  7558. *
  7559. * // Replace `_.memoize.Cache`.
  7560. * _.memoize.Cache = WeakMap;
  7561. */
  7562. function memoize(func, resolver) {
  7563. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  7564. throw new TypeError(FUNC_ERROR_TEXT);
  7565. }
  7566. var memoized = function() {
  7567. var args = arguments,
  7568. key = resolver ? resolver.apply(this, args) : args[0],
  7569. cache = memoized.cache;
  7570. if (cache.has(key)) {
  7571. return cache.get(key);
  7572. }
  7573. var result = func.apply(this, args);
  7574. memoized.cache = cache.set(key, result) || cache;
  7575. return result;
  7576. };
  7577. memoized.cache = new (memoize.Cache || MapCache);
  7578. return memoized;
  7579. }
  7580. // Expose `MapCache`.
  7581. memoize.Cache = MapCache;
  7582. memoize_1 = memoize;
  7583. return memoize_1;
  7584. }
  7585. var _memoizeCapped;
  7586. var hasRequired_memoizeCapped;
  7587. function require_memoizeCapped () {
  7588. if (hasRequired_memoizeCapped) return _memoizeCapped;
  7589. hasRequired_memoizeCapped = 1;
  7590. var memoize = requireMemoize();
  7591. /** Used as the maximum memoize cache size. */
  7592. var MAX_MEMOIZE_SIZE = 500;
  7593. /**
  7594. * A specialized version of `_.memoize` which clears the memoized function's
  7595. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  7596. *
  7597. * @private
  7598. * @param {Function} func The function to have its output memoized.
  7599. * @returns {Function} Returns the new memoized function.
  7600. */
  7601. function memoizeCapped(func) {
  7602. var result = memoize(func, function(key) {
  7603. if (cache.size === MAX_MEMOIZE_SIZE) {
  7604. cache.clear();
  7605. }
  7606. return key;
  7607. });
  7608. var cache = result.cache;
  7609. return result;
  7610. }
  7611. _memoizeCapped = memoizeCapped;
  7612. return _memoizeCapped;
  7613. }
  7614. var _stringToPath;
  7615. var hasRequired_stringToPath;
  7616. function require_stringToPath () {
  7617. if (hasRequired_stringToPath) return _stringToPath;
  7618. hasRequired_stringToPath = 1;
  7619. var memoizeCapped = require_memoizeCapped();
  7620. /** Used to match property names within property paths. */
  7621. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  7622. /** Used to match backslashes in property paths. */
  7623. var reEscapeChar = /\\(\\)?/g;
  7624. /**
  7625. * Converts `string` to a property path array.
  7626. *
  7627. * @private
  7628. * @param {string} string The string to convert.
  7629. * @returns {Array} Returns the property path array.
  7630. */
  7631. var stringToPath = memoizeCapped(function(string) {
  7632. var result = [];
  7633. if (string.charCodeAt(0) === 46 /* . */) {
  7634. result.push('');
  7635. }
  7636. string.replace(rePropName, function(match, number, quote, subString) {
  7637. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  7638. });
  7639. return result;
  7640. });
  7641. _stringToPath = stringToPath;
  7642. return _stringToPath;
  7643. }
  7644. /**
  7645. * A specialized version of `_.map` for arrays without support for iteratee
  7646. * shorthands.
  7647. *
  7648. * @private
  7649. * @param {Array} [array] The array to iterate over.
  7650. * @param {Function} iteratee The function invoked per iteration.
  7651. * @returns {Array} Returns the new mapped array.
  7652. */
  7653. var _arrayMap;
  7654. var hasRequired_arrayMap;
  7655. function require_arrayMap () {
  7656. if (hasRequired_arrayMap) return _arrayMap;
  7657. hasRequired_arrayMap = 1;
  7658. function arrayMap(array, iteratee) {
  7659. var index = -1,
  7660. length = array == null ? 0 : array.length,
  7661. result = Array(length);
  7662. while (++index < length) {
  7663. result[index] = iteratee(array[index], index, array);
  7664. }
  7665. return result;
  7666. }
  7667. _arrayMap = arrayMap;
  7668. return _arrayMap;
  7669. }
  7670. var _baseToString;
  7671. var hasRequired_baseToString;
  7672. function require_baseToString () {
  7673. if (hasRequired_baseToString) return _baseToString;
  7674. hasRequired_baseToString = 1;
  7675. var Symbol = require_Symbol(),
  7676. arrayMap = require_arrayMap(),
  7677. isArray = requireIsArray(),
  7678. isSymbol = requireIsSymbol();
  7679. /** Used to convert symbols to primitives and strings. */
  7680. var symbolProto = Symbol ? Symbol.prototype : undefined,
  7681. symbolToString = symbolProto ? symbolProto.toString : undefined;
  7682. /**
  7683. * The base implementation of `_.toString` which doesn't convert nullish
  7684. * values to empty strings.
  7685. *
  7686. * @private
  7687. * @param {*} value The value to process.
  7688. * @returns {string} Returns the string.
  7689. */
  7690. function baseToString(value) {
  7691. // Exit early for strings to avoid a performance hit in some environments.
  7692. if (typeof value == 'string') {
  7693. return value;
  7694. }
  7695. if (isArray(value)) {
  7696. // Recursively convert values (susceptible to call stack limits).
  7697. return arrayMap(value, baseToString) + '';
  7698. }
  7699. if (isSymbol(value)) {
  7700. return symbolToString ? symbolToString.call(value) : '';
  7701. }
  7702. var result = (value + '');
  7703. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  7704. }
  7705. _baseToString = baseToString;
  7706. return _baseToString;
  7707. }
  7708. var toString_1;
  7709. var hasRequiredToString;
  7710. function requireToString () {
  7711. if (hasRequiredToString) return toString_1;
  7712. hasRequiredToString = 1;
  7713. var baseToString = require_baseToString();
  7714. /**
  7715. * Converts `value` to a string. An empty string is returned for `null`
  7716. * and `undefined` values. The sign of `-0` is preserved.
  7717. *
  7718. * @static
  7719. * @memberOf _
  7720. * @since 4.0.0
  7721. * @category Lang
  7722. * @param {*} value The value to convert.
  7723. * @returns {string} Returns the converted string.
  7724. * @example
  7725. *
  7726. * _.toString(null);
  7727. * // => ''
  7728. *
  7729. * _.toString(-0);
  7730. * // => '-0'
  7731. *
  7732. * _.toString([1, 2, 3]);
  7733. * // => '1,2,3'
  7734. */
  7735. function toString(value) {
  7736. return value == null ? '' : baseToString(value);
  7737. }
  7738. toString_1 = toString;
  7739. return toString_1;
  7740. }
  7741. var _castPath;
  7742. var hasRequired_castPath;
  7743. function require_castPath () {
  7744. if (hasRequired_castPath) return _castPath;
  7745. hasRequired_castPath = 1;
  7746. var isArray = requireIsArray(),
  7747. isKey = require_isKey(),
  7748. stringToPath = require_stringToPath(),
  7749. toString = requireToString();
  7750. /**
  7751. * Casts `value` to a path array if it's not one.
  7752. *
  7753. * @private
  7754. * @param {*} value The value to inspect.
  7755. * @param {Object} [object] The object to query keys on.
  7756. * @returns {Array} Returns the cast property path array.
  7757. */
  7758. function castPath(value, object) {
  7759. if (isArray(value)) {
  7760. return value;
  7761. }
  7762. return isKey(value, object) ? [value] : stringToPath(toString(value));
  7763. }
  7764. _castPath = castPath;
  7765. return _castPath;
  7766. }
  7767. var _toKey;
  7768. var hasRequired_toKey;
  7769. function require_toKey () {
  7770. if (hasRequired_toKey) return _toKey;
  7771. hasRequired_toKey = 1;
  7772. var isSymbol = requireIsSymbol();
  7773. /**
  7774. * Converts `value` to a string key if it's not a string or symbol.
  7775. *
  7776. * @private
  7777. * @param {*} value The value to inspect.
  7778. * @returns {string|symbol} Returns the key.
  7779. */
  7780. function toKey(value) {
  7781. if (typeof value == 'string' || isSymbol(value)) {
  7782. return value;
  7783. }
  7784. var result = (value + '');
  7785. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  7786. }
  7787. _toKey = toKey;
  7788. return _toKey;
  7789. }
  7790. var _baseGet;
  7791. var hasRequired_baseGet;
  7792. function require_baseGet () {
  7793. if (hasRequired_baseGet) return _baseGet;
  7794. hasRequired_baseGet = 1;
  7795. var castPath = require_castPath(),
  7796. toKey = require_toKey();
  7797. /**
  7798. * The base implementation of `_.get` without support for default values.
  7799. *
  7800. * @private
  7801. * @param {Object} object The object to query.
  7802. * @param {Array|string} path The path of the property to get.
  7803. * @returns {*} Returns the resolved value.
  7804. */
  7805. function baseGet(object, path) {
  7806. path = castPath(path, object);
  7807. var index = 0,
  7808. length = path.length;
  7809. while (object != null && index < length) {
  7810. object = object[toKey(path[index++])];
  7811. }
  7812. return (index && index == length) ? object : undefined;
  7813. }
  7814. _baseGet = baseGet;
  7815. return _baseGet;
  7816. }
  7817. var get_1;
  7818. var hasRequiredGet;
  7819. function requireGet () {
  7820. if (hasRequiredGet) return get_1;
  7821. hasRequiredGet = 1;
  7822. var baseGet = require_baseGet();
  7823. /**
  7824. * Gets the value at `path` of `object`. If the resolved value is
  7825. * `undefined`, the `defaultValue` is returned in its place.
  7826. *
  7827. * @static
  7828. * @memberOf _
  7829. * @since 3.7.0
  7830. * @category Object
  7831. * @param {Object} object The object to query.
  7832. * @param {Array|string} path The path of the property to get.
  7833. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  7834. * @returns {*} Returns the resolved value.
  7835. * @example
  7836. *
  7837. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  7838. *
  7839. * _.get(object, 'a[0].b.c');
  7840. * // => 3
  7841. *
  7842. * _.get(object, ['a', '0', 'b', 'c']);
  7843. * // => 3
  7844. *
  7845. * _.get(object, 'a.b.c', 'default');
  7846. * // => 'default'
  7847. */
  7848. function get(object, path, defaultValue) {
  7849. var result = object == null ? undefined : baseGet(object, path);
  7850. return result === undefined ? defaultValue : result;
  7851. }
  7852. get_1 = get;
  7853. return get_1;
  7854. }
  7855. var getExports = requireGet();
  7856. var get = /*@__PURE__*/getDefaultExportFromCjs(getExports);
  7857. var _defineProperty;
  7858. var hasRequired_defineProperty;
  7859. function require_defineProperty () {
  7860. if (hasRequired_defineProperty) return _defineProperty;
  7861. hasRequired_defineProperty = 1;
  7862. var getNative = require_getNative();
  7863. var defineProperty = (function() {
  7864. try {
  7865. var func = getNative(Object, 'defineProperty');
  7866. func({}, '', {});
  7867. return func;
  7868. } catch (e) {}
  7869. }());
  7870. _defineProperty = defineProperty;
  7871. return _defineProperty;
  7872. }
  7873. var _baseAssignValue;
  7874. var hasRequired_baseAssignValue;
  7875. function require_baseAssignValue () {
  7876. if (hasRequired_baseAssignValue) return _baseAssignValue;
  7877. hasRequired_baseAssignValue = 1;
  7878. var defineProperty = require_defineProperty();
  7879. /**
  7880. * The base implementation of `assignValue` and `assignMergeValue` without
  7881. * value checks.
  7882. *
  7883. * @private
  7884. * @param {Object} object The object to modify.
  7885. * @param {string} key The key of the property to assign.
  7886. * @param {*} value The value to assign.
  7887. */
  7888. function baseAssignValue(object, key, value) {
  7889. if (key == '__proto__' && defineProperty) {
  7890. defineProperty(object, key, {
  7891. 'configurable': true,
  7892. 'enumerable': true,
  7893. 'value': value,
  7894. 'writable': true
  7895. });
  7896. } else {
  7897. object[key] = value;
  7898. }
  7899. }
  7900. _baseAssignValue = baseAssignValue;
  7901. return _baseAssignValue;
  7902. }
  7903. var _assignValue;
  7904. var hasRequired_assignValue;
  7905. function require_assignValue () {
  7906. if (hasRequired_assignValue) return _assignValue;
  7907. hasRequired_assignValue = 1;
  7908. var baseAssignValue = require_baseAssignValue(),
  7909. eq = requireEq();
  7910. /** Used for built-in method references. */
  7911. var objectProto = Object.prototype;
  7912. /** Used to check objects for own properties. */
  7913. var hasOwnProperty = objectProto.hasOwnProperty;
  7914. /**
  7915. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  7916. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7917. * for equality comparisons.
  7918. *
  7919. * @private
  7920. * @param {Object} object The object to modify.
  7921. * @param {string} key The key of the property to assign.
  7922. * @param {*} value The value to assign.
  7923. */
  7924. function assignValue(object, key, value) {
  7925. var objValue = object[key];
  7926. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  7927. (value === undefined && !(key in object))) {
  7928. baseAssignValue(object, key, value);
  7929. }
  7930. }
  7931. _assignValue = assignValue;
  7932. return _assignValue;
  7933. }
  7934. /** Used as references for various `Number` constants. */
  7935. var _isIndex;
  7936. var hasRequired_isIndex;
  7937. function require_isIndex () {
  7938. if (hasRequired_isIndex) return _isIndex;
  7939. hasRequired_isIndex = 1;
  7940. var MAX_SAFE_INTEGER = 9007199254740991;
  7941. /** Used to detect unsigned integer values. */
  7942. var reIsUint = /^(?:0|[1-9]\d*)$/;
  7943. /**
  7944. * Checks if `value` is a valid array-like index.
  7945. *
  7946. * @private
  7947. * @param {*} value The value to check.
  7948. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  7949. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  7950. */
  7951. function isIndex(value, length) {
  7952. var type = typeof value;
  7953. length = length == null ? MAX_SAFE_INTEGER : length;
  7954. return !!length &&
  7955. (type == 'number' ||
  7956. (type != 'symbol' && reIsUint.test(value))) &&
  7957. (value > -1 && value % 1 == 0 && value < length);
  7958. }
  7959. _isIndex = isIndex;
  7960. return _isIndex;
  7961. }
  7962. var _baseSet;
  7963. var hasRequired_baseSet;
  7964. function require_baseSet () {
  7965. if (hasRequired_baseSet) return _baseSet;
  7966. hasRequired_baseSet = 1;
  7967. var assignValue = require_assignValue(),
  7968. castPath = require_castPath(),
  7969. isIndex = require_isIndex(),
  7970. isObject = requireIsObject(),
  7971. toKey = require_toKey();
  7972. /**
  7973. * The base implementation of `_.set`.
  7974. *
  7975. * @private
  7976. * @param {Object} object The object to modify.
  7977. * @param {Array|string} path The path of the property to set.
  7978. * @param {*} value The value to set.
  7979. * @param {Function} [customizer] The function to customize path creation.
  7980. * @returns {Object} Returns `object`.
  7981. */
  7982. function baseSet(object, path, value, customizer) {
  7983. if (!isObject(object)) {
  7984. return object;
  7985. }
  7986. path = castPath(path, object);
  7987. var index = -1,
  7988. length = path.length,
  7989. lastIndex = length - 1,
  7990. nested = object;
  7991. while (nested != null && ++index < length) {
  7992. var key = toKey(path[index]),
  7993. newValue = value;
  7994. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  7995. return object;
  7996. }
  7997. if (index != lastIndex) {
  7998. var objValue = nested[key];
  7999. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  8000. if (newValue === undefined) {
  8001. newValue = isObject(objValue)
  8002. ? objValue
  8003. : (isIndex(path[index + 1]) ? [] : {});
  8004. }
  8005. }
  8006. assignValue(nested, key, newValue);
  8007. nested = nested[key];
  8008. }
  8009. return object;
  8010. }
  8011. _baseSet = baseSet;
  8012. return _baseSet;
  8013. }
  8014. var set_1;
  8015. var hasRequiredSet;
  8016. function requireSet () {
  8017. if (hasRequiredSet) return set_1;
  8018. hasRequiredSet = 1;
  8019. var baseSet = require_baseSet();
  8020. /**
  8021. * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
  8022. * it's created. Arrays are created for missing index properties while objects
  8023. * are created for all other missing properties. Use `_.setWith` to customize
  8024. * `path` creation.
  8025. *
  8026. * **Note:** This method mutates `object`.
  8027. *
  8028. * @static
  8029. * @memberOf _
  8030. * @since 3.7.0
  8031. * @category Object
  8032. * @param {Object} object The object to modify.
  8033. * @param {Array|string} path The path of the property to set.
  8034. * @param {*} value The value to set.
  8035. * @returns {Object} Returns `object`.
  8036. * @example
  8037. *
  8038. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  8039. *
  8040. * _.set(object, 'a[0].b.c', 4);
  8041. * console.log(object.a[0].b.c);
  8042. * // => 4
  8043. *
  8044. * _.set(object, ['x', '0', 'y', 'z'], 5);
  8045. * console.log(object.x[0].y.z);
  8046. * // => 5
  8047. */
  8048. function set(object, path, value) {
  8049. return object == null ? object : baseSet(object, path, value);
  8050. }
  8051. set_1 = set;
  8052. return set_1;
  8053. }
  8054. var setExports = requireSet();
  8055. var set = /*@__PURE__*/getDefaultExportFromCjs(setExports);
  8056. /**
  8057. * Copies the values of `source` to `array`.
  8058. *
  8059. * @private
  8060. * @param {Array} source The array to copy values from.
  8061. * @param {Array} [array=[]] The array to copy values to.
  8062. * @returns {Array} Returns `array`.
  8063. */
  8064. var _copyArray;
  8065. var hasRequired_copyArray;
  8066. function require_copyArray () {
  8067. if (hasRequired_copyArray) return _copyArray;
  8068. hasRequired_copyArray = 1;
  8069. function copyArray(source, array) {
  8070. var index = -1,
  8071. length = source.length;
  8072. array || (array = Array(length));
  8073. while (++index < length) {
  8074. array[index] = source[index];
  8075. }
  8076. return array;
  8077. }
  8078. _copyArray = copyArray;
  8079. return _copyArray;
  8080. }
  8081. var toPath_1;
  8082. var hasRequiredToPath;
  8083. function requireToPath () {
  8084. if (hasRequiredToPath) return toPath_1;
  8085. hasRequiredToPath = 1;
  8086. var arrayMap = require_arrayMap(),
  8087. copyArray = require_copyArray(),
  8088. isArray = requireIsArray(),
  8089. isSymbol = requireIsSymbol(),
  8090. stringToPath = require_stringToPath(),
  8091. toKey = require_toKey(),
  8092. toString = requireToString();
  8093. /**
  8094. * Converts `value` to a property path array.
  8095. *
  8096. * @static
  8097. * @memberOf _
  8098. * @since 4.0.0
  8099. * @category Util
  8100. * @param {*} value The value to convert.
  8101. * @returns {Array} Returns the new property path array.
  8102. * @example
  8103. *
  8104. * _.toPath('a.b.c');
  8105. * // => ['a', 'b', 'c']
  8106. *
  8107. * _.toPath('a[0].b.c');
  8108. * // => ['a', '0', 'b', 'c']
  8109. */
  8110. function toPath(value) {
  8111. if (isArray(value)) {
  8112. return arrayMap(value, toKey);
  8113. }
  8114. return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
  8115. }
  8116. toPath_1 = toPath;
  8117. return toPath_1;
  8118. }
  8119. var toPathExports = requireToPath();
  8120. var toPath = /*@__PURE__*/getDefaultExportFromCjs(toPathExports);
  8121. var define$2 = {
  8122. // access data field
  8123. data: function data(params) {
  8124. var defaults = {
  8125. field: 'data',
  8126. bindingEvent: 'data',
  8127. allowBinding: false,
  8128. allowSetting: false,
  8129. allowGetting: false,
  8130. settingEvent: 'data',
  8131. settingTriggersEvent: false,
  8132. triggerFnName: 'trigger',
  8133. immutableKeys: {},
  8134. // key => true if immutable
  8135. updateStyle: false,
  8136. beforeGet: function beforeGet(self) {},
  8137. beforeSet: function beforeSet(self, obj) {},
  8138. onSet: function onSet(self) {},
  8139. canSet: function canSet(self) {
  8140. return true;
  8141. }
  8142. };
  8143. params = extend({}, defaults, params);
  8144. return function dataImpl(name, value) {
  8145. var p = params;
  8146. var self = this;
  8147. var selfIsArrayLike = self.length !== undefined;
  8148. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  8149. var single = selfIsArrayLike ? self[0] : self;
  8150. // .data('foo', ...)
  8151. if (string(name)) {
  8152. // set or get property
  8153. var isPathLike = name.indexOf('.') !== -1; // there might be a normal field with a dot
  8154. var path = isPathLike && toPath(name);
  8155. // .data('foo')
  8156. if (p.allowGetting && value === undefined) {
  8157. // get
  8158. var ret;
  8159. if (single) {
  8160. p.beforeGet(single);
  8161. // check if it's path and a field with the same name doesn't exist
  8162. if (path && single._private[p.field][name] === undefined) {
  8163. ret = get(single._private[p.field], path);
  8164. } else {
  8165. ret = single._private[p.field][name];
  8166. }
  8167. }
  8168. return ret;
  8169. // .data('foo', 'bar')
  8170. } else if (p.allowSetting && value !== undefined) {
  8171. // set
  8172. var valid = !p.immutableKeys[name];
  8173. if (valid) {
  8174. var change = _defineProperty$1({}, name, value);
  8175. p.beforeSet(self, change);
  8176. for (var i = 0, l = all.length; i < l; i++) {
  8177. var ele = all[i];
  8178. if (p.canSet(ele)) {
  8179. if (path && single._private[p.field][name] === undefined) {
  8180. set(ele._private[p.field], path, value);
  8181. } else {
  8182. ele._private[p.field][name] = value;
  8183. }
  8184. }
  8185. }
  8186. // update mappers if asked
  8187. if (p.updateStyle) {
  8188. self.updateStyle();
  8189. }
  8190. // call onSet callback
  8191. p.onSet(self);
  8192. if (p.settingTriggersEvent) {
  8193. self[p.triggerFnName](p.settingEvent);
  8194. }
  8195. }
  8196. }
  8197. // .data({ 'foo': 'bar' })
  8198. } else if (p.allowSetting && plainObject(name)) {
  8199. // extend
  8200. var obj = name;
  8201. var k, v;
  8202. var keys = Object.keys(obj);
  8203. p.beforeSet(self, obj);
  8204. for (var _i = 0; _i < keys.length; _i++) {
  8205. k = keys[_i];
  8206. v = obj[k];
  8207. var _valid = !p.immutableKeys[k];
  8208. if (_valid) {
  8209. for (var j = 0; j < all.length; j++) {
  8210. var _ele = all[j];
  8211. if (p.canSet(_ele)) {
  8212. _ele._private[p.field][k] = v;
  8213. }
  8214. }
  8215. }
  8216. }
  8217. // update mappers if asked
  8218. if (p.updateStyle) {
  8219. self.updateStyle();
  8220. }
  8221. // call onSet callback
  8222. p.onSet(self);
  8223. if (p.settingTriggersEvent) {
  8224. self[p.triggerFnName](p.settingEvent);
  8225. }
  8226. // .data(function(){ ... })
  8227. } else if (p.allowBinding && fn$6(name)) {
  8228. // bind to event
  8229. var fn = name;
  8230. self.on(p.bindingEvent, fn);
  8231. // .data()
  8232. } else if (p.allowGetting && name === undefined) {
  8233. // get whole object
  8234. var _ret;
  8235. if (single) {
  8236. p.beforeGet(single);
  8237. _ret = single._private[p.field];
  8238. }
  8239. return _ret;
  8240. }
  8241. return self; // maintain chainability
  8242. }; // function
  8243. },
  8244. // data
  8245. // remove data field
  8246. removeData: function removeData(params) {
  8247. var defaults = {
  8248. field: 'data',
  8249. event: 'data',
  8250. triggerFnName: 'trigger',
  8251. triggerEvent: false,
  8252. immutableKeys: {} // key => true if immutable
  8253. };
  8254. params = extend({}, defaults, params);
  8255. return function removeDataImpl(names) {
  8256. var p = params;
  8257. var self = this;
  8258. var selfIsArrayLike = self.length !== undefined;
  8259. var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
  8260. // .removeData('foo bar')
  8261. if (string(names)) {
  8262. // then get the list of keys, and delete them
  8263. var keys = names.split(/\s+/);
  8264. var l = keys.length;
  8265. for (var i = 0; i < l; i++) {
  8266. // delete each non-empty key
  8267. var key = keys[i];
  8268. if (emptyString(key)) {
  8269. continue;
  8270. }
  8271. var valid = !p.immutableKeys[key]; // not valid if immutable
  8272. if (valid) {
  8273. for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) {
  8274. all[i_a]._private[p.field][key] = undefined;
  8275. }
  8276. }
  8277. }
  8278. if (p.triggerEvent) {
  8279. self[p.triggerFnName](p.event);
  8280. }
  8281. // .removeData()
  8282. } else if (names === undefined) {
  8283. // then delete all keys
  8284. for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) {
  8285. var _privateFields = all[_i_a]._private[p.field];
  8286. var _keys = Object.keys(_privateFields);
  8287. for (var _i2 = 0; _i2 < _keys.length; _i2++) {
  8288. var _key = _keys[_i2];
  8289. var validKeyToDelete = !p.immutableKeys[_key];
  8290. if (validKeyToDelete) {
  8291. _privateFields[_key] = undefined;
  8292. }
  8293. }
  8294. }
  8295. if (p.triggerEvent) {
  8296. self[p.triggerFnName](p.event);
  8297. }
  8298. }
  8299. return self; // maintain chaining
  8300. }; // function
  8301. } // removeData
  8302. }; // define
  8303. var define$1 = {
  8304. eventAliasesOn: function eventAliasesOn(proto) {
  8305. var p = proto;
  8306. p.addListener = p.listen = p.bind = p.on;
  8307. p.unlisten = p.unbind = p.off = p.removeListener;
  8308. p.trigger = p.emit;
  8309. // this is just a wrapper alias of .on()
  8310. p.pon = p.promiseOn = function (events, selector) {
  8311. var self = this;
  8312. var args = Array.prototype.slice.call(arguments, 0);
  8313. return new Promise$1(function (resolve, reject) {
  8314. var callback = function callback(e) {
  8315. self.off.apply(self, offArgs);
  8316. resolve(e);
  8317. };
  8318. var onArgs = args.concat([callback]);
  8319. var offArgs = onArgs.concat([]);
  8320. self.on.apply(self, onArgs);
  8321. });
  8322. };
  8323. }
  8324. }; // define
  8325. // use this module to cherry pick functions into your prototype
  8326. // (useful for functions shared between the core and collections, for example)
  8327. var define = {};
  8328. [define$3, define$2, define$1].forEach(function (m) {
  8329. extend(define, m);
  8330. });
  8331. var elesfn$i = {
  8332. animate: define.animate(),
  8333. animation: define.animation(),
  8334. animated: define.animated(),
  8335. clearQueue: define.clearQueue(),
  8336. delay: define.delay(),
  8337. delayAnimation: define.delayAnimation(),
  8338. stop: define.stop()
  8339. };
  8340. var elesfn$h = {
  8341. classes: function classes(_classes) {
  8342. var self = this;
  8343. if (_classes === undefined) {
  8344. var ret = [];
  8345. self[0]._private.classes.forEach(function (cls) {
  8346. return ret.push(cls);
  8347. });
  8348. return ret;
  8349. } else if (!array(_classes)) {
  8350. // extract classes from string
  8351. _classes = (_classes || '').match(/\S+/g) || [];
  8352. }
  8353. var changed = [];
  8354. var classesSet = new Set$1(_classes);
  8355. // check and update each ele
  8356. for (var j = 0; j < self.length; j++) {
  8357. var ele = self[j];
  8358. var _p = ele._private;
  8359. var eleClasses = _p.classes;
  8360. var changedEle = false;
  8361. // check if ele has all of the passed classes
  8362. for (var i = 0; i < _classes.length; i++) {
  8363. var cls = _classes[i];
  8364. var eleHasClass = eleClasses.has(cls);
  8365. if (!eleHasClass) {
  8366. changedEle = true;
  8367. break;
  8368. }
  8369. }
  8370. // check if ele has classes outside of those passed
  8371. if (!changedEle) {
  8372. changedEle = eleClasses.size !== _classes.length;
  8373. }
  8374. if (changedEle) {
  8375. _p.classes = classesSet;
  8376. changed.push(ele);
  8377. }
  8378. }
  8379. // trigger update style on those eles that had class changes
  8380. if (changed.length > 0) {
  8381. this.spawn(changed).updateStyle().emit('class');
  8382. }
  8383. return self;
  8384. },
  8385. addClass: function addClass(classes) {
  8386. return this.toggleClass(classes, true);
  8387. },
  8388. hasClass: function hasClass(className) {
  8389. var ele = this[0];
  8390. return ele != null && ele._private.classes.has(className);
  8391. },
  8392. toggleClass: function toggleClass(classes, toggle) {
  8393. if (!array(classes)) {
  8394. // extract classes from string
  8395. classes = classes.match(/\S+/g) || [];
  8396. }
  8397. var self = this;
  8398. var toggleUndefd = toggle === undefined;
  8399. var changed = []; // eles who had classes changed
  8400. for (var i = 0, il = self.length; i < il; i++) {
  8401. var ele = self[i];
  8402. var eleClasses = ele._private.classes;
  8403. var changedEle = false;
  8404. for (var j = 0; j < classes.length; j++) {
  8405. var cls = classes[j];
  8406. var hasClass = eleClasses.has(cls);
  8407. var changedNow = false;
  8408. if (toggle || toggleUndefd && !hasClass) {
  8409. eleClasses.add(cls);
  8410. changedNow = true;
  8411. } else if (!toggle || toggleUndefd && hasClass) {
  8412. eleClasses["delete"](cls);
  8413. changedNow = true;
  8414. }
  8415. if (!changedEle && changedNow) {
  8416. changed.push(ele);
  8417. changedEle = true;
  8418. }
  8419. } // for j classes
  8420. } // for i eles
  8421. // trigger update style on those eles that had class changes
  8422. if (changed.length > 0) {
  8423. this.spawn(changed).updateStyle().emit('class');
  8424. }
  8425. return self;
  8426. },
  8427. removeClass: function removeClass(classes) {
  8428. return this.toggleClass(classes, false);
  8429. },
  8430. flashClass: function flashClass(classes, duration) {
  8431. var self = this;
  8432. if (duration == null) {
  8433. duration = 250;
  8434. } else if (duration === 0) {
  8435. return self; // nothing to do really
  8436. }
  8437. self.addClass(classes);
  8438. setTimeout(function () {
  8439. self.removeClass(classes);
  8440. }, duration);
  8441. return self;
  8442. }
  8443. };
  8444. elesfn$h.className = elesfn$h.classNames = elesfn$h.classes;
  8445. // tokens in the query language
  8446. var tokens = {
  8447. metaChar: '[\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]',
  8448. // chars we need to escape in let names, etc
  8449. comparatorOp: '=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=',
  8450. // binary comparison op (used in data selectors)
  8451. boolOp: '\\?|\\!|\\^',
  8452. // boolean (unary) operators (used in data selectors)
  8453. string: '"(?:\\\\"|[^"])*"' + '|' + "'(?:\\\\'|[^'])*'",
  8454. // string literals (used in data selectors) -- doublequotes | singlequotes
  8455. number: number,
  8456. // number literal (used in data selectors) --- e.g. 0.1234, 1234, 12e123
  8457. meta: 'degree|indegree|outdegree',
  8458. // allowed metadata fields (i.e. allowed functions to use from Collection)
  8459. separator: '\\s*,\\s*',
  8460. // queries are separated by commas, e.g. edge[foo = 'bar'], node.someClass
  8461. descendant: '\\s+',
  8462. child: '\\s+>\\s+',
  8463. subject: '\\$',
  8464. group: 'node|edge|\\*',
  8465. directedEdge: '\\s+->\\s+',
  8466. undirectedEdge: '\\s+<->\\s+'
  8467. };
  8468. tokens.variable = '(?:[\\w-.]|(?:\\\\' + tokens.metaChar + '))+'; // a variable name can have letters, numbers, dashes, and periods
  8469. tokens.className = '(?:[\\w-]|(?:\\\\' + tokens.metaChar + '))+'; // a class name has the same rules as a variable except it can't have a '.' in the name
  8470. tokens.value = tokens.string + '|' + tokens.number; // a value literal, either a string or number
  8471. tokens.id = tokens.variable; // an element id (follows variable conventions)
  8472. (function () {
  8473. var ops, op, i;
  8474. // add @ variants to comparatorOp
  8475. ops = tokens.comparatorOp.split('|');
  8476. for (i = 0; i < ops.length; i++) {
  8477. op = ops[i];
  8478. tokens.comparatorOp += '|@' + op;
  8479. }
  8480. // add ! variants to comparatorOp
  8481. ops = tokens.comparatorOp.split('|');
  8482. for (i = 0; i < ops.length; i++) {
  8483. op = ops[i];
  8484. if (op.indexOf('!') >= 0) {
  8485. continue;
  8486. } // skip ops that explicitly contain !
  8487. if (op === '=') {
  8488. continue;
  8489. } // skip = b/c != is explicitly defined
  8490. tokens.comparatorOp += '|\\!' + op;
  8491. }
  8492. })();
  8493. /**
  8494. * Make a new query object
  8495. *
  8496. * @prop type {Type} The type enum (int) of the query
  8497. * @prop checks List of checks to make against an ele to test for a match
  8498. */
  8499. var newQuery = function newQuery() {
  8500. return {
  8501. checks: []
  8502. };
  8503. };
  8504. /**
  8505. * A check type enum-like object. Uses integer values for fast match() lookup.
  8506. * The ordering does not matter as long as the ints are unique.
  8507. */
  8508. var Type = {
  8509. /** E.g. node */
  8510. GROUP: 0,
  8511. /** A collection of elements */
  8512. COLLECTION: 1,
  8513. /** A filter(ele) function */
  8514. FILTER: 2,
  8515. /** E.g. [foo > 1] */
  8516. DATA_COMPARE: 3,
  8517. /** E.g. [foo] */
  8518. DATA_EXIST: 4,
  8519. /** E.g. [?foo] */
  8520. DATA_BOOL: 5,
  8521. /** E.g. [[degree > 2]] */
  8522. META_COMPARE: 6,
  8523. /** E.g. :selected */
  8524. STATE: 7,
  8525. /** E.g. #foo */
  8526. ID: 8,
  8527. /** E.g. .foo */
  8528. CLASS: 9,
  8529. /** E.g. #foo <-> #bar */
  8530. UNDIRECTED_EDGE: 10,
  8531. /** E.g. #foo -> #bar */
  8532. DIRECTED_EDGE: 11,
  8533. /** E.g. $#foo -> #bar */
  8534. NODE_SOURCE: 12,
  8535. /** E.g. #foo -> $#bar */
  8536. NODE_TARGET: 13,
  8537. /** E.g. $#foo <-> #bar */
  8538. NODE_NEIGHBOR: 14,
  8539. /** E.g. #foo > #bar */
  8540. CHILD: 15,
  8541. /** E.g. #foo #bar */
  8542. DESCENDANT: 16,
  8543. /** E.g. $#foo > #bar */
  8544. PARENT: 17,
  8545. /** E.g. $#foo #bar */
  8546. ANCESTOR: 18,
  8547. /** E.g. #foo > $bar > #baz */
  8548. COMPOUND_SPLIT: 19,
  8549. /** Always matches, useful placeholder for subject in `COMPOUND_SPLIT` */
  8550. TRUE: 20
  8551. };
  8552. var stateSelectors = [{
  8553. selector: ':selected',
  8554. matches: function matches(ele) {
  8555. return ele.selected();
  8556. }
  8557. }, {
  8558. selector: ':unselected',
  8559. matches: function matches(ele) {
  8560. return !ele.selected();
  8561. }
  8562. }, {
  8563. selector: ':selectable',
  8564. matches: function matches(ele) {
  8565. return ele.selectable();
  8566. }
  8567. }, {
  8568. selector: ':unselectable',
  8569. matches: function matches(ele) {
  8570. return !ele.selectable();
  8571. }
  8572. }, {
  8573. selector: ':locked',
  8574. matches: function matches(ele) {
  8575. return ele.locked();
  8576. }
  8577. }, {
  8578. selector: ':unlocked',
  8579. matches: function matches(ele) {
  8580. return !ele.locked();
  8581. }
  8582. }, {
  8583. selector: ':visible',
  8584. matches: function matches(ele) {
  8585. return ele.visible();
  8586. }
  8587. }, {
  8588. selector: ':hidden',
  8589. matches: function matches(ele) {
  8590. return !ele.visible();
  8591. }
  8592. }, {
  8593. selector: ':transparent',
  8594. matches: function matches(ele) {
  8595. return ele.transparent();
  8596. }
  8597. }, {
  8598. selector: ':grabbed',
  8599. matches: function matches(ele) {
  8600. return ele.grabbed();
  8601. }
  8602. }, {
  8603. selector: ':free',
  8604. matches: function matches(ele) {
  8605. return !ele.grabbed();
  8606. }
  8607. }, {
  8608. selector: ':removed',
  8609. matches: function matches(ele) {
  8610. return ele.removed();
  8611. }
  8612. }, {
  8613. selector: ':inside',
  8614. matches: function matches(ele) {
  8615. return !ele.removed();
  8616. }
  8617. }, {
  8618. selector: ':grabbable',
  8619. matches: function matches(ele) {
  8620. return ele.grabbable();
  8621. }
  8622. }, {
  8623. selector: ':ungrabbable',
  8624. matches: function matches(ele) {
  8625. return !ele.grabbable();
  8626. }
  8627. }, {
  8628. selector: ':animated',
  8629. matches: function matches(ele) {
  8630. return ele.animated();
  8631. }
  8632. }, {
  8633. selector: ':unanimated',
  8634. matches: function matches(ele) {
  8635. return !ele.animated();
  8636. }
  8637. }, {
  8638. selector: ':parent',
  8639. matches: function matches(ele) {
  8640. return ele.isParent();
  8641. }
  8642. }, {
  8643. selector: ':childless',
  8644. matches: function matches(ele) {
  8645. return ele.isChildless();
  8646. }
  8647. }, {
  8648. selector: ':child',
  8649. matches: function matches(ele) {
  8650. return ele.isChild();
  8651. }
  8652. }, {
  8653. selector: ':orphan',
  8654. matches: function matches(ele) {
  8655. return ele.isOrphan();
  8656. }
  8657. }, {
  8658. selector: ':nonorphan',
  8659. matches: function matches(ele) {
  8660. return ele.isChild();
  8661. }
  8662. }, {
  8663. selector: ':compound',
  8664. matches: function matches(ele) {
  8665. if (ele.isNode()) {
  8666. return ele.isParent();
  8667. } else {
  8668. return ele.source().isParent() || ele.target().isParent();
  8669. }
  8670. }
  8671. }, {
  8672. selector: ':loop',
  8673. matches: function matches(ele) {
  8674. return ele.isLoop();
  8675. }
  8676. }, {
  8677. selector: ':simple',
  8678. matches: function matches(ele) {
  8679. return ele.isSimple();
  8680. }
  8681. }, {
  8682. selector: ':active',
  8683. matches: function matches(ele) {
  8684. return ele.active();
  8685. }
  8686. }, {
  8687. selector: ':inactive',
  8688. matches: function matches(ele) {
  8689. return !ele.active();
  8690. }
  8691. }, {
  8692. selector: ':backgrounding',
  8693. matches: function matches(ele) {
  8694. return ele.backgrounding();
  8695. }
  8696. }, {
  8697. selector: ':nonbackgrounding',
  8698. matches: function matches(ele) {
  8699. return !ele.backgrounding();
  8700. }
  8701. }].sort(function (a, b) {
  8702. // n.b. selectors that are starting substrings of others must have the longer ones first
  8703. return descending(a.selector, b.selector);
  8704. });
  8705. var lookup = function () {
  8706. var selToFn = {};
  8707. var s;
  8708. for (var i = 0; i < stateSelectors.length; i++) {
  8709. s = stateSelectors[i];
  8710. selToFn[s.selector] = s.matches;
  8711. }
  8712. return selToFn;
  8713. }();
  8714. var stateSelectorMatches = function stateSelectorMatches(sel, ele) {
  8715. return lookup[sel](ele);
  8716. };
  8717. var stateSelectorRegex = '(' + stateSelectors.map(function (s) {
  8718. return s.selector;
  8719. }).join('|') + ')';
  8720. // when a token like a variable has escaped meta characters, we need to clean the backslashes out
  8721. // so that values get compared properly in Selector.filter()
  8722. var cleanMetaChars = function cleanMetaChars(str) {
  8723. return str.replace(new RegExp('\\\\(' + tokens.metaChar + ')', 'g'), function (match, $1) {
  8724. return $1;
  8725. });
  8726. };
  8727. var replaceLastQuery = function replaceLastQuery(selector, examiningQuery, replacementQuery) {
  8728. selector[selector.length - 1] = replacementQuery;
  8729. };
  8730. // NOTE: add new expression syntax here to have it recognised by the parser;
  8731. // - a query contains all adjacent (i.e. no separator in between) expressions;
  8732. // - the current query is stored in selector[i]
  8733. // - you need to check the query objects in match() for it actually filter properly, but that's pretty straight forward
  8734. var exprs = [{
  8735. name: 'group',
  8736. // just used for identifying when debugging
  8737. query: true,
  8738. regex: '(' + tokens.group + ')',
  8739. populate: function populate(selector, query, _ref) {
  8740. var _ref2 = _slicedToArray(_ref, 1),
  8741. group = _ref2[0];
  8742. query.checks.push({
  8743. type: Type.GROUP,
  8744. value: group === '*' ? group : group + 's'
  8745. });
  8746. }
  8747. }, {
  8748. name: 'state',
  8749. query: true,
  8750. regex: stateSelectorRegex,
  8751. populate: function populate(selector, query, _ref3) {
  8752. var _ref4 = _slicedToArray(_ref3, 1),
  8753. state = _ref4[0];
  8754. query.checks.push({
  8755. type: Type.STATE,
  8756. value: state
  8757. });
  8758. }
  8759. }, {
  8760. name: 'id',
  8761. query: true,
  8762. regex: '\\#(' + tokens.id + ')',
  8763. populate: function populate(selector, query, _ref5) {
  8764. var _ref6 = _slicedToArray(_ref5, 1),
  8765. id = _ref6[0];
  8766. query.checks.push({
  8767. type: Type.ID,
  8768. value: cleanMetaChars(id)
  8769. });
  8770. }
  8771. }, {
  8772. name: 'className',
  8773. query: true,
  8774. regex: '\\.(' + tokens.className + ')',
  8775. populate: function populate(selector, query, _ref7) {
  8776. var _ref8 = _slicedToArray(_ref7, 1),
  8777. className = _ref8[0];
  8778. query.checks.push({
  8779. type: Type.CLASS,
  8780. value: cleanMetaChars(className)
  8781. });
  8782. }
  8783. }, {
  8784. name: 'dataExists',
  8785. query: true,
  8786. regex: '\\[\\s*(' + tokens.variable + ')\\s*\\]',
  8787. populate: function populate(selector, query, _ref9) {
  8788. var _ref10 = _slicedToArray(_ref9, 1),
  8789. variable = _ref10[0];
  8790. query.checks.push({
  8791. type: Type.DATA_EXIST,
  8792. field: cleanMetaChars(variable)
  8793. });
  8794. }
  8795. }, {
  8796. name: 'dataCompare',
  8797. query: true,
  8798. regex: '\\[\\s*(' + tokens.variable + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.value + ')\\s*\\]',
  8799. populate: function populate(selector, query, _ref11) {
  8800. var _ref12 = _slicedToArray(_ref11, 3),
  8801. variable = _ref12[0],
  8802. comparatorOp = _ref12[1],
  8803. value = _ref12[2];
  8804. var valueIsString = new RegExp('^' + tokens.string + '$').exec(value) != null;
  8805. if (valueIsString) {
  8806. value = value.substring(1, value.length - 1);
  8807. } else {
  8808. value = parseFloat(value);
  8809. }
  8810. query.checks.push({
  8811. type: Type.DATA_COMPARE,
  8812. field: cleanMetaChars(variable),
  8813. operator: comparatorOp,
  8814. value: value
  8815. });
  8816. }
  8817. }, {
  8818. name: 'dataBool',
  8819. query: true,
  8820. regex: '\\[\\s*(' + tokens.boolOp + ')\\s*(' + tokens.variable + ')\\s*\\]',
  8821. populate: function populate(selector, query, _ref13) {
  8822. var _ref14 = _slicedToArray(_ref13, 2),
  8823. boolOp = _ref14[0],
  8824. variable = _ref14[1];
  8825. query.checks.push({
  8826. type: Type.DATA_BOOL,
  8827. field: cleanMetaChars(variable),
  8828. operator: boolOp
  8829. });
  8830. }
  8831. }, {
  8832. name: 'metaCompare',
  8833. query: true,
  8834. regex: '\\[\\[\\s*(' + tokens.meta + ')\\s*(' + tokens.comparatorOp + ')\\s*(' + tokens.number + ')\\s*\\]\\]',
  8835. populate: function populate(selector, query, _ref15) {
  8836. var _ref16 = _slicedToArray(_ref15, 3),
  8837. meta = _ref16[0],
  8838. comparatorOp = _ref16[1],
  8839. number = _ref16[2];
  8840. query.checks.push({
  8841. type: Type.META_COMPARE,
  8842. field: cleanMetaChars(meta),
  8843. operator: comparatorOp,
  8844. value: parseFloat(number)
  8845. });
  8846. }
  8847. }, {
  8848. name: 'nextQuery',
  8849. separator: true,
  8850. regex: tokens.separator,
  8851. populate: function populate(selector, query) {
  8852. var currentSubject = selector.currentSubject;
  8853. var edgeCount = selector.edgeCount;
  8854. var compoundCount = selector.compoundCount;
  8855. var lastQ = selector[selector.length - 1];
  8856. if (currentSubject != null) {
  8857. lastQ.subject = currentSubject;
  8858. selector.currentSubject = null;
  8859. }
  8860. lastQ.edgeCount = edgeCount;
  8861. lastQ.compoundCount = compoundCount;
  8862. selector.edgeCount = 0;
  8863. selector.compoundCount = 0;
  8864. // go on to next query
  8865. var nextQuery = selector[selector.length++] = newQuery();
  8866. return nextQuery; // this is the new query to be filled by the following exprs
  8867. }
  8868. }, {
  8869. name: 'directedEdge',
  8870. separator: true,
  8871. regex: tokens.directedEdge,
  8872. populate: function populate(selector, query) {
  8873. if (selector.currentSubject == null) {
  8874. // undirected edge
  8875. var edgeQuery = newQuery();
  8876. var source = query;
  8877. var target = newQuery();
  8878. edgeQuery.checks.push({
  8879. type: Type.DIRECTED_EDGE,
  8880. source: source,
  8881. target: target
  8882. });
  8883. // the query in the selector should be the edge rather than the source
  8884. replaceLastQuery(selector, query, edgeQuery);
  8885. selector.edgeCount++;
  8886. // we're now populating the target query with expressions that follow
  8887. return target;
  8888. } else {
  8889. // source/target
  8890. var srcTgtQ = newQuery();
  8891. var _source = query;
  8892. var _target = newQuery();
  8893. srcTgtQ.checks.push({
  8894. type: Type.NODE_SOURCE,
  8895. source: _source,
  8896. target: _target
  8897. });
  8898. // the query in the selector should be the neighbourhood rather than the node
  8899. replaceLastQuery(selector, query, srcTgtQ);
  8900. selector.edgeCount++;
  8901. return _target; // now populating the target with the following expressions
  8902. }
  8903. }
  8904. }, {
  8905. name: 'undirectedEdge',
  8906. separator: true,
  8907. regex: tokens.undirectedEdge,
  8908. populate: function populate(selector, query) {
  8909. if (selector.currentSubject == null) {
  8910. // undirected edge
  8911. var edgeQuery = newQuery();
  8912. var source = query;
  8913. var target = newQuery();
  8914. edgeQuery.checks.push({
  8915. type: Type.UNDIRECTED_EDGE,
  8916. nodes: [source, target]
  8917. });
  8918. // the query in the selector should be the edge rather than the source
  8919. replaceLastQuery(selector, query, edgeQuery);
  8920. selector.edgeCount++;
  8921. // we're now populating the target query with expressions that follow
  8922. return target;
  8923. } else {
  8924. // neighbourhood
  8925. var nhoodQ = newQuery();
  8926. var node = query;
  8927. var neighbor = newQuery();
  8928. nhoodQ.checks.push({
  8929. type: Type.NODE_NEIGHBOR,
  8930. node: node,
  8931. neighbor: neighbor
  8932. });
  8933. // the query in the selector should be the neighbourhood rather than the node
  8934. replaceLastQuery(selector, query, nhoodQ);
  8935. return neighbor; // now populating the neighbor with following expressions
  8936. }
  8937. }
  8938. }, {
  8939. name: 'child',
  8940. separator: true,
  8941. regex: tokens.child,
  8942. populate: function populate(selector, query) {
  8943. if (selector.currentSubject == null) {
  8944. // default: child query
  8945. var parentChildQuery = newQuery();
  8946. var child = newQuery();
  8947. var parent = selector[selector.length - 1];
  8948. parentChildQuery.checks.push({
  8949. type: Type.CHILD,
  8950. parent: parent,
  8951. child: child
  8952. });
  8953. // the query in the selector should be the '>' itself
  8954. replaceLastQuery(selector, query, parentChildQuery);
  8955. selector.compoundCount++;
  8956. // we're now populating the child query with expressions that follow
  8957. return child;
  8958. } else if (selector.currentSubject === query) {
  8959. // compound split query
  8960. var compound = newQuery();
  8961. var left = selector[selector.length - 1];
  8962. var right = newQuery();
  8963. var subject = newQuery();
  8964. var _child = newQuery();
  8965. var _parent = newQuery();
  8966. // set up the root compound q
  8967. compound.checks.push({
  8968. type: Type.COMPOUND_SPLIT,
  8969. left: left,
  8970. right: right,
  8971. subject: subject
  8972. });
  8973. // populate the subject and replace the q at the old spot (within left) with TRUE
  8974. subject.checks = query.checks; // take the checks from the left
  8975. query.checks = [{
  8976. type: Type.TRUE
  8977. }]; // checks under left refs the subject implicitly
  8978. // set up the right q
  8979. _parent.checks.push({
  8980. type: Type.TRUE
  8981. }); // parent implicitly refs the subject
  8982. right.checks.push({
  8983. type: Type.PARENT,
  8984. // type is swapped on right side queries
  8985. parent: _parent,
  8986. child: _child // empty for now
  8987. });
  8988. replaceLastQuery(selector, left, compound);
  8989. // update the ref since we moved things around for `query`
  8990. selector.currentSubject = subject;
  8991. selector.compoundCount++;
  8992. return _child; // now populating the right side's child
  8993. } else {
  8994. // parent query
  8995. // info for parent query
  8996. var _parent2 = newQuery();
  8997. var _child2 = newQuery();
  8998. var pcQChecks = [{
  8999. type: Type.PARENT,
  9000. parent: _parent2,
  9001. child: _child2
  9002. }];
  9003. // the parent-child query takes the place of the query previously being populated
  9004. _parent2.checks = query.checks; // the previous query contains the checks for the parent
  9005. query.checks = pcQChecks; // pc query takes over
  9006. selector.compoundCount++;
  9007. return _child2; // we're now populating the child
  9008. }
  9009. }
  9010. }, {
  9011. name: 'descendant',
  9012. separator: true,
  9013. regex: tokens.descendant,
  9014. populate: function populate(selector, query) {
  9015. if (selector.currentSubject == null) {
  9016. // default: descendant query
  9017. var ancChQuery = newQuery();
  9018. var descendant = newQuery();
  9019. var ancestor = selector[selector.length - 1];
  9020. ancChQuery.checks.push({
  9021. type: Type.DESCENDANT,
  9022. ancestor: ancestor,
  9023. descendant: descendant
  9024. });
  9025. // the query in the selector should be the '>' itself
  9026. replaceLastQuery(selector, query, ancChQuery);
  9027. selector.compoundCount++;
  9028. // we're now populating the descendant query with expressions that follow
  9029. return descendant;
  9030. } else if (selector.currentSubject === query) {
  9031. // compound split query
  9032. var compound = newQuery();
  9033. var left = selector[selector.length - 1];
  9034. var right = newQuery();
  9035. var subject = newQuery();
  9036. var _descendant = newQuery();
  9037. var _ancestor = newQuery();
  9038. // set up the root compound q
  9039. compound.checks.push({
  9040. type: Type.COMPOUND_SPLIT,
  9041. left: left,
  9042. right: right,
  9043. subject: subject
  9044. });
  9045. // populate the subject and replace the q at the old spot (within left) with TRUE
  9046. subject.checks = query.checks; // take the checks from the left
  9047. query.checks = [{
  9048. type: Type.TRUE
  9049. }]; // checks under left refs the subject implicitly
  9050. // set up the right q
  9051. _ancestor.checks.push({
  9052. type: Type.TRUE
  9053. }); // ancestor implicitly refs the subject
  9054. right.checks.push({
  9055. type: Type.ANCESTOR,
  9056. // type is swapped on right side queries
  9057. ancestor: _ancestor,
  9058. descendant: _descendant // empty for now
  9059. });
  9060. replaceLastQuery(selector, left, compound);
  9061. // update the ref since we moved things around for `query`
  9062. selector.currentSubject = subject;
  9063. selector.compoundCount++;
  9064. return _descendant; // now populating the right side's descendant
  9065. } else {
  9066. // ancestor query
  9067. // info for parent query
  9068. var _ancestor2 = newQuery();
  9069. var _descendant2 = newQuery();
  9070. var adQChecks = [{
  9071. type: Type.ANCESTOR,
  9072. ancestor: _ancestor2,
  9073. descendant: _descendant2
  9074. }];
  9075. // the parent-child query takes the place of the query previously being populated
  9076. _ancestor2.checks = query.checks; // the previous query contains the checks for the parent
  9077. query.checks = adQChecks; // pc query takes over
  9078. selector.compoundCount++;
  9079. return _descendant2; // we're now populating the child
  9080. }
  9081. }
  9082. }, {
  9083. name: 'subject',
  9084. modifier: true,
  9085. regex: tokens.subject,
  9086. populate: function populate(selector, query) {
  9087. if (selector.currentSubject != null && selector.currentSubject !== query) {
  9088. warn('Redefinition of subject in selector `' + selector.toString() + '`');
  9089. return false;
  9090. }
  9091. selector.currentSubject = query;
  9092. var topQ = selector[selector.length - 1];
  9093. var topChk = topQ.checks[0];
  9094. var topType = topChk == null ? null : topChk.type;
  9095. if (topType === Type.DIRECTED_EDGE) {
  9096. // directed edge with subject on the target
  9097. // change to target node check
  9098. topChk.type = Type.NODE_TARGET;
  9099. } else if (topType === Type.UNDIRECTED_EDGE) {
  9100. // undirected edge with subject on the second node
  9101. // change to neighbor check
  9102. topChk.type = Type.NODE_NEIGHBOR;
  9103. topChk.node = topChk.nodes[1]; // second node is subject
  9104. topChk.neighbor = topChk.nodes[0];
  9105. // clean up unused fields for new type
  9106. topChk.nodes = null;
  9107. }
  9108. }
  9109. }];
  9110. exprs.forEach(function (e) {
  9111. return e.regexObj = new RegExp('^' + e.regex);
  9112. });
  9113. /**
  9114. * Of all the expressions, find the first match in the remaining text.
  9115. * @param {string} remaining The remaining text to parse
  9116. * @returns The matched expression and the newly remaining text `{ expr, match, name, remaining }`
  9117. */
  9118. var consumeExpr = function consumeExpr(remaining) {
  9119. var expr;
  9120. var match;
  9121. var name;
  9122. for (var j = 0; j < exprs.length; j++) {
  9123. var e = exprs[j];
  9124. var n = e.name;
  9125. var m = remaining.match(e.regexObj);
  9126. if (m != null) {
  9127. match = m;
  9128. expr = e;
  9129. name = n;
  9130. var consumed = m[0];
  9131. remaining = remaining.substring(consumed.length);
  9132. break; // we've consumed one expr, so we can return now
  9133. }
  9134. }
  9135. return {
  9136. expr: expr,
  9137. match: match,
  9138. name: name,
  9139. remaining: remaining
  9140. };
  9141. };
  9142. /**
  9143. * Consume all the leading whitespace
  9144. * @param {string} remaining The text to consume
  9145. * @returns The text with the leading whitespace removed
  9146. */
  9147. var consumeWhitespace = function consumeWhitespace(remaining) {
  9148. var match = remaining.match(/^\s+/);
  9149. if (match) {
  9150. var consumed = match[0];
  9151. remaining = remaining.substring(consumed.length);
  9152. }
  9153. return remaining;
  9154. };
  9155. /**
  9156. * Parse the string and store the parsed representation in the Selector.
  9157. * @param {string} selector The selector string
  9158. * @returns `true` if the selector was successfully parsed, `false` otherwise
  9159. */
  9160. var parse = function parse(selector) {
  9161. var self = this;
  9162. var remaining = self.inputText = selector;
  9163. var currentQuery = self[0] = newQuery();
  9164. self.length = 1;
  9165. remaining = consumeWhitespace(remaining); // get rid of leading whitespace
  9166. for (;;) {
  9167. var exprInfo = consumeExpr(remaining);
  9168. if (exprInfo.expr == null) {
  9169. warn('The selector `' + selector + '`is invalid');
  9170. return false;
  9171. } else {
  9172. var args = exprInfo.match.slice(1);
  9173. // let the token populate the selector object in currentQuery
  9174. var ret = exprInfo.expr.populate(self, currentQuery, args);
  9175. if (ret === false) {
  9176. return false; // exit if population failed
  9177. } else if (ret != null) {
  9178. currentQuery = ret; // change the current query to be filled if the expr specifies
  9179. }
  9180. }
  9181. remaining = exprInfo.remaining;
  9182. // we're done when there's nothing left to parse
  9183. if (remaining.match(/^\s*$/)) {
  9184. break;
  9185. }
  9186. }
  9187. var lastQ = self[self.length - 1];
  9188. if (self.currentSubject != null) {
  9189. lastQ.subject = self.currentSubject;
  9190. }
  9191. lastQ.edgeCount = self.edgeCount;
  9192. lastQ.compoundCount = self.compoundCount;
  9193. for (var i = 0; i < self.length; i++) {
  9194. var q = self[i];
  9195. // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations
  9196. if (q.compoundCount > 0 && q.edgeCount > 0) {
  9197. warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector');
  9198. return false;
  9199. }
  9200. if (q.edgeCount > 1) {
  9201. warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors');
  9202. return false;
  9203. } else if (q.edgeCount === 1) {
  9204. 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.');
  9205. }
  9206. }
  9207. return true; // success
  9208. };
  9209. /**
  9210. * Get the selector represented as a string. This value uses default formatting,
  9211. * so things like spacing may differ from the input text passed to the constructor.
  9212. * @returns {string} The selector string
  9213. */
  9214. var toString = function toString() {
  9215. if (this.toStringCache != null) {
  9216. return this.toStringCache;
  9217. }
  9218. var clean = function clean(obj) {
  9219. if (obj == null) {
  9220. return '';
  9221. } else {
  9222. return obj;
  9223. }
  9224. };
  9225. var cleanVal = function cleanVal(val) {
  9226. if (string(val)) {
  9227. return '"' + val + '"';
  9228. } else {
  9229. return clean(val);
  9230. }
  9231. };
  9232. var space = function space(val) {
  9233. return ' ' + val + ' ';
  9234. };
  9235. var checkToString = function checkToString(check, subject) {
  9236. var type = check.type,
  9237. value = check.value;
  9238. switch (type) {
  9239. case Type.GROUP:
  9240. {
  9241. var group = clean(value);
  9242. return group.substring(0, group.length - 1);
  9243. }
  9244. case Type.DATA_COMPARE:
  9245. {
  9246. var field = check.field,
  9247. operator = check.operator;
  9248. return '[' + field + space(clean(operator)) + cleanVal(value) + ']';
  9249. }
  9250. case Type.DATA_BOOL:
  9251. {
  9252. var _operator = check.operator,
  9253. _field = check.field;
  9254. return '[' + clean(_operator) + _field + ']';
  9255. }
  9256. case Type.DATA_EXIST:
  9257. {
  9258. var _field2 = check.field;
  9259. return '[' + _field2 + ']';
  9260. }
  9261. case Type.META_COMPARE:
  9262. {
  9263. var _operator2 = check.operator,
  9264. _field3 = check.field;
  9265. return '[[' + _field3 + space(clean(_operator2)) + cleanVal(value) + ']]';
  9266. }
  9267. case Type.STATE:
  9268. {
  9269. return value;
  9270. }
  9271. case Type.ID:
  9272. {
  9273. return '#' + value;
  9274. }
  9275. case Type.CLASS:
  9276. {
  9277. return '.' + value;
  9278. }
  9279. case Type.PARENT:
  9280. case Type.CHILD:
  9281. {
  9282. return queryToString(check.parent, subject) + space('>') + queryToString(check.child, subject);
  9283. }
  9284. case Type.ANCESTOR:
  9285. case Type.DESCENDANT:
  9286. {
  9287. return queryToString(check.ancestor, subject) + ' ' + queryToString(check.descendant, subject);
  9288. }
  9289. case Type.COMPOUND_SPLIT:
  9290. {
  9291. var lhs = queryToString(check.left, subject);
  9292. var sub = queryToString(check.subject, subject);
  9293. var rhs = queryToString(check.right, subject);
  9294. return lhs + (lhs.length > 0 ? ' ' : '') + sub + rhs;
  9295. }
  9296. case Type.TRUE:
  9297. {
  9298. return '';
  9299. }
  9300. }
  9301. };
  9302. var queryToString = function queryToString(query, subject) {
  9303. return query.checks.reduce(function (str, chk, i) {
  9304. return str + (subject === query && i === 0 ? '$' : '') + checkToString(chk, subject);
  9305. }, '');
  9306. };
  9307. var str = '';
  9308. for (var i = 0; i < this.length; i++) {
  9309. var query = this[i];
  9310. str += queryToString(query, query.subject);
  9311. if (this.length > 1 && i < this.length - 1) {
  9312. str += ', ';
  9313. }
  9314. }
  9315. this.toStringCache = str;
  9316. return str;
  9317. };
  9318. var parse$1 = {
  9319. parse: parse,
  9320. toString: toString
  9321. };
  9322. var valCmp = function valCmp(fieldVal, operator, value) {
  9323. var matches;
  9324. var isFieldStr = string(fieldVal);
  9325. var isFieldNum = number$1(fieldVal);
  9326. var isValStr = string(value);
  9327. var fieldStr, valStr;
  9328. var caseInsensitive = false;
  9329. var notExpr = false;
  9330. var isIneqCmp = false;
  9331. if (operator.indexOf('!') >= 0) {
  9332. operator = operator.replace('!', '');
  9333. notExpr = true;
  9334. }
  9335. if (operator.indexOf('@') >= 0) {
  9336. operator = operator.replace('@', '');
  9337. caseInsensitive = true;
  9338. }
  9339. if (isFieldStr || isValStr || caseInsensitive) {
  9340. fieldStr = !isFieldStr && !isFieldNum ? '' : '' + fieldVal;
  9341. valStr = '' + value;
  9342. }
  9343. // if we're doing a case insensitive comparison, then we're using a STRING comparison
  9344. // even if we're comparing numbers
  9345. if (caseInsensitive) {
  9346. fieldVal = fieldStr = fieldStr.toLowerCase();
  9347. value = valStr = valStr.toLowerCase();
  9348. }
  9349. switch (operator) {
  9350. case '*=':
  9351. matches = fieldStr.indexOf(valStr) >= 0;
  9352. break;
  9353. case '$=':
  9354. matches = fieldStr.indexOf(valStr, fieldStr.length - valStr.length) >= 0;
  9355. break;
  9356. case '^=':
  9357. matches = fieldStr.indexOf(valStr) === 0;
  9358. break;
  9359. case '=':
  9360. matches = fieldVal === value;
  9361. break;
  9362. case '>':
  9363. isIneqCmp = true;
  9364. matches = fieldVal > value;
  9365. break;
  9366. case '>=':
  9367. isIneqCmp = true;
  9368. matches = fieldVal >= value;
  9369. break;
  9370. case '<':
  9371. isIneqCmp = true;
  9372. matches = fieldVal < value;
  9373. break;
  9374. case '<=':
  9375. isIneqCmp = true;
  9376. matches = fieldVal <= value;
  9377. break;
  9378. default:
  9379. matches = false;
  9380. break;
  9381. }
  9382. // apply the not op, but null vals for inequalities should always stay non-matching
  9383. if (notExpr && (fieldVal != null || !isIneqCmp)) {
  9384. matches = !matches;
  9385. }
  9386. return matches;
  9387. };
  9388. var boolCmp = function boolCmp(fieldVal, operator) {
  9389. switch (operator) {
  9390. case '?':
  9391. return fieldVal ? true : false;
  9392. case '!':
  9393. return fieldVal ? false : true;
  9394. case '^':
  9395. return fieldVal === undefined;
  9396. }
  9397. };
  9398. var existCmp = function existCmp(fieldVal) {
  9399. return fieldVal !== undefined;
  9400. };
  9401. var data$1 = function data(ele, field) {
  9402. return ele.data(field);
  9403. };
  9404. var meta = function meta(ele, field) {
  9405. return ele[field]();
  9406. };
  9407. /** A lookup of `match(check, ele)` functions by `Type` int */
  9408. var match = [];
  9409. /**
  9410. * Returns whether the query matches for the element
  9411. * @param query The `{ type, value, ... }` query object
  9412. * @param ele The element to compare against
  9413. */
  9414. var matches$1 = function matches(query, ele) {
  9415. return query.checks.every(function (chk) {
  9416. return match[chk.type](chk, ele);
  9417. });
  9418. };
  9419. match[Type.GROUP] = function (check, ele) {
  9420. var group = check.value;
  9421. return group === '*' || group === ele.group();
  9422. };
  9423. match[Type.STATE] = function (check, ele) {
  9424. var stateSelector = check.value;
  9425. return stateSelectorMatches(stateSelector, ele);
  9426. };
  9427. match[Type.ID] = function (check, ele) {
  9428. var id = check.value;
  9429. return ele.id() === id;
  9430. };
  9431. match[Type.CLASS] = function (check, ele) {
  9432. var cls = check.value;
  9433. return ele.hasClass(cls);
  9434. };
  9435. match[Type.META_COMPARE] = function (check, ele) {
  9436. var field = check.field,
  9437. operator = check.operator,
  9438. value = check.value;
  9439. return valCmp(meta(ele, field), operator, value);
  9440. };
  9441. match[Type.DATA_COMPARE] = function (check, ele) {
  9442. var field = check.field,
  9443. operator = check.operator,
  9444. value = check.value;
  9445. return valCmp(data$1(ele, field), operator, value);
  9446. };
  9447. match[Type.DATA_BOOL] = function (check, ele) {
  9448. var field = check.field,
  9449. operator = check.operator;
  9450. return boolCmp(data$1(ele, field), operator);
  9451. };
  9452. match[Type.DATA_EXIST] = function (check, ele) {
  9453. var field = check.field;
  9454. check.operator;
  9455. return existCmp(data$1(ele, field));
  9456. };
  9457. match[Type.UNDIRECTED_EDGE] = function (check, ele) {
  9458. var qA = check.nodes[0];
  9459. var qB = check.nodes[1];
  9460. var src = ele.source();
  9461. var tgt = ele.target();
  9462. return matches$1(qA, src) && matches$1(qB, tgt) || matches$1(qB, src) && matches$1(qA, tgt);
  9463. };
  9464. match[Type.NODE_NEIGHBOR] = function (check, ele) {
  9465. return matches$1(check.node, ele) && ele.neighborhood().some(function (n) {
  9466. return n.isNode() && matches$1(check.neighbor, n);
  9467. });
  9468. };
  9469. match[Type.DIRECTED_EDGE] = function (check, ele) {
  9470. return matches$1(check.source, ele.source()) && matches$1(check.target, ele.target());
  9471. };
  9472. match[Type.NODE_SOURCE] = function (check, ele) {
  9473. return matches$1(check.source, ele) && ele.outgoers().some(function (n) {
  9474. return n.isNode() && matches$1(check.target, n);
  9475. });
  9476. };
  9477. match[Type.NODE_TARGET] = function (check, ele) {
  9478. return matches$1(check.target, ele) && ele.incomers().some(function (n) {
  9479. return n.isNode() && matches$1(check.source, n);
  9480. });
  9481. };
  9482. match[Type.CHILD] = function (check, ele) {
  9483. return matches$1(check.child, ele) && matches$1(check.parent, ele.parent());
  9484. };
  9485. match[Type.PARENT] = function (check, ele) {
  9486. return matches$1(check.parent, ele) && ele.children().some(function (c) {
  9487. return matches$1(check.child, c);
  9488. });
  9489. };
  9490. match[Type.DESCENDANT] = function (check, ele) {
  9491. return matches$1(check.descendant, ele) && ele.ancestors().some(function (a) {
  9492. return matches$1(check.ancestor, a);
  9493. });
  9494. };
  9495. match[Type.ANCESTOR] = function (check, ele) {
  9496. return matches$1(check.ancestor, ele) && ele.descendants().some(function (d) {
  9497. return matches$1(check.descendant, d);
  9498. });
  9499. };
  9500. match[Type.COMPOUND_SPLIT] = function (check, ele) {
  9501. return matches$1(check.subject, ele) && matches$1(check.left, ele) && matches$1(check.right, ele);
  9502. };
  9503. match[Type.TRUE] = function () {
  9504. return true;
  9505. };
  9506. match[Type.COLLECTION] = function (check, ele) {
  9507. var collection = check.value;
  9508. return collection.has(ele);
  9509. };
  9510. match[Type.FILTER] = function (check, ele) {
  9511. var filter = check.value;
  9512. return filter(ele);
  9513. };
  9514. // filter an existing collection
  9515. var filter = function filter(collection) {
  9516. var self = this;
  9517. // for 1 id #foo queries, just get the element
  9518. if (self.length === 1 && self[0].checks.length === 1 && self[0].checks[0].type === Type.ID) {
  9519. return collection.getElementById(self[0].checks[0].value).collection();
  9520. }
  9521. var selectorFunction = function selectorFunction(element) {
  9522. for (var j = 0; j < self.length; j++) {
  9523. var query = self[j];
  9524. if (matches$1(query, element)) {
  9525. return true;
  9526. }
  9527. }
  9528. return false;
  9529. };
  9530. if (self.text() == null) {
  9531. selectorFunction = function selectorFunction() {
  9532. return true;
  9533. };
  9534. }
  9535. return collection.filter(selectorFunction);
  9536. }; // filter
  9537. // does selector match a single element?
  9538. var matches = function matches(ele) {
  9539. var self = this;
  9540. for (var j = 0; j < self.length; j++) {
  9541. var query = self[j];
  9542. if (matches$1(query, ele)) {
  9543. return true;
  9544. }
  9545. }
  9546. return false;
  9547. }; // matches
  9548. var matching = {
  9549. matches: matches,
  9550. filter: filter
  9551. };
  9552. var Selector = function Selector(selector) {
  9553. this.inputText = selector;
  9554. this.currentSubject = null;
  9555. this.compoundCount = 0;
  9556. this.edgeCount = 0;
  9557. this.length = 0;
  9558. if (selector == null || string(selector) && selector.match(/^\s*$/)) ; else if (elementOrCollection(selector)) {
  9559. this.addQuery({
  9560. checks: [{
  9561. type: Type.COLLECTION,
  9562. value: selector.collection()
  9563. }]
  9564. });
  9565. } else if (fn$6(selector)) {
  9566. this.addQuery({
  9567. checks: [{
  9568. type: Type.FILTER,
  9569. value: selector
  9570. }]
  9571. });
  9572. } else if (string(selector)) {
  9573. if (!this.parse(selector)) {
  9574. this.invalid = true;
  9575. }
  9576. } else {
  9577. error('A selector must be created from a string; found ');
  9578. }
  9579. };
  9580. var selfn = Selector.prototype;
  9581. [parse$1, matching].forEach(function (p) {
  9582. return extend(selfn, p);
  9583. });
  9584. selfn.text = function () {
  9585. return this.inputText;
  9586. };
  9587. selfn.size = function () {
  9588. return this.length;
  9589. };
  9590. selfn.eq = function (i) {
  9591. return this[i];
  9592. };
  9593. selfn.sameText = function (otherSel) {
  9594. return !this.invalid && !otherSel.invalid && this.text() === otherSel.text();
  9595. };
  9596. selfn.addQuery = function (q) {
  9597. this[this.length++] = q;
  9598. };
  9599. selfn.selector = selfn.toString;
  9600. var elesfn$g = {
  9601. allAre: function allAre(selector) {
  9602. var selObj = new Selector(selector);
  9603. return this.every(function (ele) {
  9604. return selObj.matches(ele);
  9605. });
  9606. },
  9607. is: function is(selector) {
  9608. var selObj = new Selector(selector);
  9609. return this.some(function (ele) {
  9610. return selObj.matches(ele);
  9611. });
  9612. },
  9613. some: function some(fn, thisArg) {
  9614. for (var i = 0; i < this.length; i++) {
  9615. var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
  9616. if (ret) {
  9617. return true;
  9618. }
  9619. }
  9620. return false;
  9621. },
  9622. every: function every(fn, thisArg) {
  9623. for (var i = 0; i < this.length; i++) {
  9624. var ret = !thisArg ? fn(this[i], i, this) : fn.apply(thisArg, [this[i], i, this]);
  9625. if (!ret) {
  9626. return false;
  9627. }
  9628. }
  9629. return true;
  9630. },
  9631. same: function same(collection) {
  9632. // cheap collection ref check
  9633. if (this === collection) {
  9634. return true;
  9635. }
  9636. collection = this.cy().collection(collection);
  9637. var thisLength = this.length;
  9638. var collectionLength = collection.length;
  9639. // cheap length check
  9640. if (thisLength !== collectionLength) {
  9641. return false;
  9642. }
  9643. // cheap element ref check
  9644. if (thisLength === 1) {
  9645. return this[0] === collection[0];
  9646. }
  9647. return this.every(function (ele) {
  9648. return collection.hasElementWithId(ele.id());
  9649. });
  9650. },
  9651. anySame: function anySame(collection) {
  9652. collection = this.cy().collection(collection);
  9653. return this.some(function (ele) {
  9654. return collection.hasElementWithId(ele.id());
  9655. });
  9656. },
  9657. allAreNeighbors: function allAreNeighbors(collection) {
  9658. collection = this.cy().collection(collection);
  9659. var nhood = this.neighborhood();
  9660. return collection.every(function (ele) {
  9661. return nhood.hasElementWithId(ele.id());
  9662. });
  9663. },
  9664. contains: function contains(collection) {
  9665. collection = this.cy().collection(collection);
  9666. var self = this;
  9667. return collection.every(function (ele) {
  9668. return self.hasElementWithId(ele.id());
  9669. });
  9670. }
  9671. };
  9672. elesfn$g.allAreNeighbours = elesfn$g.allAreNeighbors;
  9673. elesfn$g.has = elesfn$g.contains;
  9674. elesfn$g.equal = elesfn$g.equals = elesfn$g.same;
  9675. var cache = function cache(fn, name) {
  9676. return function traversalCache(arg1, arg2, arg3, arg4) {
  9677. var selectorOrEles = arg1;
  9678. var eles = this;
  9679. var key;
  9680. if (selectorOrEles == null) {
  9681. key = '';
  9682. } else if (elementOrCollection(selectorOrEles) && selectorOrEles.length === 1) {
  9683. key = selectorOrEles.id();
  9684. }
  9685. if (eles.length === 1 && key) {
  9686. var _p = eles[0]._private;
  9687. var tch = _p.traversalCache = _p.traversalCache || {};
  9688. var ch = tch[name] = tch[name] || [];
  9689. var hash = hashString(key);
  9690. var cacheHit = ch[hash];
  9691. if (cacheHit) {
  9692. return cacheHit;
  9693. } else {
  9694. return ch[hash] = fn.call(eles, arg1, arg2, arg3, arg4);
  9695. }
  9696. } else {
  9697. return fn.call(eles, arg1, arg2, arg3, arg4);
  9698. }
  9699. };
  9700. };
  9701. var elesfn$f = {
  9702. parent: function parent(selector) {
  9703. var parents = [];
  9704. // optimisation for single ele call
  9705. if (this.length === 1) {
  9706. var parent = this[0]._private.parent;
  9707. if (parent) {
  9708. return parent;
  9709. }
  9710. }
  9711. for (var i = 0; i < this.length; i++) {
  9712. var ele = this[i];
  9713. var _parent = ele._private.parent;
  9714. if (_parent) {
  9715. parents.push(_parent);
  9716. }
  9717. }
  9718. return this.spawn(parents, true).filter(selector);
  9719. },
  9720. parents: function parents(selector) {
  9721. var parents = [];
  9722. var eles = this.parent();
  9723. while (eles.nonempty()) {
  9724. for (var i = 0; i < eles.length; i++) {
  9725. var ele = eles[i];
  9726. parents.push(ele);
  9727. }
  9728. eles = eles.parent();
  9729. }
  9730. return this.spawn(parents, true).filter(selector);
  9731. },
  9732. commonAncestors: function commonAncestors(selector) {
  9733. var ancestors;
  9734. for (var i = 0; i < this.length; i++) {
  9735. var ele = this[i];
  9736. var parents = ele.parents();
  9737. ancestors = ancestors || parents;
  9738. ancestors = ancestors.intersect(parents); // current list must be common with current ele parents set
  9739. }
  9740. return ancestors.filter(selector);
  9741. },
  9742. orphans: function orphans(selector) {
  9743. return this.stdFilter(function (ele) {
  9744. return ele.isOrphan();
  9745. }).filter(selector);
  9746. },
  9747. nonorphans: function nonorphans(selector) {
  9748. return this.stdFilter(function (ele) {
  9749. return ele.isChild();
  9750. }).filter(selector);
  9751. },
  9752. children: cache(function (selector) {
  9753. var children = [];
  9754. for (var i = 0; i < this.length; i++) {
  9755. var ele = this[i];
  9756. var eleChildren = ele._private.children;
  9757. for (var j = 0; j < eleChildren.length; j++) {
  9758. children.push(eleChildren[j]);
  9759. }
  9760. }
  9761. return this.spawn(children, true).filter(selector);
  9762. }, 'children'),
  9763. siblings: function siblings(selector) {
  9764. return this.parent().children().not(this).filter(selector);
  9765. },
  9766. isParent: function isParent() {
  9767. var ele = this[0];
  9768. if (ele) {
  9769. return ele.isNode() && ele._private.children.length !== 0;
  9770. }
  9771. },
  9772. isChildless: function isChildless() {
  9773. var ele = this[0];
  9774. if (ele) {
  9775. return ele.isNode() && ele._private.children.length === 0;
  9776. }
  9777. },
  9778. isChild: function isChild() {
  9779. var ele = this[0];
  9780. if (ele) {
  9781. return ele.isNode() && ele._private.parent != null;
  9782. }
  9783. },
  9784. isOrphan: function isOrphan() {
  9785. var ele = this[0];
  9786. if (ele) {
  9787. return ele.isNode() && ele._private.parent == null;
  9788. }
  9789. },
  9790. descendants: function descendants(selector) {
  9791. var elements = [];
  9792. function add(eles) {
  9793. for (var i = 0; i < eles.length; i++) {
  9794. var ele = eles[i];
  9795. elements.push(ele);
  9796. if (ele.children().nonempty()) {
  9797. add(ele.children());
  9798. }
  9799. }
  9800. }
  9801. add(this.children());
  9802. return this.spawn(elements, true).filter(selector);
  9803. }
  9804. };
  9805. function forEachCompound(eles, fn, includeSelf, recursiveStep) {
  9806. var q = [];
  9807. var did = new Set$1();
  9808. var cy = eles.cy();
  9809. var hasCompounds = cy.hasCompoundNodes();
  9810. for (var i = 0; i < eles.length; i++) {
  9811. var ele = eles[i];
  9812. if (includeSelf) {
  9813. q.push(ele);
  9814. } else if (hasCompounds) {
  9815. recursiveStep(q, did, ele);
  9816. }
  9817. }
  9818. while (q.length > 0) {
  9819. var _ele = q.shift();
  9820. fn(_ele);
  9821. did.add(_ele.id());
  9822. if (hasCompounds) {
  9823. recursiveStep(q, did, _ele);
  9824. }
  9825. }
  9826. return eles;
  9827. }
  9828. function addChildren(q, did, ele) {
  9829. if (ele.isParent()) {
  9830. var children = ele._private.children;
  9831. for (var i = 0; i < children.length; i++) {
  9832. var child = children[i];
  9833. if (!did.has(child.id())) {
  9834. q.push(child);
  9835. }
  9836. }
  9837. }
  9838. }
  9839. // very efficient version of eles.add( eles.descendants() ).forEach()
  9840. // for internal use
  9841. elesfn$f.forEachDown = function (fn) {
  9842. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9843. return forEachCompound(this, fn, includeSelf, addChildren);
  9844. };
  9845. function addParent(q, did, ele) {
  9846. if (ele.isChild()) {
  9847. var parent = ele._private.parent;
  9848. if (!did.has(parent.id())) {
  9849. q.push(parent);
  9850. }
  9851. }
  9852. }
  9853. elesfn$f.forEachUp = function (fn) {
  9854. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9855. return forEachCompound(this, fn, includeSelf, addParent);
  9856. };
  9857. function addParentAndChildren(q, did, ele) {
  9858. addParent(q, did, ele);
  9859. addChildren(q, did, ele);
  9860. }
  9861. elesfn$f.forEachUpAndDown = function (fn) {
  9862. var includeSelf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  9863. return forEachCompound(this, fn, includeSelf, addParentAndChildren);
  9864. };
  9865. // aliases
  9866. elesfn$f.ancestors = elesfn$f.parents;
  9867. var fn$5, elesfn$e;
  9868. fn$5 = elesfn$e = {
  9869. data: define.data({
  9870. field: 'data',
  9871. bindingEvent: 'data',
  9872. allowBinding: true,
  9873. allowSetting: true,
  9874. settingEvent: 'data',
  9875. settingTriggersEvent: true,
  9876. triggerFnName: 'trigger',
  9877. allowGetting: true,
  9878. immutableKeys: {
  9879. 'id': true,
  9880. 'source': true,
  9881. 'target': true,
  9882. 'parent': true
  9883. },
  9884. updateStyle: true
  9885. }),
  9886. removeData: define.removeData({
  9887. field: 'data',
  9888. event: 'data',
  9889. triggerFnName: 'trigger',
  9890. triggerEvent: true,
  9891. immutableKeys: {
  9892. 'id': true,
  9893. 'source': true,
  9894. 'target': true,
  9895. 'parent': true
  9896. },
  9897. updateStyle: true
  9898. }),
  9899. scratch: define.data({
  9900. field: 'scratch',
  9901. bindingEvent: 'scratch',
  9902. allowBinding: true,
  9903. allowSetting: true,
  9904. settingEvent: 'scratch',
  9905. settingTriggersEvent: true,
  9906. triggerFnName: 'trigger',
  9907. allowGetting: true,
  9908. updateStyle: true
  9909. }),
  9910. removeScratch: define.removeData({
  9911. field: 'scratch',
  9912. event: 'scratch',
  9913. triggerFnName: 'trigger',
  9914. triggerEvent: true,
  9915. updateStyle: true
  9916. }),
  9917. rscratch: define.data({
  9918. field: 'rscratch',
  9919. allowBinding: false,
  9920. allowSetting: true,
  9921. settingTriggersEvent: false,
  9922. allowGetting: true
  9923. }),
  9924. removeRscratch: define.removeData({
  9925. field: 'rscratch',
  9926. triggerEvent: false
  9927. }),
  9928. id: function id() {
  9929. var ele = this[0];
  9930. if (ele) {
  9931. return ele._private.data.id;
  9932. }
  9933. }
  9934. };
  9935. // aliases
  9936. fn$5.attr = fn$5.data;
  9937. fn$5.removeAttr = fn$5.removeData;
  9938. var data = elesfn$e;
  9939. var elesfn$d = {};
  9940. function defineDegreeFunction(callback) {
  9941. return function (includeLoops) {
  9942. var self = this;
  9943. if (includeLoops === undefined) {
  9944. includeLoops = true;
  9945. }
  9946. if (self.length === 0) {
  9947. return;
  9948. }
  9949. if (self.isNode() && !self.removed()) {
  9950. var degree = 0;
  9951. var node = self[0];
  9952. var connectedEdges = node._private.edges;
  9953. for (var i = 0; i < connectedEdges.length; i++) {
  9954. var edge = connectedEdges[i];
  9955. if (!includeLoops && edge.isLoop()) {
  9956. continue;
  9957. }
  9958. degree += callback(node, edge);
  9959. }
  9960. return degree;
  9961. } else {
  9962. return;
  9963. }
  9964. };
  9965. }
  9966. extend(elesfn$d, {
  9967. degree: defineDegreeFunction(function (node, edge) {
  9968. if (edge.source().same(edge.target())) {
  9969. return 2;
  9970. } else {
  9971. return 1;
  9972. }
  9973. }),
  9974. indegree: defineDegreeFunction(function (node, edge) {
  9975. if (edge.target().same(node)) {
  9976. return 1;
  9977. } else {
  9978. return 0;
  9979. }
  9980. }),
  9981. outdegree: defineDegreeFunction(function (node, edge) {
  9982. if (edge.source().same(node)) {
  9983. return 1;
  9984. } else {
  9985. return 0;
  9986. }
  9987. })
  9988. });
  9989. function defineDegreeBoundsFunction(degreeFn, callback) {
  9990. return function (includeLoops) {
  9991. var ret;
  9992. var nodes = this.nodes();
  9993. for (var i = 0; i < nodes.length; i++) {
  9994. var ele = nodes[i];
  9995. var degree = ele[degreeFn](includeLoops);
  9996. if (degree !== undefined && (ret === undefined || callback(degree, ret))) {
  9997. ret = degree;
  9998. }
  9999. }
  10000. return ret;
  10001. };
  10002. }
  10003. extend(elesfn$d, {
  10004. minDegree: defineDegreeBoundsFunction('degree', function (degree, min) {
  10005. return degree < min;
  10006. }),
  10007. maxDegree: defineDegreeBoundsFunction('degree', function (degree, max) {
  10008. return degree > max;
  10009. }),
  10010. minIndegree: defineDegreeBoundsFunction('indegree', function (degree, min) {
  10011. return degree < min;
  10012. }),
  10013. maxIndegree: defineDegreeBoundsFunction('indegree', function (degree, max) {
  10014. return degree > max;
  10015. }),
  10016. minOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, min) {
  10017. return degree < min;
  10018. }),
  10019. maxOutdegree: defineDegreeBoundsFunction('outdegree', function (degree, max) {
  10020. return degree > max;
  10021. })
  10022. });
  10023. extend(elesfn$d, {
  10024. totalDegree: function totalDegree(includeLoops) {
  10025. var total = 0;
  10026. var nodes = this.nodes();
  10027. for (var i = 0; i < nodes.length; i++) {
  10028. total += nodes[i].degree(includeLoops);
  10029. }
  10030. return total;
  10031. }
  10032. });
  10033. var fn$4, elesfn$c;
  10034. var beforePositionSet = function beforePositionSet(eles, newPos, silent) {
  10035. for (var i = 0; i < eles.length; i++) {
  10036. var ele = eles[i];
  10037. if (!ele.locked()) {
  10038. var oldPos = ele._private.position;
  10039. var delta = {
  10040. x: newPos.x != null ? newPos.x - oldPos.x : 0,
  10041. y: newPos.y != null ? newPos.y - oldPos.y : 0
  10042. };
  10043. if (ele.isParent() && !(delta.x === 0 && delta.y === 0)) {
  10044. ele.children().shift(delta, silent);
  10045. }
  10046. ele.dirtyBoundingBoxCache();
  10047. }
  10048. }
  10049. };
  10050. var positionDef = {
  10051. field: 'position',
  10052. bindingEvent: 'position',
  10053. allowBinding: true,
  10054. allowSetting: true,
  10055. settingEvent: 'position',
  10056. settingTriggersEvent: true,
  10057. triggerFnName: 'emitAndNotify',
  10058. allowGetting: true,
  10059. validKeys: ['x', 'y'],
  10060. beforeGet: function beforeGet(ele) {
  10061. ele.updateCompoundBounds();
  10062. },
  10063. beforeSet: function beforeSet(eles, newPos) {
  10064. beforePositionSet(eles, newPos, false);
  10065. },
  10066. onSet: function onSet(eles) {
  10067. eles.dirtyCompoundBoundsCache();
  10068. },
  10069. canSet: function canSet(ele) {
  10070. return !ele.locked();
  10071. }
  10072. };
  10073. fn$4 = elesfn$c = {
  10074. position: define.data(positionDef),
  10075. // position but no notification to renderer
  10076. silentPosition: define.data(extend({}, positionDef, {
  10077. allowBinding: false,
  10078. allowSetting: true,
  10079. settingTriggersEvent: false,
  10080. allowGetting: false,
  10081. beforeSet: function beforeSet(eles, newPos) {
  10082. beforePositionSet(eles, newPos, true);
  10083. },
  10084. onSet: function onSet(eles) {
  10085. eles.dirtyCompoundBoundsCache();
  10086. }
  10087. })),
  10088. positions: function positions(pos, silent) {
  10089. if (plainObject(pos)) {
  10090. if (silent) {
  10091. this.silentPosition(pos);
  10092. } else {
  10093. this.position(pos);
  10094. }
  10095. } else if (fn$6(pos)) {
  10096. var _fn = pos;
  10097. var cy = this.cy();
  10098. cy.startBatch();
  10099. for (var i = 0; i < this.length; i++) {
  10100. var ele = this[i];
  10101. var _pos = undefined;
  10102. if (_pos = _fn(ele, i)) {
  10103. if (silent) {
  10104. ele.silentPosition(_pos);
  10105. } else {
  10106. ele.position(_pos);
  10107. }
  10108. }
  10109. }
  10110. cy.endBatch();
  10111. }
  10112. return this; // chaining
  10113. },
  10114. silentPositions: function silentPositions(pos) {
  10115. return this.positions(pos, true);
  10116. },
  10117. shift: function shift(dim, val, silent) {
  10118. var delta;
  10119. if (plainObject(dim)) {
  10120. delta = {
  10121. x: number$1(dim.x) ? dim.x : 0,
  10122. y: number$1(dim.y) ? dim.y : 0
  10123. };
  10124. silent = val;
  10125. } else if (string(dim) && number$1(val)) {
  10126. delta = {
  10127. x: 0,
  10128. y: 0
  10129. };
  10130. delta[dim] = val;
  10131. }
  10132. if (delta != null) {
  10133. var cy = this.cy();
  10134. cy.startBatch();
  10135. for (var i = 0; i < this.length; i++) {
  10136. var ele = this[i];
  10137. // exclude any node that is a descendant of the calling collection
  10138. if (cy.hasCompoundNodes() && ele.isChild() && ele.ancestors().anySame(this)) {
  10139. continue;
  10140. }
  10141. var pos = ele.position();
  10142. var newPos = {
  10143. x: pos.x + delta.x,
  10144. y: pos.y + delta.y
  10145. };
  10146. if (silent) {
  10147. ele.silentPosition(newPos);
  10148. } else {
  10149. ele.position(newPos);
  10150. }
  10151. }
  10152. cy.endBatch();
  10153. }
  10154. return this;
  10155. },
  10156. silentShift: function silentShift(dim, val) {
  10157. if (plainObject(dim)) {
  10158. this.shift(dim, true);
  10159. } else if (string(dim) && number$1(val)) {
  10160. this.shift(dim, val, true);
  10161. }
  10162. return this;
  10163. },
  10164. // get/set the rendered (i.e. on screen) positon of the element
  10165. renderedPosition: function renderedPosition(dim, val) {
  10166. var ele = this[0];
  10167. var cy = this.cy();
  10168. var zoom = cy.zoom();
  10169. var pan = cy.pan();
  10170. var rpos = plainObject(dim) ? dim : undefined;
  10171. var setting = rpos !== undefined || val !== undefined && string(dim);
  10172. if (ele && ele.isNode()) {
  10173. // must have an element and must be a node to return position
  10174. if (setting) {
  10175. for (var i = 0; i < this.length; i++) {
  10176. var _ele = this[i];
  10177. if (val !== undefined) {
  10178. // set one dimension
  10179. _ele.position(dim, (val - pan[dim]) / zoom);
  10180. } else if (rpos !== undefined) {
  10181. // set whole position
  10182. _ele.position(renderedToModelPosition(rpos, zoom, pan));
  10183. }
  10184. }
  10185. } else {
  10186. // getting
  10187. var pos = ele.position();
  10188. rpos = modelToRenderedPosition$1(pos, zoom, pan);
  10189. if (dim === undefined) {
  10190. // then return the whole rendered position
  10191. return rpos;
  10192. } else {
  10193. // then return the specified dimension
  10194. return rpos[dim];
  10195. }
  10196. }
  10197. } else if (!setting) {
  10198. return undefined; // for empty collection case
  10199. }
  10200. return this; // chaining
  10201. },
  10202. // get/set the position relative to the parent
  10203. relativePosition: function relativePosition(dim, val) {
  10204. var ele = this[0];
  10205. var cy = this.cy();
  10206. var ppos = plainObject(dim) ? dim : undefined;
  10207. var setting = ppos !== undefined || val !== undefined && string(dim);
  10208. var hasCompoundNodes = cy.hasCompoundNodes();
  10209. if (ele && ele.isNode()) {
  10210. // must have an element and must be a node to return position
  10211. if (setting) {
  10212. for (var i = 0; i < this.length; i++) {
  10213. var _ele2 = this[i];
  10214. var parent = hasCompoundNodes ? _ele2.parent() : null;
  10215. var hasParent = parent && parent.length > 0;
  10216. var relativeToParent = hasParent;
  10217. if (hasParent) {
  10218. parent = parent[0];
  10219. }
  10220. var origin = relativeToParent ? parent.position() : {
  10221. x: 0,
  10222. y: 0
  10223. };
  10224. if (val !== undefined) {
  10225. // set one dimension
  10226. _ele2.position(dim, val + origin[dim]);
  10227. } else if (ppos !== undefined) {
  10228. // set whole position
  10229. _ele2.position({
  10230. x: ppos.x + origin.x,
  10231. y: ppos.y + origin.y
  10232. });
  10233. }
  10234. }
  10235. } else {
  10236. // getting
  10237. var pos = ele.position();
  10238. var _parent = hasCompoundNodes ? ele.parent() : null;
  10239. var _hasParent = _parent && _parent.length > 0;
  10240. var _relativeToParent = _hasParent;
  10241. if (_hasParent) {
  10242. _parent = _parent[0];
  10243. }
  10244. var _origin = _relativeToParent ? _parent.position() : {
  10245. x: 0,
  10246. y: 0
  10247. };
  10248. ppos = {
  10249. x: pos.x - _origin.x,
  10250. y: pos.y - _origin.y
  10251. };
  10252. if (dim === undefined) {
  10253. // then return the whole rendered position
  10254. return ppos;
  10255. } else {
  10256. // then return the specified dimension
  10257. return ppos[dim];
  10258. }
  10259. }
  10260. } else if (!setting) {
  10261. return undefined; // for empty collection case
  10262. }
  10263. return this; // chaining
  10264. }
  10265. };
  10266. // aliases
  10267. fn$4.modelPosition = fn$4.point = fn$4.position;
  10268. fn$4.modelPositions = fn$4.points = fn$4.positions;
  10269. fn$4.renderedPoint = fn$4.renderedPosition;
  10270. fn$4.relativePoint = fn$4.relativePosition;
  10271. var position = elesfn$c;
  10272. var fn$3, elesfn$b;
  10273. fn$3 = elesfn$b = {};
  10274. elesfn$b.renderedBoundingBox = function (options) {
  10275. var bb = this.boundingBox(options);
  10276. var cy = this.cy();
  10277. var zoom = cy.zoom();
  10278. var pan = cy.pan();
  10279. var x1 = bb.x1 * zoom + pan.x;
  10280. var x2 = bb.x2 * zoom + pan.x;
  10281. var y1 = bb.y1 * zoom + pan.y;
  10282. var y2 = bb.y2 * zoom + pan.y;
  10283. return {
  10284. x1: x1,
  10285. x2: x2,
  10286. y1: y1,
  10287. y2: y2,
  10288. w: x2 - x1,
  10289. h: y2 - y1
  10290. };
  10291. };
  10292. elesfn$b.dirtyCompoundBoundsCache = function () {
  10293. var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  10294. var cy = this.cy();
  10295. if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
  10296. return this;
  10297. }
  10298. this.forEachUp(function (ele) {
  10299. if (ele.isParent()) {
  10300. var _p = ele._private;
  10301. _p.compoundBoundsClean = false;
  10302. _p.bbCache = null;
  10303. if (!silent) {
  10304. ele.emitAndNotify('bounds');
  10305. }
  10306. }
  10307. });
  10308. return this;
  10309. };
  10310. elesfn$b.updateCompoundBounds = function () {
  10311. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  10312. var cy = this.cy();
  10313. // not possible to do on non-compound graphs or with the style disabled
  10314. if (!cy.styleEnabled() || !cy.hasCompoundNodes()) {
  10315. return this;
  10316. }
  10317. // save cycles when batching -- but bounds will be stale (or not exist yet)
  10318. if (!force && cy.batching()) {
  10319. return this;
  10320. }
  10321. function update(parent) {
  10322. if (!parent.isParent()) {
  10323. return;
  10324. }
  10325. var _p = parent._private;
  10326. var children = parent.children();
  10327. var includeLabels = parent.pstyle('compound-sizing-wrt-labels').value === 'include';
  10328. var min = {
  10329. width: {
  10330. val: parent.pstyle('min-width').pfValue,
  10331. left: parent.pstyle('min-width-bias-left'),
  10332. right: parent.pstyle('min-width-bias-right')
  10333. },
  10334. height: {
  10335. val: parent.pstyle('min-height').pfValue,
  10336. top: parent.pstyle('min-height-bias-top'),
  10337. bottom: parent.pstyle('min-height-bias-bottom')
  10338. }
  10339. };
  10340. var bb = children.boundingBox({
  10341. includeLabels: includeLabels,
  10342. includeOverlays: false,
  10343. // updating the compound bounds happens outside of the regular
  10344. // cache cycle (i.e. before fired events)
  10345. useCache: false
  10346. });
  10347. var pos = _p.position;
  10348. // if children take up zero area then keep position and fall back on stylesheet w/h
  10349. if (bb.w === 0 || bb.h === 0) {
  10350. bb = {
  10351. w: parent.pstyle('width').pfValue,
  10352. h: parent.pstyle('height').pfValue
  10353. };
  10354. bb.x1 = pos.x - bb.w / 2;
  10355. bb.x2 = pos.x + bb.w / 2;
  10356. bb.y1 = pos.y - bb.h / 2;
  10357. bb.y2 = pos.y + bb.h / 2;
  10358. }
  10359. function computeBiasValues(propDiff, propBias, propBiasComplement) {
  10360. var biasDiff = 0;
  10361. var biasComplementDiff = 0;
  10362. var biasTotal = propBias + propBiasComplement;
  10363. if (propDiff > 0 && biasTotal > 0) {
  10364. biasDiff = propBias / biasTotal * propDiff;
  10365. biasComplementDiff = propBiasComplement / biasTotal * propDiff;
  10366. }
  10367. return {
  10368. biasDiff: biasDiff,
  10369. biasComplementDiff: biasComplementDiff
  10370. };
  10371. }
  10372. function computePaddingValues(width, height, paddingObject, relativeTo) {
  10373. // Assuming percentage is number from 0 to 1
  10374. if (paddingObject.units === '%') {
  10375. switch (relativeTo) {
  10376. case 'width':
  10377. return width > 0 ? paddingObject.pfValue * width : 0;
  10378. case 'height':
  10379. return height > 0 ? paddingObject.pfValue * height : 0;
  10380. case 'average':
  10381. return width > 0 && height > 0 ? paddingObject.pfValue * (width + height) / 2 : 0;
  10382. case 'min':
  10383. return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * height : paddingObject.pfValue * width : 0;
  10384. case 'max':
  10385. return width > 0 && height > 0 ? width > height ? paddingObject.pfValue * width : paddingObject.pfValue * height : 0;
  10386. default:
  10387. return 0;
  10388. }
  10389. } else if (paddingObject.units === 'px') {
  10390. return paddingObject.pfValue;
  10391. } else {
  10392. return 0;
  10393. }
  10394. }
  10395. var leftVal = min.width.left.value;
  10396. if (min.width.left.units === 'px' && min.width.val > 0) {
  10397. leftVal = leftVal * 100 / min.width.val;
  10398. }
  10399. var rightVal = min.width.right.value;
  10400. if (min.width.right.units === 'px' && min.width.val > 0) {
  10401. rightVal = rightVal * 100 / min.width.val;
  10402. }
  10403. var topVal = min.height.top.value;
  10404. if (min.height.top.units === 'px' && min.height.val > 0) {
  10405. topVal = topVal * 100 / min.height.val;
  10406. }
  10407. var bottomVal = min.height.bottom.value;
  10408. if (min.height.bottom.units === 'px' && min.height.val > 0) {
  10409. bottomVal = bottomVal * 100 / min.height.val;
  10410. }
  10411. var widthBiasDiffs = computeBiasValues(min.width.val - bb.w, leftVal, rightVal);
  10412. var diffLeft = widthBiasDiffs.biasDiff;
  10413. var diffRight = widthBiasDiffs.biasComplementDiff;
  10414. var heightBiasDiffs = computeBiasValues(min.height.val - bb.h, topVal, bottomVal);
  10415. var diffTop = heightBiasDiffs.biasDiff;
  10416. var diffBottom = heightBiasDiffs.biasComplementDiff;
  10417. _p.autoPadding = computePaddingValues(bb.w, bb.h, parent.pstyle('padding'), parent.pstyle('padding-relative-to').value);
  10418. _p.autoWidth = Math.max(bb.w, min.width.val);
  10419. pos.x = (-diffLeft + bb.x1 + bb.x2 + diffRight) / 2;
  10420. _p.autoHeight = Math.max(bb.h, min.height.val);
  10421. pos.y = (-diffTop + bb.y1 + bb.y2 + diffBottom) / 2;
  10422. }
  10423. for (var i = 0; i < this.length; i++) {
  10424. var ele = this[i];
  10425. var _p = ele._private;
  10426. if (!_p.compoundBoundsClean || force) {
  10427. update(ele);
  10428. if (!cy.batching()) {
  10429. _p.compoundBoundsClean = true;
  10430. }
  10431. }
  10432. }
  10433. return this;
  10434. };
  10435. var noninf = function noninf(x) {
  10436. if (x === Infinity || x === -Infinity) {
  10437. return 0;
  10438. }
  10439. return x;
  10440. };
  10441. var updateBounds = function updateBounds(b, x1, y1, x2, y2) {
  10442. // don't update with zero area boxes
  10443. if (x2 - x1 === 0 || y2 - y1 === 0) {
  10444. return;
  10445. }
  10446. // don't update with null dim
  10447. if (x1 == null || y1 == null || x2 == null || y2 == null) {
  10448. return;
  10449. }
  10450. b.x1 = x1 < b.x1 ? x1 : b.x1;
  10451. b.x2 = x2 > b.x2 ? x2 : b.x2;
  10452. b.y1 = y1 < b.y1 ? y1 : b.y1;
  10453. b.y2 = y2 > b.y2 ? y2 : b.y2;
  10454. b.w = b.x2 - b.x1;
  10455. b.h = b.y2 - b.y1;
  10456. };
  10457. var updateBoundsFromBox = function updateBoundsFromBox(b, b2) {
  10458. if (b2 == null) {
  10459. return b;
  10460. }
  10461. return updateBounds(b, b2.x1, b2.y1, b2.x2, b2.y2);
  10462. };
  10463. var prefixedProperty = function prefixedProperty(obj, field, prefix) {
  10464. return getPrefixedProperty(obj, field, prefix);
  10465. };
  10466. var updateBoundsFromArrow = function updateBoundsFromArrow(bounds, ele, prefix) {
  10467. if (ele.cy().headless()) {
  10468. return;
  10469. }
  10470. var _p = ele._private;
  10471. var rstyle = _p.rstyle;
  10472. var halfArW = rstyle.arrowWidth / 2;
  10473. var arrowType = ele.pstyle(prefix + '-arrow-shape').value;
  10474. var x;
  10475. var y;
  10476. if (arrowType !== 'none') {
  10477. if (prefix === 'source') {
  10478. x = rstyle.srcX;
  10479. y = rstyle.srcY;
  10480. } else if (prefix === 'target') {
  10481. x = rstyle.tgtX;
  10482. y = rstyle.tgtY;
  10483. } else {
  10484. x = rstyle.midX;
  10485. y = rstyle.midY;
  10486. }
  10487. // always store the individual arrow bounds
  10488. var bbs = _p.arrowBounds = _p.arrowBounds || {};
  10489. var bb = bbs[prefix] = bbs[prefix] || {};
  10490. bb.x1 = x - halfArW;
  10491. bb.y1 = y - halfArW;
  10492. bb.x2 = x + halfArW;
  10493. bb.y2 = y + halfArW;
  10494. bb.w = bb.x2 - bb.x1;
  10495. bb.h = bb.y2 - bb.y1;
  10496. expandBoundingBox(bb, 1);
  10497. updateBounds(bounds, bb.x1, bb.y1, bb.x2, bb.y2);
  10498. }
  10499. };
  10500. var updateBoundsFromLabel = function updateBoundsFromLabel(bounds, ele, prefix) {
  10501. if (ele.cy().headless()) {
  10502. return;
  10503. }
  10504. var prefixDash;
  10505. if (prefix) {
  10506. prefixDash = prefix + '-';
  10507. } else {
  10508. prefixDash = '';
  10509. }
  10510. var _p = ele._private;
  10511. var rstyle = _p.rstyle;
  10512. var label = ele.pstyle(prefixDash + 'label').strValue;
  10513. if (label) {
  10514. var halign = ele.pstyle('text-halign');
  10515. var valign = ele.pstyle('text-valign');
  10516. var labelWidth = prefixedProperty(rstyle, 'labelWidth', prefix);
  10517. var labelHeight = prefixedProperty(rstyle, 'labelHeight', prefix);
  10518. var labelX = prefixedProperty(rstyle, 'labelX', prefix);
  10519. var labelY = prefixedProperty(rstyle, 'labelY', prefix);
  10520. var marginX = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  10521. var marginY = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  10522. var isEdge = ele.isEdge();
  10523. var rotation = ele.pstyle(prefixDash + 'text-rotation');
  10524. var outlineWidth = ele.pstyle('text-outline-width').pfValue;
  10525. var borderWidth = ele.pstyle('text-border-width').pfValue;
  10526. var halfBorderWidth = borderWidth / 2;
  10527. var padding = ele.pstyle('text-background-padding').pfValue;
  10528. var marginOfError = 2; // expand to work around browser dimension inaccuracies
  10529. var lh = labelHeight;
  10530. var lw = labelWidth;
  10531. var lw_2 = lw / 2;
  10532. var lh_2 = lh / 2;
  10533. var lx1, lx2, ly1, ly2;
  10534. if (isEdge) {
  10535. lx1 = labelX - lw_2;
  10536. lx2 = labelX + lw_2;
  10537. ly1 = labelY - lh_2;
  10538. ly2 = labelY + lh_2;
  10539. } else {
  10540. switch (halign.value) {
  10541. case 'left':
  10542. lx1 = labelX - lw;
  10543. lx2 = labelX;
  10544. break;
  10545. case 'center':
  10546. lx1 = labelX - lw_2;
  10547. lx2 = labelX + lw_2;
  10548. break;
  10549. case 'right':
  10550. lx1 = labelX;
  10551. lx2 = labelX + lw;
  10552. break;
  10553. }
  10554. switch (valign.value) {
  10555. case 'top':
  10556. ly1 = labelY - lh;
  10557. ly2 = labelY;
  10558. break;
  10559. case 'center':
  10560. ly1 = labelY - lh_2;
  10561. ly2 = labelY + lh_2;
  10562. break;
  10563. case 'bottom':
  10564. ly1 = labelY;
  10565. ly2 = labelY + lh;
  10566. break;
  10567. }
  10568. }
  10569. // shift by margin and expand by outline and border
  10570. var leftPad = marginX - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
  10571. var rightPad = marginX + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
  10572. var topPad = marginY - Math.max(outlineWidth, halfBorderWidth) - padding - marginOfError;
  10573. var botPad = marginY + Math.max(outlineWidth, halfBorderWidth) + padding + marginOfError;
  10574. lx1 += leftPad;
  10575. lx2 += rightPad;
  10576. ly1 += topPad;
  10577. ly2 += botPad;
  10578. // always store the unrotated label bounds separately
  10579. var bbPrefix = prefix || 'main';
  10580. var bbs = _p.labelBounds;
  10581. var bb = bbs[bbPrefix] = bbs[bbPrefix] || {};
  10582. bb.x1 = lx1;
  10583. bb.y1 = ly1;
  10584. bb.x2 = lx2;
  10585. bb.y2 = ly2;
  10586. bb.w = lx2 - lx1;
  10587. bb.h = ly2 - ly1;
  10588. bb.leftPad = leftPad;
  10589. bb.rightPad = rightPad;
  10590. bb.topPad = topPad;
  10591. bb.botPad = botPad;
  10592. var isAutorotate = isEdge && rotation.strValue === 'autorotate';
  10593. var isPfValue = rotation.pfValue != null && rotation.pfValue !== 0;
  10594. if (isAutorotate || isPfValue) {
  10595. var theta = isAutorotate ? prefixedProperty(_p.rstyle, 'labelAngle', prefix) : rotation.pfValue;
  10596. var cos = Math.cos(theta);
  10597. var sin = Math.sin(theta);
  10598. // rotation point (default value for center-center)
  10599. var xo = (lx1 + lx2) / 2;
  10600. var yo = (ly1 + ly2) / 2;
  10601. if (!isEdge) {
  10602. switch (halign.value) {
  10603. case 'left':
  10604. xo = lx2;
  10605. break;
  10606. case 'right':
  10607. xo = lx1;
  10608. break;
  10609. }
  10610. switch (valign.value) {
  10611. case 'top':
  10612. yo = ly2;
  10613. break;
  10614. case 'bottom':
  10615. yo = ly1;
  10616. break;
  10617. }
  10618. }
  10619. var rotate = function rotate(x, y) {
  10620. x = x - xo;
  10621. y = y - yo;
  10622. return {
  10623. x: x * cos - y * sin + xo,
  10624. y: x * sin + y * cos + yo
  10625. };
  10626. };
  10627. var px1y1 = rotate(lx1, ly1);
  10628. var px1y2 = rotate(lx1, ly2);
  10629. var px2y1 = rotate(lx2, ly1);
  10630. var px2y2 = rotate(lx2, ly2);
  10631. lx1 = Math.min(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
  10632. lx2 = Math.max(px1y1.x, px1y2.x, px2y1.x, px2y2.x);
  10633. ly1 = Math.min(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
  10634. ly2 = Math.max(px1y1.y, px1y2.y, px2y1.y, px2y2.y);
  10635. }
  10636. var bbPrefixRot = bbPrefix + 'Rot';
  10637. var bbRot = bbs[bbPrefixRot] = bbs[bbPrefixRot] || {};
  10638. bbRot.x1 = lx1;
  10639. bbRot.y1 = ly1;
  10640. bbRot.x2 = lx2;
  10641. bbRot.y2 = ly2;
  10642. bbRot.w = lx2 - lx1;
  10643. bbRot.h = ly2 - ly1;
  10644. updateBounds(bounds, lx1, ly1, lx2, ly2);
  10645. updateBounds(_p.labelBounds.all, lx1, ly1, lx2, ly2);
  10646. }
  10647. return bounds;
  10648. };
  10649. var updateBoundsFromOutline = function updateBoundsFromOutline(bounds, ele) {
  10650. if (ele.cy().headless()) {
  10651. return;
  10652. }
  10653. var outlineOpacity = ele.pstyle('outline-opacity').value;
  10654. var outlineWidth = ele.pstyle('outline-width').value;
  10655. var outlineOffset = ele.pstyle('outline-offset').value;
  10656. var expansion = outlineWidth + outlineOffset;
  10657. updateBoundsFromMiter(bounds, ele, outlineOpacity, expansion, 'outside', expansion / 2);
  10658. };
  10659. var updateBoundsFromMiter = function updateBoundsFromMiter(bounds, ele, opacity, expansionSize, expansionPosition, useFallbackValue) {
  10660. if (opacity === 0 || expansionSize <= 0 || expansionPosition === 'inside') {
  10661. return;
  10662. }
  10663. var cy = ele.cy();
  10664. var r = cy.renderer();
  10665. var rshape = r.nodeShapes[r.getNodeShape(ele)];
  10666. if (!rshape) {
  10667. return;
  10668. }
  10669. var _ele$position = ele.position(),
  10670. x = _ele$position.x,
  10671. y = _ele$position.y;
  10672. var w = ele.width();
  10673. var h = ele.height();
  10674. if (rshape.hasMiterBounds) {
  10675. if (expansionPosition === 'center') {
  10676. expansionSize /= 2;
  10677. }
  10678. var mbb = rshape.miterBounds(x, y, w, h, expansionSize);
  10679. updateBoundsFromBox(bounds, mbb);
  10680. } else if (useFallbackValue != null && useFallbackValue > 0) {
  10681. expandBoundingBoxSides(bounds, [useFallbackValue, useFallbackValue, useFallbackValue, useFallbackValue]);
  10682. }
  10683. };
  10684. var updateBoundsFromMiterBorder = function updateBoundsFromMiterBorder(bounds, ele) {
  10685. if (ele.cy().headless()) {
  10686. return;
  10687. }
  10688. var borderOpacity = ele.pstyle('border-opacity').value;
  10689. var borderWidth = ele.pstyle('border-width').pfValue;
  10690. var borderPosition = ele.pstyle('border-position').value;
  10691. updateBoundsFromMiter(bounds, ele, borderOpacity, borderWidth, borderPosition);
  10692. };
  10693. // get the bounding box of the elements (in raw model position)
  10694. var boundingBoxImpl = function boundingBoxImpl(ele, options) {
  10695. var cy = ele._private.cy;
  10696. var styleEnabled = cy.styleEnabled();
  10697. var headless = cy.headless();
  10698. var bounds = makeBoundingBox();
  10699. var _p = ele._private;
  10700. var isNode = ele.isNode();
  10701. var isEdge = ele.isEdge();
  10702. var ex1, ex2, ey1, ey2; // extrema of body / lines
  10703. var x, y; // node pos
  10704. var rstyle = _p.rstyle;
  10705. var manualExpansion = isNode && styleEnabled ? ele.pstyle('bounds-expansion').pfValue : [0];
  10706. // must use `display` prop only, as reading `compound.width()` causes recursion
  10707. // (other factors like width values will be considered later in this function anyway)
  10708. var isDisplayed = function isDisplayed(ele) {
  10709. return ele.pstyle('display').value !== 'none';
  10710. };
  10711. var displayed = !styleEnabled || isDisplayed(ele)
  10712. // must take into account connected nodes b/c of implicit edge hiding on display:none node
  10713. && (!isEdge || isDisplayed(ele.source()) && isDisplayed(ele.target()));
  10714. if (displayed) {
  10715. // displayed suffices, since we will find zero area eles anyway
  10716. var overlayOpacity = 0;
  10717. var overlayPadding = 0;
  10718. if (styleEnabled && options.includeOverlays) {
  10719. overlayOpacity = ele.pstyle('overlay-opacity').value;
  10720. if (overlayOpacity !== 0) {
  10721. overlayPadding = ele.pstyle('overlay-padding').value;
  10722. }
  10723. }
  10724. var underlayOpacity = 0;
  10725. var underlayPadding = 0;
  10726. if (styleEnabled && options.includeUnderlays) {
  10727. underlayOpacity = ele.pstyle('underlay-opacity').value;
  10728. if (underlayOpacity !== 0) {
  10729. underlayPadding = ele.pstyle('underlay-padding').value;
  10730. }
  10731. }
  10732. var padding = Math.max(overlayPadding, underlayPadding);
  10733. var w = 0;
  10734. var wHalf = 0;
  10735. if (styleEnabled) {
  10736. w = ele.pstyle('width').pfValue;
  10737. wHalf = w / 2;
  10738. }
  10739. if (isNode && options.includeNodes) {
  10740. var pos = ele.position();
  10741. x = pos.x;
  10742. y = pos.y;
  10743. var _w = ele.outerWidth();
  10744. var halfW = _w / 2;
  10745. var h = ele.outerHeight();
  10746. var halfH = h / 2;
  10747. // handle node dimensions
  10748. /////////////////////////
  10749. ex1 = x - halfW;
  10750. ex2 = x + halfW;
  10751. ey1 = y - halfH;
  10752. ey2 = y + halfH;
  10753. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10754. if (styleEnabled) {
  10755. updateBoundsFromOutline(bounds, ele);
  10756. }
  10757. if (styleEnabled && options.includeOutlines && !headless) {
  10758. updateBoundsFromOutline(bounds, ele);
  10759. }
  10760. if (styleEnabled) {
  10761. updateBoundsFromMiterBorder(bounds, ele);
  10762. }
  10763. } else if (isEdge && options.includeEdges) {
  10764. if (styleEnabled && !headless) {
  10765. var curveStyle = ele.pstyle('curve-style').strValue;
  10766. // handle edge dimensions (rough box estimate)
  10767. //////////////////////////////////////////////
  10768. ex1 = Math.min(rstyle.srcX, rstyle.midX, rstyle.tgtX);
  10769. ex2 = Math.max(rstyle.srcX, rstyle.midX, rstyle.tgtX);
  10770. ey1 = Math.min(rstyle.srcY, rstyle.midY, rstyle.tgtY);
  10771. ey2 = Math.max(rstyle.srcY, rstyle.midY, rstyle.tgtY);
  10772. // take into account edge width
  10773. ex1 -= wHalf;
  10774. ex2 += wHalf;
  10775. ey1 -= wHalf;
  10776. ey2 += wHalf;
  10777. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10778. // precise edges
  10779. ////////////////
  10780. if (curveStyle === 'haystack') {
  10781. var hpts = rstyle.haystackPts;
  10782. if (hpts && hpts.length === 2) {
  10783. ex1 = hpts[0].x;
  10784. ey1 = hpts[0].y;
  10785. ex2 = hpts[1].x;
  10786. ey2 = hpts[1].y;
  10787. if (ex1 > ex2) {
  10788. var temp = ex1;
  10789. ex1 = ex2;
  10790. ex2 = temp;
  10791. }
  10792. if (ey1 > ey2) {
  10793. var _temp = ey1;
  10794. ey1 = ey2;
  10795. ey2 = _temp;
  10796. }
  10797. updateBounds(bounds, ex1 - wHalf, ey1 - wHalf, ex2 + wHalf, ey2 + wHalf);
  10798. }
  10799. } else if (curveStyle === 'bezier' || curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || endsWith(curveStyle, 'taxi')) {
  10800. var pts;
  10801. switch (curveStyle) {
  10802. case 'bezier':
  10803. case 'unbundled-bezier':
  10804. pts = rstyle.bezierPts;
  10805. break;
  10806. case 'segments':
  10807. case 'taxi':
  10808. case 'round-segments':
  10809. case 'round-taxi':
  10810. pts = rstyle.linePts;
  10811. break;
  10812. }
  10813. if (pts != null) {
  10814. for (var j = 0; j < pts.length; j++) {
  10815. var pt = pts[j];
  10816. ex1 = pt.x - wHalf;
  10817. ex2 = pt.x + wHalf;
  10818. ey1 = pt.y - wHalf;
  10819. ey2 = pt.y + wHalf;
  10820. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10821. }
  10822. }
  10823. } // bezier-like or segment-like edge
  10824. } else {
  10825. // headless or style disabled
  10826. // fallback on source and target positions
  10827. //////////////////////////////////////////
  10828. var n1 = ele.source();
  10829. var n1pos = n1.position();
  10830. var n2 = ele.target();
  10831. var n2pos = n2.position();
  10832. ex1 = n1pos.x;
  10833. ex2 = n2pos.x;
  10834. ey1 = n1pos.y;
  10835. ey2 = n2pos.y;
  10836. if (ex1 > ex2) {
  10837. var _temp2 = ex1;
  10838. ex1 = ex2;
  10839. ex2 = _temp2;
  10840. }
  10841. if (ey1 > ey2) {
  10842. var _temp3 = ey1;
  10843. ey1 = ey2;
  10844. ey2 = _temp3;
  10845. }
  10846. // take into account edge width
  10847. ex1 -= wHalf;
  10848. ex2 += wHalf;
  10849. ey1 -= wHalf;
  10850. ey2 += wHalf;
  10851. updateBounds(bounds, ex1, ey1, ex2, ey2);
  10852. } // headless or style disabled
  10853. } // edges
  10854. // handle edge arrow size
  10855. /////////////////////////
  10856. if (styleEnabled && options.includeEdges && isEdge) {
  10857. updateBoundsFromArrow(bounds, ele, 'mid-source');
  10858. updateBoundsFromArrow(bounds, ele, 'mid-target');
  10859. updateBoundsFromArrow(bounds, ele, 'source');
  10860. updateBoundsFromArrow(bounds, ele, 'target');
  10861. }
  10862. // ghost
  10863. ////////
  10864. if (styleEnabled) {
  10865. var ghost = ele.pstyle('ghost').value === 'yes';
  10866. if (ghost) {
  10867. var gx = ele.pstyle('ghost-offset-x').pfValue;
  10868. var gy = ele.pstyle('ghost-offset-y').pfValue;
  10869. updateBounds(bounds, bounds.x1 + gx, bounds.y1 + gy, bounds.x2 + gx, bounds.y2 + gy);
  10870. }
  10871. }
  10872. // always store the body bounds separately from the labels
  10873. var bbBody = _p.bodyBounds = _p.bodyBounds || {};
  10874. assignBoundingBox(bbBody, bounds);
  10875. expandBoundingBoxSides(bbBody, manualExpansion);
  10876. expandBoundingBox(bbBody, 1); // expand to work around browser dimension inaccuracies
  10877. // overlay
  10878. //////////
  10879. if (styleEnabled) {
  10880. ex1 = bounds.x1;
  10881. ex2 = bounds.x2;
  10882. ey1 = bounds.y1;
  10883. ey2 = bounds.y2;
  10884. updateBounds(bounds, ex1 - padding, ey1 - padding, ex2 + padding, ey2 + padding);
  10885. }
  10886. // always store the body bounds separately from the labels
  10887. var bbOverlay = _p.overlayBounds = _p.overlayBounds || {};
  10888. assignBoundingBox(bbOverlay, bounds);
  10889. expandBoundingBoxSides(bbOverlay, manualExpansion);
  10890. expandBoundingBox(bbOverlay, 1); // expand to work around browser dimension inaccuracies
  10891. // handle label dimensions
  10892. //////////////////////////
  10893. var bbLabels = _p.labelBounds = _p.labelBounds || {};
  10894. if (bbLabels.all != null) {
  10895. clearBoundingBox(bbLabels.all);
  10896. } else {
  10897. bbLabels.all = makeBoundingBox();
  10898. }
  10899. if (styleEnabled && options.includeLabels) {
  10900. if (options.includeMainLabels) {
  10901. updateBoundsFromLabel(bounds, ele, null);
  10902. }
  10903. if (isEdge) {
  10904. if (options.includeSourceLabels) {
  10905. updateBoundsFromLabel(bounds, ele, 'source');
  10906. }
  10907. if (options.includeTargetLabels) {
  10908. updateBoundsFromLabel(bounds, ele, 'target');
  10909. }
  10910. }
  10911. } // style enabled for labels
  10912. } // if displayed
  10913. bounds.x1 = noninf(bounds.x1);
  10914. bounds.y1 = noninf(bounds.y1);
  10915. bounds.x2 = noninf(bounds.x2);
  10916. bounds.y2 = noninf(bounds.y2);
  10917. bounds.w = noninf(bounds.x2 - bounds.x1);
  10918. bounds.h = noninf(bounds.y2 - bounds.y1);
  10919. if (bounds.w > 0 && bounds.h > 0 && displayed) {
  10920. expandBoundingBoxSides(bounds, manualExpansion);
  10921. // expand bounds by 1 because antialiasing can increase the visual/effective size by 1 on all sides
  10922. expandBoundingBox(bounds, 1);
  10923. }
  10924. return bounds;
  10925. };
  10926. var getKey = function getKey(opts) {
  10927. var i = 0;
  10928. var tf = function tf(val) {
  10929. return (val ? 1 : 0) << i++;
  10930. };
  10931. var key = 0;
  10932. key += tf(opts.incudeNodes);
  10933. key += tf(opts.includeEdges);
  10934. key += tf(opts.includeLabels);
  10935. key += tf(opts.includeMainLabels);
  10936. key += tf(opts.includeSourceLabels);
  10937. key += tf(opts.includeTargetLabels);
  10938. key += tf(opts.includeOverlays);
  10939. key += tf(opts.includeOutlines);
  10940. return key;
  10941. };
  10942. var getBoundingBoxPosKey = function getBoundingBoxPosKey(ele) {
  10943. var r = function r(x) {
  10944. return Math.round(x);
  10945. };
  10946. if (ele.isEdge()) {
  10947. var p1 = ele.source().position();
  10948. var p2 = ele.target().position();
  10949. return hashIntsArray([r(p1.x), r(p1.y), r(p2.x), r(p2.y)]);
  10950. } else {
  10951. var p = ele.position();
  10952. return hashIntsArray([r(p.x), r(p.y)]);
  10953. }
  10954. };
  10955. var cachedBoundingBoxImpl = function cachedBoundingBoxImpl(ele, opts) {
  10956. var _p = ele._private;
  10957. var bb;
  10958. var isEdge = ele.isEdge();
  10959. var key = opts == null ? defBbOptsKey : getKey(opts);
  10960. var usingDefOpts = key === defBbOptsKey;
  10961. if (_p.bbCache == null) {
  10962. bb = boundingBoxImpl(ele, defBbOpts);
  10963. _p.bbCache = bb;
  10964. _p.bbCachePosKey = getBoundingBoxPosKey(ele);
  10965. } else {
  10966. bb = _p.bbCache;
  10967. }
  10968. // not using def opts => need to build up bb from combination of sub bbs
  10969. if (!usingDefOpts) {
  10970. var isNode = ele.isNode();
  10971. bb = makeBoundingBox();
  10972. if (opts.includeNodes && isNode || opts.includeEdges && !isNode) {
  10973. if (opts.includeOverlays) {
  10974. updateBoundsFromBox(bb, _p.overlayBounds);
  10975. } else {
  10976. updateBoundsFromBox(bb, _p.bodyBounds);
  10977. }
  10978. }
  10979. if (opts.includeLabels) {
  10980. if (opts.includeMainLabels && (!isEdge || opts.includeSourceLabels && opts.includeTargetLabels)) {
  10981. updateBoundsFromBox(bb, _p.labelBounds.all);
  10982. } else {
  10983. if (opts.includeMainLabels) {
  10984. updateBoundsFromBox(bb, _p.labelBounds.mainRot);
  10985. }
  10986. if (opts.includeSourceLabels) {
  10987. updateBoundsFromBox(bb, _p.labelBounds.sourceRot);
  10988. }
  10989. if (opts.includeTargetLabels) {
  10990. updateBoundsFromBox(bb, _p.labelBounds.targetRot);
  10991. }
  10992. }
  10993. }
  10994. bb.w = bb.x2 - bb.x1;
  10995. bb.h = bb.y2 - bb.y1;
  10996. }
  10997. return bb;
  10998. };
  10999. var defBbOpts = {
  11000. includeNodes: true,
  11001. includeEdges: true,
  11002. includeLabels: true,
  11003. includeMainLabels: true,
  11004. includeSourceLabels: true,
  11005. includeTargetLabels: true,
  11006. includeOverlays: true,
  11007. includeUnderlays: true,
  11008. includeOutlines: true,
  11009. useCache: true
  11010. };
  11011. var defBbOptsKey = getKey(defBbOpts);
  11012. var filledBbOpts = defaults$g(defBbOpts);
  11013. elesfn$b.boundingBox = function (options) {
  11014. var bounds;
  11015. var useCache = options === undefined || options.useCache === undefined || options.useCache === true;
  11016. var isDirty = memoize(function (ele) {
  11017. var _p = ele._private;
  11018. return _p.bbCache == null || _p.styleDirty || _p.bbCachePosKey !== getBoundingBoxPosKey(ele);
  11019. }, function (ele) {
  11020. return ele.id();
  11021. });
  11022. // the main usecase is ele.boundingBox() for a single element with no/def options
  11023. // specified s.t. the cache is used, so check for this case to make it faster by
  11024. // avoiding the overhead of the rest of the function
  11025. if (useCache && this.length === 1 && !isDirty(this[0])) {
  11026. if (options === undefined) {
  11027. options = defBbOpts;
  11028. } else {
  11029. options = filledBbOpts(options);
  11030. }
  11031. bounds = cachedBoundingBoxImpl(this[0], options);
  11032. } else {
  11033. bounds = makeBoundingBox();
  11034. options = options || defBbOpts;
  11035. var opts = filledBbOpts(options);
  11036. var eles = this;
  11037. var cy = eles.cy();
  11038. var styleEnabled = cy.styleEnabled();
  11039. // cache the isDirty state for all eles, edges first since they depend on node state
  11040. this.edges().forEach(isDirty);
  11041. this.nodes().forEach(isDirty);
  11042. if (styleEnabled) {
  11043. this.recalculateRenderedStyle(useCache);
  11044. }
  11045. this.updateCompoundBounds(!useCache);
  11046. for (var i = 0; i < eles.length; i++) {
  11047. var ele = eles[i];
  11048. if (isDirty(ele)) {
  11049. ele.dirtyBoundingBoxCache();
  11050. }
  11051. updateBoundsFromBox(bounds, cachedBoundingBoxImpl(ele, opts));
  11052. }
  11053. }
  11054. bounds.x1 = noninf(bounds.x1);
  11055. bounds.y1 = noninf(bounds.y1);
  11056. bounds.x2 = noninf(bounds.x2);
  11057. bounds.y2 = noninf(bounds.y2);
  11058. bounds.w = noninf(bounds.x2 - bounds.x1);
  11059. bounds.h = noninf(bounds.y2 - bounds.y1);
  11060. return bounds;
  11061. };
  11062. elesfn$b.dirtyBoundingBoxCache = function () {
  11063. for (var i = 0; i < this.length; i++) {
  11064. var _p = this[i]._private;
  11065. _p.bbCache = null;
  11066. _p.bbCachePosKey = null;
  11067. _p.bodyBounds = null;
  11068. _p.overlayBounds = null;
  11069. _p.labelBounds.all = null;
  11070. _p.labelBounds.source = null;
  11071. _p.labelBounds.target = null;
  11072. _p.labelBounds.main = null;
  11073. _p.labelBounds.sourceRot = null;
  11074. _p.labelBounds.targetRot = null;
  11075. _p.labelBounds.mainRot = null;
  11076. _p.arrowBounds.source = null;
  11077. _p.arrowBounds.target = null;
  11078. _p.arrowBounds['mid-source'] = null;
  11079. _p.arrowBounds['mid-target'] = null;
  11080. }
  11081. this.emitAndNotify('bounds');
  11082. return this;
  11083. };
  11084. // private helper to get bounding box for custom node positions
  11085. // - good for perf in certain cases but currently requires dirtying the rendered style
  11086. // - would be better to not modify the nodes but the nodes are read directly everywhere in the renderer...
  11087. // - try to use for only things like discrete layouts where the node position would change anyway
  11088. elesfn$b.boundingBoxAt = function (fn) {
  11089. var nodes = this.nodes();
  11090. var cy = this.cy();
  11091. var hasCompoundNodes = cy.hasCompoundNodes();
  11092. var parents = cy.collection();
  11093. if (hasCompoundNodes) {
  11094. parents = nodes.filter(function (node) {
  11095. return node.isParent();
  11096. });
  11097. nodes = nodes.not(parents);
  11098. }
  11099. if (plainObject(fn)) {
  11100. var obj = fn;
  11101. fn = function fn() {
  11102. return obj;
  11103. };
  11104. }
  11105. var storeOldPos = function storeOldPos(node, i) {
  11106. return node._private.bbAtOldPos = fn(node, i);
  11107. };
  11108. var getOldPos = function getOldPos(node) {
  11109. return node._private.bbAtOldPos;
  11110. };
  11111. cy.startBatch();
  11112. nodes.forEach(storeOldPos).silentPositions(fn);
  11113. if (hasCompoundNodes) {
  11114. parents.dirtyCompoundBoundsCache();
  11115. parents.dirtyBoundingBoxCache();
  11116. parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  11117. }
  11118. var bb = copyBoundingBox(this.boundingBox({
  11119. useCache: false
  11120. }));
  11121. nodes.silentPositions(getOldPos);
  11122. if (hasCompoundNodes) {
  11123. parents.dirtyCompoundBoundsCache();
  11124. parents.dirtyBoundingBoxCache();
  11125. parents.updateCompoundBounds(true); // force update b/c we're inside a batch cycle
  11126. }
  11127. cy.endBatch();
  11128. return bb;
  11129. };
  11130. fn$3.boundingbox = fn$3.bb = fn$3.boundingBox;
  11131. fn$3.renderedBoundingbox = fn$3.renderedBoundingBox;
  11132. var bounds = elesfn$b;
  11133. var fn$2, elesfn$a;
  11134. fn$2 = elesfn$a = {};
  11135. var defineDimFns = function defineDimFns(opts) {
  11136. opts.uppercaseName = capitalize(opts.name);
  11137. opts.autoName = 'auto' + opts.uppercaseName;
  11138. opts.labelName = 'label' + opts.uppercaseName;
  11139. opts.outerName = 'outer' + opts.uppercaseName;
  11140. opts.uppercaseOuterName = capitalize(opts.outerName);
  11141. fn$2[opts.name] = function dimImpl() {
  11142. var ele = this[0];
  11143. var _p = ele._private;
  11144. var cy = _p.cy;
  11145. var styleEnabled = cy._private.styleEnabled;
  11146. if (ele) {
  11147. if (styleEnabled) {
  11148. if (ele.isParent()) {
  11149. ele.updateCompoundBounds();
  11150. return _p[opts.autoName] || 0;
  11151. }
  11152. var d = ele.pstyle(opts.name);
  11153. switch (d.strValue) {
  11154. case 'label':
  11155. ele.recalculateRenderedStyle();
  11156. return _p.rstyle[opts.labelName] || 0;
  11157. default:
  11158. return d.pfValue;
  11159. }
  11160. } else {
  11161. return 1;
  11162. }
  11163. }
  11164. };
  11165. fn$2['outer' + opts.uppercaseName] = function outerDimImpl() {
  11166. var ele = this[0];
  11167. var _p = ele._private;
  11168. var cy = _p.cy;
  11169. var styleEnabled = cy._private.styleEnabled;
  11170. if (ele) {
  11171. if (styleEnabled) {
  11172. var dim = ele[opts.name]();
  11173. var borderPos = ele.pstyle('border-position').value;
  11174. var border;
  11175. if (borderPos === 'center') {
  11176. border = ele.pstyle('border-width').pfValue; // n.b. 1/2 each side
  11177. } else if (borderPos === 'outside') {
  11178. border = 2 * ele.pstyle('border-width').pfValue;
  11179. } else {
  11180. // 'inside'
  11181. border = 0;
  11182. }
  11183. var padding = 2 * ele.padding();
  11184. return dim + border + padding;
  11185. } else {
  11186. return 1;
  11187. }
  11188. }
  11189. };
  11190. fn$2['rendered' + opts.uppercaseName] = function renderedDimImpl() {
  11191. var ele = this[0];
  11192. if (ele) {
  11193. var d = ele[opts.name]();
  11194. return d * this.cy().zoom();
  11195. }
  11196. };
  11197. fn$2['rendered' + opts.uppercaseOuterName] = function renderedOuterDimImpl() {
  11198. var ele = this[0];
  11199. if (ele) {
  11200. var od = ele[opts.outerName]();
  11201. return od * this.cy().zoom();
  11202. }
  11203. };
  11204. };
  11205. defineDimFns({
  11206. name: 'width'
  11207. });
  11208. defineDimFns({
  11209. name: 'height'
  11210. });
  11211. elesfn$a.padding = function () {
  11212. var ele = this[0];
  11213. var _p = ele._private;
  11214. if (ele.isParent()) {
  11215. ele.updateCompoundBounds();
  11216. if (_p.autoPadding !== undefined) {
  11217. return _p.autoPadding;
  11218. } else {
  11219. return ele.pstyle('padding').pfValue;
  11220. }
  11221. } else {
  11222. return ele.pstyle('padding').pfValue;
  11223. }
  11224. };
  11225. elesfn$a.paddedHeight = function () {
  11226. var ele = this[0];
  11227. return ele.height() + 2 * ele.padding();
  11228. };
  11229. elesfn$a.paddedWidth = function () {
  11230. var ele = this[0];
  11231. return ele.width() + 2 * ele.padding();
  11232. };
  11233. var widthHeight = elesfn$a;
  11234. var ifEdge = function ifEdge(ele, getValue) {
  11235. if (ele.isEdge() && ele.takesUpSpace()) {
  11236. return getValue(ele);
  11237. }
  11238. };
  11239. var ifEdgeRenderedPosition = function ifEdgeRenderedPosition(ele, getPoint) {
  11240. if (ele.isEdge() && ele.takesUpSpace()) {
  11241. var cy = ele.cy();
  11242. return modelToRenderedPosition$1(getPoint(ele), cy.zoom(), cy.pan());
  11243. }
  11244. };
  11245. var ifEdgeRenderedPositions = function ifEdgeRenderedPositions(ele, getPoints) {
  11246. if (ele.isEdge() && ele.takesUpSpace()) {
  11247. var cy = ele.cy();
  11248. var pan = cy.pan();
  11249. var zoom = cy.zoom();
  11250. return getPoints(ele).map(function (p) {
  11251. return modelToRenderedPosition$1(p, zoom, pan);
  11252. });
  11253. }
  11254. };
  11255. var controlPoints = function controlPoints(ele) {
  11256. return ele.renderer().getControlPoints(ele);
  11257. };
  11258. var segmentPoints = function segmentPoints(ele) {
  11259. return ele.renderer().getSegmentPoints(ele);
  11260. };
  11261. var sourceEndpoint = function sourceEndpoint(ele) {
  11262. return ele.renderer().getSourceEndpoint(ele);
  11263. };
  11264. var targetEndpoint = function targetEndpoint(ele) {
  11265. return ele.renderer().getTargetEndpoint(ele);
  11266. };
  11267. var midpoint = function midpoint(ele) {
  11268. return ele.renderer().getEdgeMidpoint(ele);
  11269. };
  11270. var pts = {
  11271. controlPoints: {
  11272. get: controlPoints,
  11273. mult: true
  11274. },
  11275. segmentPoints: {
  11276. get: segmentPoints,
  11277. mult: true
  11278. },
  11279. sourceEndpoint: {
  11280. get: sourceEndpoint
  11281. },
  11282. targetEndpoint: {
  11283. get: targetEndpoint
  11284. },
  11285. midpoint: {
  11286. get: midpoint
  11287. }
  11288. };
  11289. var renderedName = function renderedName(name) {
  11290. return 'rendered' + name[0].toUpperCase() + name.substr(1);
  11291. };
  11292. var edgePoints = Object.keys(pts).reduce(function (obj, name) {
  11293. var spec = pts[name];
  11294. var rName = renderedName(name);
  11295. obj[name] = function () {
  11296. return ifEdge(this, spec.get);
  11297. };
  11298. if (spec.mult) {
  11299. obj[rName] = function () {
  11300. return ifEdgeRenderedPositions(this, spec.get);
  11301. };
  11302. } else {
  11303. obj[rName] = function () {
  11304. return ifEdgeRenderedPosition(this, spec.get);
  11305. };
  11306. }
  11307. return obj;
  11308. }, {});
  11309. var dimensions = extend({}, position, bounds, widthHeight, edgePoints);
  11310. /*!
  11311. Event object based on jQuery events, MIT license
  11312. https://jquery.org/license/
  11313. https://tldrlegal.com/license/mit-license
  11314. https://github.com/jquery/jquery/blob/master/src/event.js
  11315. */
  11316. var Event = function Event(src, props) {
  11317. this.recycle(src, props);
  11318. };
  11319. function returnFalse() {
  11320. return false;
  11321. }
  11322. function returnTrue() {
  11323. return true;
  11324. }
  11325. // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  11326. Event.prototype = {
  11327. instanceString: function instanceString() {
  11328. return 'event';
  11329. },
  11330. recycle: function recycle(src, props) {
  11331. this.isImmediatePropagationStopped = this.isPropagationStopped = this.isDefaultPrevented = returnFalse;
  11332. if (src != null && src.preventDefault) {
  11333. // Browser Event object
  11334. this.type = src.type;
  11335. // Events bubbling up the document may have been marked as prevented
  11336. // by a handler lower down the tree; reflect the correct value.
  11337. this.isDefaultPrevented = src.defaultPrevented ? returnTrue : returnFalse;
  11338. } else if (src != null && src.type) {
  11339. // Plain object containing all event details
  11340. props = src;
  11341. } else {
  11342. // Event string
  11343. this.type = src;
  11344. }
  11345. // Put explicitly provided properties onto the event object
  11346. if (props != null) {
  11347. // more efficient to manually copy fields we use
  11348. this.originalEvent = props.originalEvent;
  11349. this.type = props.type != null ? props.type : this.type;
  11350. this.cy = props.cy;
  11351. this.target = props.target;
  11352. this.position = props.position;
  11353. this.renderedPosition = props.renderedPosition;
  11354. this.namespace = props.namespace;
  11355. this.layout = props.layout;
  11356. }
  11357. if (this.cy != null && this.position != null && this.renderedPosition == null) {
  11358. // create a rendered position based on the passed position
  11359. var pos = this.position;
  11360. var zoom = this.cy.zoom();
  11361. var pan = this.cy.pan();
  11362. this.renderedPosition = {
  11363. x: pos.x * zoom + pan.x,
  11364. y: pos.y * zoom + pan.y
  11365. };
  11366. }
  11367. // Create a timestamp if incoming event doesn't have one
  11368. this.timeStamp = src && src.timeStamp || Date.now();
  11369. },
  11370. preventDefault: function preventDefault() {
  11371. this.isDefaultPrevented = returnTrue;
  11372. var e = this.originalEvent;
  11373. if (!e) {
  11374. return;
  11375. }
  11376. // if preventDefault exists run it on the original event
  11377. if (e.preventDefault) {
  11378. e.preventDefault();
  11379. }
  11380. },
  11381. stopPropagation: function stopPropagation() {
  11382. this.isPropagationStopped = returnTrue;
  11383. var e = this.originalEvent;
  11384. if (!e) {
  11385. return;
  11386. }
  11387. // if stopPropagation exists run it on the original event
  11388. if (e.stopPropagation) {
  11389. e.stopPropagation();
  11390. }
  11391. },
  11392. stopImmediatePropagation: function stopImmediatePropagation() {
  11393. this.isImmediatePropagationStopped = returnTrue;
  11394. this.stopPropagation();
  11395. },
  11396. isDefaultPrevented: returnFalse,
  11397. isPropagationStopped: returnFalse,
  11398. isImmediatePropagationStopped: returnFalse
  11399. };
  11400. var eventRegex = /^([^.]+)(\.(?:[^.]+))?$/; // regex for matching event strings (e.g. "click.namespace")
  11401. var universalNamespace = '.*'; // matches as if no namespace specified and prevents users from unbinding accidentally
  11402. var defaults$8 = {
  11403. qualifierCompare: function qualifierCompare(q1, q2) {
  11404. return q1 === q2;
  11405. },
  11406. eventMatches: function eventMatches(/*context, listener, eventObj*/
  11407. ) {
  11408. return true;
  11409. },
  11410. addEventFields: function addEventFields(/*context, evt*/
  11411. ) {},
  11412. callbackContext: function callbackContext(context /*, listener, eventObj*/) {
  11413. return context;
  11414. },
  11415. beforeEmit: function beforeEmit(/* context, listener, eventObj */
  11416. ) {},
  11417. afterEmit: function afterEmit(/* context, listener, eventObj */
  11418. ) {},
  11419. bubble: function bubble(/*context*/
  11420. ) {
  11421. return false;
  11422. },
  11423. parent: function parent(/*context*/
  11424. ) {
  11425. return null;
  11426. },
  11427. context: null
  11428. };
  11429. var defaultsKeys = Object.keys(defaults$8);
  11430. var emptyOpts = {};
  11431. function Emitter() {
  11432. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : emptyOpts;
  11433. var context = arguments.length > 1 ? arguments[1] : undefined;
  11434. // micro-optimisation vs Object.assign() -- reduces Element instantiation time
  11435. for (var i = 0; i < defaultsKeys.length; i++) {
  11436. var key = defaultsKeys[i];
  11437. this[key] = opts[key] || defaults$8[key];
  11438. }
  11439. this.context = context || this.context;
  11440. this.listeners = [];
  11441. this.emitting = 0;
  11442. }
  11443. var p = Emitter.prototype;
  11444. var forEachEvent = function forEachEvent(self, handler, events, qualifier, callback, conf, confOverrides) {
  11445. if (fn$6(qualifier)) {
  11446. callback = qualifier;
  11447. qualifier = null;
  11448. }
  11449. if (confOverrides) {
  11450. if (conf == null) {
  11451. conf = confOverrides;
  11452. } else {
  11453. conf = extend({}, conf, confOverrides);
  11454. }
  11455. }
  11456. var eventList = array(events) ? events : events.split(/\s+/);
  11457. for (var i = 0; i < eventList.length; i++) {
  11458. var evt = eventList[i];
  11459. if (emptyString(evt)) {
  11460. continue;
  11461. }
  11462. var match = evt.match(eventRegex); // type[.namespace]
  11463. if (match) {
  11464. var type = match[1];
  11465. var namespace = match[2] ? match[2] : null;
  11466. var ret = handler(self, evt, type, namespace, qualifier, callback, conf);
  11467. if (ret === false) {
  11468. break;
  11469. } // allow exiting early
  11470. }
  11471. }
  11472. };
  11473. var makeEventObj = function makeEventObj(self, obj) {
  11474. self.addEventFields(self.context, obj);
  11475. return new Event(obj.type, obj);
  11476. };
  11477. var forEachEventObj = function forEachEventObj(self, handler, events) {
  11478. if (event(events)) {
  11479. handler(self, events);
  11480. return;
  11481. } else if (plainObject(events)) {
  11482. handler(self, makeEventObj(self, events));
  11483. return;
  11484. }
  11485. var eventList = array(events) ? events : events.split(/\s+/);
  11486. for (var i = 0; i < eventList.length; i++) {
  11487. var evt = eventList[i];
  11488. if (emptyString(evt)) {
  11489. continue;
  11490. }
  11491. var match = evt.match(eventRegex); // type[.namespace]
  11492. if (match) {
  11493. var type = match[1];
  11494. var namespace = match[2] ? match[2] : null;
  11495. var eventObj = makeEventObj(self, {
  11496. type: type,
  11497. namespace: namespace,
  11498. target: self.context
  11499. });
  11500. handler(self, eventObj);
  11501. }
  11502. }
  11503. };
  11504. p.on = p.addListener = function (events, qualifier, callback, conf, confOverrides) {
  11505. forEachEvent(this, function (self, event, type, namespace, qualifier, callback, conf) {
  11506. if (fn$6(callback)) {
  11507. self.listeners.push({
  11508. event: event,
  11509. // full event string
  11510. callback: callback,
  11511. // callback to run
  11512. type: type,
  11513. // the event type (e.g. 'click')
  11514. namespace: namespace,
  11515. // the event namespace (e.g. ".foo")
  11516. qualifier: qualifier,
  11517. // a restriction on whether to match this emitter
  11518. conf: conf // additional configuration
  11519. });
  11520. }
  11521. }, events, qualifier, callback, conf, confOverrides);
  11522. return this;
  11523. };
  11524. p.one = function (events, qualifier, callback, conf) {
  11525. return this.on(events, qualifier, callback, conf, {
  11526. one: true
  11527. });
  11528. };
  11529. p.removeListener = p.off = function (events, qualifier, callback, conf) {
  11530. var _this = this;
  11531. if (this.emitting !== 0) {
  11532. this.listeners = copyArray(this.listeners);
  11533. }
  11534. var listeners = this.listeners;
  11535. var _loop = function _loop(i) {
  11536. var listener = listeners[i];
  11537. forEachEvent(_this, function (self, event, type, namespace, qualifier, callback /*, conf*/) {
  11538. if ((listener.type === type || events === '*') && (!namespace && listener.namespace !== '.*' || listener.namespace === namespace) && (!qualifier || self.qualifierCompare(listener.qualifier, qualifier)) && (!callback || listener.callback === callback)) {
  11539. listeners.splice(i, 1);
  11540. return false;
  11541. }
  11542. }, events, qualifier, callback, conf);
  11543. };
  11544. for (var i = listeners.length - 1; i >= 0; i--) {
  11545. _loop(i);
  11546. }
  11547. return this;
  11548. };
  11549. p.removeAllListeners = function () {
  11550. return this.removeListener('*');
  11551. };
  11552. p.emit = p.trigger = function (events, extraParams, manualCallback) {
  11553. var listeners = this.listeners;
  11554. var numListenersBeforeEmit = listeners.length;
  11555. this.emitting++;
  11556. if (!array(extraParams)) {
  11557. extraParams = [extraParams];
  11558. }
  11559. forEachEventObj(this, function (self, eventObj) {
  11560. if (manualCallback != null) {
  11561. listeners = [{
  11562. event: eventObj.event,
  11563. type: eventObj.type,
  11564. namespace: eventObj.namespace,
  11565. callback: manualCallback
  11566. }];
  11567. numListenersBeforeEmit = listeners.length;
  11568. }
  11569. var _loop2 = function _loop2() {
  11570. var listener = listeners[i];
  11571. if (listener.type === eventObj.type && (!listener.namespace || listener.namespace === eventObj.namespace || listener.namespace === universalNamespace) && self.eventMatches(self.context, listener, eventObj)) {
  11572. var args = [eventObj];
  11573. if (extraParams != null) {
  11574. push(args, extraParams);
  11575. }
  11576. self.beforeEmit(self.context, listener, eventObj);
  11577. if (listener.conf && listener.conf.one) {
  11578. self.listeners = self.listeners.filter(function (l) {
  11579. return l !== listener;
  11580. });
  11581. }
  11582. var context = self.callbackContext(self.context, listener, eventObj);
  11583. var ret = listener.callback.apply(context, args);
  11584. self.afterEmit(self.context, listener, eventObj);
  11585. if (ret === false) {
  11586. eventObj.stopPropagation();
  11587. eventObj.preventDefault();
  11588. }
  11589. } // if listener matches
  11590. };
  11591. for (var i = 0; i < numListenersBeforeEmit; i++) {
  11592. _loop2();
  11593. } // for listener
  11594. if (self.bubble(self.context) && !eventObj.isPropagationStopped()) {
  11595. self.parent(self.context).emit(eventObj, extraParams);
  11596. }
  11597. }, events);
  11598. this.emitting--;
  11599. return this;
  11600. };
  11601. var emitterOptions$1 = {
  11602. qualifierCompare: function qualifierCompare(selector1, selector2) {
  11603. if (selector1 == null || selector2 == null) {
  11604. return selector1 == null && selector2 == null;
  11605. } else {
  11606. return selector1.sameText(selector2);
  11607. }
  11608. },
  11609. eventMatches: function eventMatches(ele, listener, eventObj) {
  11610. var selector = listener.qualifier;
  11611. if (selector != null) {
  11612. return ele !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
  11613. }
  11614. return true;
  11615. },
  11616. addEventFields: function addEventFields(ele, evt) {
  11617. evt.cy = ele.cy();
  11618. evt.target = ele;
  11619. },
  11620. callbackContext: function callbackContext(ele, listener, eventObj) {
  11621. return listener.qualifier != null ? eventObj.target : ele;
  11622. },
  11623. beforeEmit: function beforeEmit(context, listener /*, eventObj*/) {
  11624. if (listener.conf && listener.conf.once) {
  11625. listener.conf.onceCollection.removeListener(listener.event, listener.qualifier, listener.callback);
  11626. }
  11627. },
  11628. bubble: function bubble() {
  11629. return true;
  11630. },
  11631. parent: function parent(ele) {
  11632. return ele.isChild() ? ele.parent() : ele.cy();
  11633. }
  11634. };
  11635. var argSelector$1 = function argSelector(arg) {
  11636. if (string(arg)) {
  11637. return new Selector(arg);
  11638. } else {
  11639. return arg;
  11640. }
  11641. };
  11642. var elesfn$9 = {
  11643. createEmitter: function createEmitter() {
  11644. for (var i = 0; i < this.length; i++) {
  11645. var ele = this[i];
  11646. var _p = ele._private;
  11647. if (!_p.emitter) {
  11648. _p.emitter = new Emitter(emitterOptions$1, ele);
  11649. }
  11650. }
  11651. return this;
  11652. },
  11653. emitter: function emitter() {
  11654. return this._private.emitter;
  11655. },
  11656. on: function on(events, selector, callback) {
  11657. var argSel = argSelector$1(selector);
  11658. for (var i = 0; i < this.length; i++) {
  11659. var ele = this[i];
  11660. ele.emitter().on(events, argSel, callback);
  11661. }
  11662. return this;
  11663. },
  11664. removeListener: function removeListener(events, selector, callback) {
  11665. var argSel = argSelector$1(selector);
  11666. for (var i = 0; i < this.length; i++) {
  11667. var ele = this[i];
  11668. ele.emitter().removeListener(events, argSel, callback);
  11669. }
  11670. return this;
  11671. },
  11672. removeAllListeners: function removeAllListeners() {
  11673. for (var i = 0; i < this.length; i++) {
  11674. var ele = this[i];
  11675. ele.emitter().removeAllListeners();
  11676. }
  11677. return this;
  11678. },
  11679. one: function one(events, selector, callback) {
  11680. var argSel = argSelector$1(selector);
  11681. for (var i = 0; i < this.length; i++) {
  11682. var ele = this[i];
  11683. ele.emitter().one(events, argSel, callback);
  11684. }
  11685. return this;
  11686. },
  11687. once: function once(events, selector, callback) {
  11688. var argSel = argSelector$1(selector);
  11689. for (var i = 0; i < this.length; i++) {
  11690. var ele = this[i];
  11691. ele.emitter().on(events, argSel, callback, {
  11692. once: true,
  11693. onceCollection: this
  11694. });
  11695. }
  11696. },
  11697. emit: function emit(events, extraParams) {
  11698. for (var i = 0; i < this.length; i++) {
  11699. var ele = this[i];
  11700. ele.emitter().emit(events, extraParams);
  11701. }
  11702. return this;
  11703. },
  11704. emitAndNotify: function emitAndNotify(event, extraParams) {
  11705. // for internal use only
  11706. if (this.length === 0) {
  11707. return;
  11708. } // empty collections don't need to notify anything
  11709. // notify renderer
  11710. this.cy().notify(event, this);
  11711. this.emit(event, extraParams);
  11712. return this;
  11713. }
  11714. };
  11715. define.eventAliasesOn(elesfn$9);
  11716. var elesfn$8 = {
  11717. nodes: function nodes(selector) {
  11718. return this.filter(function (ele) {
  11719. return ele.isNode();
  11720. }).filter(selector);
  11721. },
  11722. edges: function edges(selector) {
  11723. return this.filter(function (ele) {
  11724. return ele.isEdge();
  11725. }).filter(selector);
  11726. },
  11727. // internal helper to get nodes and edges as separate collections with single iteration over elements
  11728. byGroup: function byGroup() {
  11729. var nodes = this.spawn();
  11730. var edges = this.spawn();
  11731. for (var i = 0; i < this.length; i++) {
  11732. var ele = this[i];
  11733. if (ele.isNode()) {
  11734. nodes.push(ele);
  11735. } else {
  11736. edges.push(ele);
  11737. }
  11738. }
  11739. return {
  11740. nodes: nodes,
  11741. edges: edges
  11742. };
  11743. },
  11744. filter: function filter(_filter, thisArg) {
  11745. if (_filter === undefined) {
  11746. // check this first b/c it's the most common/performant case
  11747. return this;
  11748. } else if (string(_filter) || elementOrCollection(_filter)) {
  11749. return new Selector(_filter).filter(this);
  11750. } else if (fn$6(_filter)) {
  11751. var filterEles = this.spawn();
  11752. var eles = this;
  11753. for (var i = 0; i < eles.length; i++) {
  11754. var ele = eles[i];
  11755. var include = thisArg ? _filter.apply(thisArg, [ele, i, eles]) : _filter(ele, i, eles);
  11756. if (include) {
  11757. filterEles.push(ele);
  11758. }
  11759. }
  11760. return filterEles;
  11761. }
  11762. return this.spawn(); // if not handled by above, give 'em an empty collection
  11763. },
  11764. not: function not(toRemove) {
  11765. if (!toRemove) {
  11766. return this;
  11767. } else {
  11768. if (string(toRemove)) {
  11769. toRemove = this.filter(toRemove);
  11770. }
  11771. var elements = this.spawn();
  11772. for (var i = 0; i < this.length; i++) {
  11773. var element = this[i];
  11774. var remove = toRemove.has(element);
  11775. if (!remove) {
  11776. elements.push(element);
  11777. }
  11778. }
  11779. return elements;
  11780. }
  11781. },
  11782. absoluteComplement: function absoluteComplement() {
  11783. var cy = this.cy();
  11784. return cy.mutableElements().not(this);
  11785. },
  11786. intersect: function intersect(other) {
  11787. // if a selector is specified, then filter by it instead
  11788. if (string(other)) {
  11789. var selector = other;
  11790. return this.filter(selector);
  11791. }
  11792. var elements = this.spawn();
  11793. var col1 = this;
  11794. var col2 = other;
  11795. var col1Smaller = this.length < other.length;
  11796. var colS = col1Smaller ? col1 : col2;
  11797. var colL = col1Smaller ? col2 : col1;
  11798. for (var i = 0; i < colS.length; i++) {
  11799. var ele = colS[i];
  11800. if (colL.has(ele)) {
  11801. elements.push(ele);
  11802. }
  11803. }
  11804. return elements;
  11805. },
  11806. xor: function xor(other) {
  11807. var cy = this._private.cy;
  11808. if (string(other)) {
  11809. other = cy.$(other);
  11810. }
  11811. var elements = this.spawn();
  11812. var col1 = this;
  11813. var col2 = other;
  11814. var add = function add(col, other) {
  11815. for (var i = 0; i < col.length; i++) {
  11816. var ele = col[i];
  11817. var id = ele._private.data.id;
  11818. var inOther = other.hasElementWithId(id);
  11819. if (!inOther) {
  11820. elements.push(ele);
  11821. }
  11822. }
  11823. };
  11824. add(col1, col2);
  11825. add(col2, col1);
  11826. return elements;
  11827. },
  11828. diff: function diff(other) {
  11829. var cy = this._private.cy;
  11830. if (string(other)) {
  11831. other = cy.$(other);
  11832. }
  11833. var left = this.spawn();
  11834. var right = this.spawn();
  11835. var both = this.spawn();
  11836. var col1 = this;
  11837. var col2 = other;
  11838. var add = function add(col, other, retEles) {
  11839. for (var i = 0; i < col.length; i++) {
  11840. var ele = col[i];
  11841. var id = ele._private.data.id;
  11842. var inOther = other.hasElementWithId(id);
  11843. if (inOther) {
  11844. both.merge(ele);
  11845. } else {
  11846. retEles.push(ele);
  11847. }
  11848. }
  11849. };
  11850. add(col1, col2, left);
  11851. add(col2, col1, right);
  11852. return {
  11853. left: left,
  11854. right: right,
  11855. both: both
  11856. };
  11857. },
  11858. add: function add(toAdd) {
  11859. var cy = this._private.cy;
  11860. if (!toAdd) {
  11861. return this;
  11862. }
  11863. if (string(toAdd)) {
  11864. var selector = toAdd;
  11865. toAdd = cy.mutableElements().filter(selector);
  11866. }
  11867. var elements = this.spawnSelf();
  11868. for (var i = 0; i < toAdd.length; i++) {
  11869. var ele = toAdd[i];
  11870. var add = !this.has(ele);
  11871. if (add) {
  11872. elements.push(ele);
  11873. }
  11874. }
  11875. return elements;
  11876. },
  11877. // in place merge on calling collection
  11878. merge: function merge(toAdd) {
  11879. var _p = this._private;
  11880. var cy = _p.cy;
  11881. if (!toAdd) {
  11882. return this;
  11883. }
  11884. if (toAdd && string(toAdd)) {
  11885. var selector = toAdd;
  11886. toAdd = cy.mutableElements().filter(selector);
  11887. }
  11888. var map = _p.map;
  11889. for (var i = 0; i < toAdd.length; i++) {
  11890. var toAddEle = toAdd[i];
  11891. var id = toAddEle._private.data.id;
  11892. var add = !map.has(id);
  11893. if (add) {
  11894. var index = this.length++;
  11895. this[index] = toAddEle;
  11896. map.set(id, {
  11897. ele: toAddEle,
  11898. index: index
  11899. });
  11900. }
  11901. }
  11902. return this; // chaining
  11903. },
  11904. unmergeAt: function unmergeAt(i) {
  11905. var ele = this[i];
  11906. var id = ele.id();
  11907. var _p = this._private;
  11908. var map = _p.map;
  11909. // remove ele
  11910. this[i] = undefined;
  11911. map["delete"](id);
  11912. var unmergedLastEle = i === this.length - 1;
  11913. // replace empty spot with last ele in collection
  11914. if (this.length > 1 && !unmergedLastEle) {
  11915. var lastEleI = this.length - 1;
  11916. var lastEle = this[lastEleI];
  11917. var lastEleId = lastEle._private.data.id;
  11918. this[lastEleI] = undefined;
  11919. this[i] = lastEle;
  11920. map.set(lastEleId, {
  11921. ele: lastEle,
  11922. index: i
  11923. });
  11924. }
  11925. // the collection is now 1 ele smaller
  11926. this.length--;
  11927. return this;
  11928. },
  11929. // remove single ele in place in calling collection
  11930. unmergeOne: function unmergeOne(ele) {
  11931. ele = ele[0];
  11932. var _p = this._private;
  11933. var id = ele._private.data.id;
  11934. var map = _p.map;
  11935. var entry = map.get(id);
  11936. if (!entry) {
  11937. return this; // no need to remove
  11938. }
  11939. var i = entry.index;
  11940. this.unmergeAt(i);
  11941. return this;
  11942. },
  11943. // remove eles in place on calling collection
  11944. unmerge: function unmerge(toRemove) {
  11945. var cy = this._private.cy;
  11946. if (!toRemove) {
  11947. return this;
  11948. }
  11949. if (toRemove && string(toRemove)) {
  11950. var selector = toRemove;
  11951. toRemove = cy.mutableElements().filter(selector);
  11952. }
  11953. for (var i = 0; i < toRemove.length; i++) {
  11954. this.unmergeOne(toRemove[i]);
  11955. }
  11956. return this; // chaining
  11957. },
  11958. unmergeBy: function unmergeBy(toRmFn) {
  11959. for (var i = this.length - 1; i >= 0; i--) {
  11960. var ele = this[i];
  11961. if (toRmFn(ele)) {
  11962. this.unmergeAt(i);
  11963. }
  11964. }
  11965. return this;
  11966. },
  11967. map: function map(mapFn, thisArg) {
  11968. var arr = [];
  11969. var eles = this;
  11970. for (var i = 0; i < eles.length; i++) {
  11971. var ele = eles[i];
  11972. var ret = thisArg ? mapFn.apply(thisArg, [ele, i, eles]) : mapFn(ele, i, eles);
  11973. arr.push(ret);
  11974. }
  11975. return arr;
  11976. },
  11977. reduce: function reduce(fn, initialValue) {
  11978. var val = initialValue;
  11979. var eles = this;
  11980. for (var i = 0; i < eles.length; i++) {
  11981. val = fn(val, eles[i], i, eles);
  11982. }
  11983. return val;
  11984. },
  11985. max: function max(valFn, thisArg) {
  11986. var max = -Infinity;
  11987. var maxEle;
  11988. var eles = this;
  11989. for (var i = 0; i < eles.length; i++) {
  11990. var ele = eles[i];
  11991. var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
  11992. if (val > max) {
  11993. max = val;
  11994. maxEle = ele;
  11995. }
  11996. }
  11997. return {
  11998. value: max,
  11999. ele: maxEle
  12000. };
  12001. },
  12002. min: function min(valFn, thisArg) {
  12003. var min = Infinity;
  12004. var minEle;
  12005. var eles = this;
  12006. for (var i = 0; i < eles.length; i++) {
  12007. var ele = eles[i];
  12008. var val = thisArg ? valFn.apply(thisArg, [ele, i, eles]) : valFn(ele, i, eles);
  12009. if (val < min) {
  12010. min = val;
  12011. minEle = ele;
  12012. }
  12013. }
  12014. return {
  12015. value: min,
  12016. ele: minEle
  12017. };
  12018. }
  12019. };
  12020. // aliases
  12021. var fn$1 = elesfn$8;
  12022. fn$1['u'] = fn$1['|'] = fn$1['+'] = fn$1.union = fn$1.or = fn$1.add;
  12023. fn$1['\\'] = fn$1['!'] = fn$1['-'] = fn$1.difference = fn$1.relativeComplement = fn$1.subtract = fn$1.not;
  12024. fn$1['n'] = fn$1['&'] = fn$1['.'] = fn$1.and = fn$1.intersection = fn$1.intersect;
  12025. fn$1['^'] = fn$1['(+)'] = fn$1['(-)'] = fn$1.symmetricDifference = fn$1.symdiff = fn$1.xor;
  12026. fn$1.fnFilter = fn$1.filterFn = fn$1.stdFilter = fn$1.filter;
  12027. fn$1.complement = fn$1.abscomp = fn$1.absoluteComplement;
  12028. var elesfn$7 = {
  12029. isNode: function isNode() {
  12030. return this.group() === 'nodes';
  12031. },
  12032. isEdge: function isEdge() {
  12033. return this.group() === 'edges';
  12034. },
  12035. isLoop: function isLoop() {
  12036. return this.isEdge() && this.source()[0] === this.target()[0];
  12037. },
  12038. isSimple: function isSimple() {
  12039. return this.isEdge() && this.source()[0] !== this.target()[0];
  12040. },
  12041. group: function group() {
  12042. var ele = this[0];
  12043. if (ele) {
  12044. return ele._private.group;
  12045. }
  12046. }
  12047. };
  12048. /**
  12049. * Elements are drawn in a specific order based on compound depth (low to high), the element type (nodes above edges),
  12050. * and z-index (low to high). These styles affect how this applies:
  12051. *
  12052. * z-compound-depth: May be `bottom | orphan | auto | top`. The first drawn is `bottom`, then `orphan` which is the
  12053. * same depth as the root of the compound graph, followed by the default value `auto` which draws in order from
  12054. * root to leaves of the compound graph. The last drawn is `top`.
  12055. * z-index-compare: May be `auto | manual`. The default value is `auto` which always draws edges under nodes.
  12056. * `manual` ignores this convention and draws based on the `z-index` value setting.
  12057. * z-index: An integer value that affects the relative draw order of elements. In general, an element with a higher
  12058. * `z-index` will be drawn on top of an element with a lower `z-index`.
  12059. */
  12060. var zIndexSort = function zIndexSort(a, b) {
  12061. var cy = a.cy();
  12062. var hasCompoundNodes = cy.hasCompoundNodes();
  12063. function getDepth(ele) {
  12064. var style = ele.pstyle('z-compound-depth');
  12065. if (style.value === 'auto') {
  12066. return hasCompoundNodes ? ele.zDepth() : 0;
  12067. } else if (style.value === 'bottom') {
  12068. return -1;
  12069. } else if (style.value === 'top') {
  12070. return MAX_INT$1;
  12071. }
  12072. // 'orphan'
  12073. return 0;
  12074. }
  12075. var depthDiff = getDepth(a) - getDepth(b);
  12076. if (depthDiff !== 0) {
  12077. return depthDiff;
  12078. }
  12079. function getEleDepth(ele) {
  12080. var style = ele.pstyle('z-index-compare');
  12081. if (style.value === 'auto') {
  12082. return ele.isNode() ? 1 : 0;
  12083. }
  12084. // 'manual'
  12085. return 0;
  12086. }
  12087. var eleDiff = getEleDepth(a) - getEleDepth(b);
  12088. if (eleDiff !== 0) {
  12089. return eleDiff;
  12090. }
  12091. var zDiff = a.pstyle('z-index').value - b.pstyle('z-index').value;
  12092. if (zDiff !== 0) {
  12093. return zDiff;
  12094. }
  12095. // compare indices in the core (order added to graph w/ last on top)
  12096. return a.poolIndex() - b.poolIndex();
  12097. };
  12098. var elesfn$6 = {
  12099. forEach: function forEach(fn, thisArg) {
  12100. if (fn$6(fn)) {
  12101. var N = this.length;
  12102. for (var i = 0; i < N; i++) {
  12103. var ele = this[i];
  12104. var ret = thisArg ? fn.apply(thisArg, [ele, i, this]) : fn(ele, i, this);
  12105. if (ret === false) {
  12106. break;
  12107. } // exit each early on return false
  12108. }
  12109. }
  12110. return this;
  12111. },
  12112. toArray: function toArray() {
  12113. var array = [];
  12114. for (var i = 0; i < this.length; i++) {
  12115. array.push(this[i]);
  12116. }
  12117. return array;
  12118. },
  12119. slice: function slice(start, end) {
  12120. var array = [];
  12121. var thisSize = this.length;
  12122. if (end == null) {
  12123. end = thisSize;
  12124. }
  12125. if (start == null) {
  12126. start = 0;
  12127. }
  12128. if (start < 0) {
  12129. start = thisSize + start;
  12130. }
  12131. if (end < 0) {
  12132. end = thisSize + end;
  12133. }
  12134. for (var i = start; i >= 0 && i < end && i < thisSize; i++) {
  12135. array.push(this[i]);
  12136. }
  12137. return this.spawn(array);
  12138. },
  12139. size: function size() {
  12140. return this.length;
  12141. },
  12142. eq: function eq(i) {
  12143. return this[i] || this.spawn();
  12144. },
  12145. first: function first() {
  12146. return this[0] || this.spawn();
  12147. },
  12148. last: function last() {
  12149. return this[this.length - 1] || this.spawn();
  12150. },
  12151. empty: function empty() {
  12152. return this.length === 0;
  12153. },
  12154. nonempty: function nonempty() {
  12155. return !this.empty();
  12156. },
  12157. sort: function sort(sortFn) {
  12158. if (!fn$6(sortFn)) {
  12159. return this;
  12160. }
  12161. var sorted = this.toArray().sort(sortFn);
  12162. return this.spawn(sorted);
  12163. },
  12164. sortByZIndex: function sortByZIndex() {
  12165. return this.sort(zIndexSort);
  12166. },
  12167. zDepth: function zDepth() {
  12168. var ele = this[0];
  12169. if (!ele) {
  12170. return undefined;
  12171. }
  12172. // let cy = ele.cy();
  12173. var _p = ele._private;
  12174. var group = _p.group;
  12175. if (group === 'nodes') {
  12176. var depth = _p.data.parent ? ele.parents().size() : 0;
  12177. if (!ele.isParent()) {
  12178. return MAX_INT$1 - 1; // childless nodes always on top
  12179. }
  12180. return depth;
  12181. } else {
  12182. var src = _p.source;
  12183. var tgt = _p.target;
  12184. var srcDepth = src.zDepth();
  12185. var tgtDepth = tgt.zDepth();
  12186. return Math.max(srcDepth, tgtDepth, 0); // depth of deepest parent
  12187. }
  12188. }
  12189. };
  12190. elesfn$6.each = elesfn$6.forEach;
  12191. var defineSymbolIterator = function defineSymbolIterator() {
  12192. var typeofUndef = "undefined" ;
  12193. var isIteratorSupported = (typeof Symbol === "undefined" ? "undefined" : _typeof(Symbol)) != typeofUndef && _typeof(Symbol.iterator) != typeofUndef;
  12194. if (isIteratorSupported) {
  12195. elesfn$6[Symbol.iterator] = function () {
  12196. var _this = this;
  12197. var entry = {
  12198. value: undefined,
  12199. done: false
  12200. };
  12201. var i = 0;
  12202. var length = this.length;
  12203. return _defineProperty$1({
  12204. next: function next() {
  12205. if (i < length) {
  12206. entry.value = _this[i++];
  12207. } else {
  12208. entry.value = undefined;
  12209. entry.done = true;
  12210. }
  12211. return entry;
  12212. }
  12213. }, Symbol.iterator, function () {
  12214. return this;
  12215. });
  12216. };
  12217. }
  12218. };
  12219. defineSymbolIterator();
  12220. var getLayoutDimensionOptions = defaults$g({
  12221. nodeDimensionsIncludeLabels: false
  12222. });
  12223. var elesfn$5 = {
  12224. // Calculates and returns node dimensions { x, y } based on options given
  12225. layoutDimensions: function layoutDimensions(options) {
  12226. options = getLayoutDimensionOptions(options);
  12227. var dims;
  12228. if (!this.takesUpSpace()) {
  12229. dims = {
  12230. w: 0,
  12231. h: 0
  12232. };
  12233. } else if (options.nodeDimensionsIncludeLabels) {
  12234. var bbDim = this.boundingBox();
  12235. dims = {
  12236. w: bbDim.w,
  12237. h: bbDim.h
  12238. };
  12239. } else {
  12240. dims = {
  12241. w: this.outerWidth(),
  12242. h: this.outerHeight()
  12243. };
  12244. }
  12245. // sanitise the dimensions for external layouts (avoid division by zero)
  12246. if (dims.w === 0 || dims.h === 0) {
  12247. dims.w = dims.h = 1;
  12248. }
  12249. return dims;
  12250. },
  12251. // using standard layout options, apply position function (w/ or w/o animation)
  12252. layoutPositions: function layoutPositions(layout, options, fn) {
  12253. var nodes = this.nodes().filter(function (n) {
  12254. return !n.isParent();
  12255. });
  12256. var cy = this.cy();
  12257. var layoutEles = options.eles; // nodes & edges
  12258. var getMemoizeKey = function getMemoizeKey(node) {
  12259. return node.id();
  12260. };
  12261. var fnMem = memoize(fn, getMemoizeKey); // memoized version of position function
  12262. layout.emit({
  12263. type: 'layoutstart',
  12264. layout: layout
  12265. });
  12266. layout.animations = [];
  12267. var calculateSpacing = function calculateSpacing(spacing, nodesBb, pos) {
  12268. var center = {
  12269. x: nodesBb.x1 + nodesBb.w / 2,
  12270. y: nodesBb.y1 + nodesBb.h / 2
  12271. };
  12272. var spacingVector = {
  12273. // scale from center of bounding box (not necessarily 0,0)
  12274. x: (pos.x - center.x) * spacing,
  12275. y: (pos.y - center.y) * spacing
  12276. };
  12277. return {
  12278. x: center.x + spacingVector.x,
  12279. y: center.y + spacingVector.y
  12280. };
  12281. };
  12282. var useSpacingFactor = options.spacingFactor && options.spacingFactor !== 1;
  12283. var spacingBb = function spacingBb() {
  12284. if (!useSpacingFactor) {
  12285. return null;
  12286. }
  12287. var bb = makeBoundingBox();
  12288. for (var i = 0; i < nodes.length; i++) {
  12289. var node = nodes[i];
  12290. var pos = fnMem(node, i);
  12291. expandBoundingBoxByPoint(bb, pos.x, pos.y);
  12292. }
  12293. return bb;
  12294. };
  12295. var bb = spacingBb();
  12296. var getFinalPos = memoize(function (node, i) {
  12297. var newPos = fnMem(node, i);
  12298. if (useSpacingFactor) {
  12299. var spacing = Math.abs(options.spacingFactor);
  12300. newPos = calculateSpacing(spacing, bb, newPos);
  12301. }
  12302. if (options.transform != null) {
  12303. newPos = options.transform(node, newPos);
  12304. }
  12305. return newPos;
  12306. }, getMemoizeKey);
  12307. if (options.animate) {
  12308. for (var i = 0; i < nodes.length; i++) {
  12309. var node = nodes[i];
  12310. var newPos = getFinalPos(node, i);
  12311. var animateNode = options.animateFilter == null || options.animateFilter(node, i);
  12312. if (animateNode) {
  12313. var ani = node.animation({
  12314. position: newPos,
  12315. duration: options.animationDuration,
  12316. easing: options.animationEasing
  12317. });
  12318. layout.animations.push(ani);
  12319. } else {
  12320. node.position(newPos);
  12321. }
  12322. }
  12323. if (options.fit) {
  12324. var fitAni = cy.animation({
  12325. fit: {
  12326. boundingBox: layoutEles.boundingBoxAt(getFinalPos),
  12327. padding: options.padding
  12328. },
  12329. duration: options.animationDuration,
  12330. easing: options.animationEasing
  12331. });
  12332. layout.animations.push(fitAni);
  12333. } else if (options.zoom !== undefined && options.pan !== undefined) {
  12334. var zoomPanAni = cy.animation({
  12335. zoom: options.zoom,
  12336. pan: options.pan,
  12337. duration: options.animationDuration,
  12338. easing: options.animationEasing
  12339. });
  12340. layout.animations.push(zoomPanAni);
  12341. }
  12342. layout.animations.forEach(function (ani) {
  12343. return ani.play();
  12344. });
  12345. layout.one('layoutready', options.ready);
  12346. layout.emit({
  12347. type: 'layoutready',
  12348. layout: layout
  12349. });
  12350. Promise$1.all(layout.animations.map(function (ani) {
  12351. return ani.promise();
  12352. })).then(function () {
  12353. layout.one('layoutstop', options.stop);
  12354. layout.emit({
  12355. type: 'layoutstop',
  12356. layout: layout
  12357. });
  12358. });
  12359. } else {
  12360. nodes.positions(getFinalPos);
  12361. if (options.fit) {
  12362. cy.fit(options.eles, options.padding);
  12363. }
  12364. if (options.zoom != null) {
  12365. cy.zoom(options.zoom);
  12366. }
  12367. if (options.pan) {
  12368. cy.pan(options.pan);
  12369. }
  12370. layout.one('layoutready', options.ready);
  12371. layout.emit({
  12372. type: 'layoutready',
  12373. layout: layout
  12374. });
  12375. layout.one('layoutstop', options.stop);
  12376. layout.emit({
  12377. type: 'layoutstop',
  12378. layout: layout
  12379. });
  12380. }
  12381. return this; // chaining
  12382. },
  12383. layout: function layout(options) {
  12384. var cy = this.cy();
  12385. return cy.makeLayout(extend({}, options, {
  12386. eles: this
  12387. }));
  12388. }
  12389. };
  12390. // aliases:
  12391. elesfn$5.createLayout = elesfn$5.makeLayout = elesfn$5.layout;
  12392. function styleCache(key, fn, ele) {
  12393. var _p = ele._private;
  12394. var cache = _p.styleCache = _p.styleCache || [];
  12395. var val;
  12396. if ((val = cache[key]) != null) {
  12397. return val;
  12398. } else {
  12399. val = cache[key] = fn(ele);
  12400. return val;
  12401. }
  12402. }
  12403. function cacheStyleFunction(key, fn) {
  12404. key = hashString(key);
  12405. return function cachedStyleFunction(ele) {
  12406. return styleCache(key, fn, ele);
  12407. };
  12408. }
  12409. function cachePrototypeStyleFunction(key, fn) {
  12410. key = hashString(key);
  12411. var selfFn = function selfFn(ele) {
  12412. return fn.call(ele);
  12413. };
  12414. return function cachedPrototypeStyleFunction() {
  12415. var ele = this[0];
  12416. if (ele) {
  12417. return styleCache(key, selfFn, ele);
  12418. }
  12419. };
  12420. }
  12421. var elesfn$4 = {
  12422. recalculateRenderedStyle: function recalculateRenderedStyle(useCache) {
  12423. var cy = this.cy();
  12424. var renderer = cy.renderer();
  12425. var styleEnabled = cy.styleEnabled();
  12426. if (renderer && styleEnabled) {
  12427. renderer.recalculateRenderedStyle(this, useCache);
  12428. }
  12429. return this;
  12430. },
  12431. dirtyStyleCache: function dirtyStyleCache() {
  12432. var cy = this.cy();
  12433. var dirty = function dirty(ele) {
  12434. return ele._private.styleCache = null;
  12435. };
  12436. if (cy.hasCompoundNodes()) {
  12437. var eles;
  12438. eles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
  12439. eles.merge(eles.connectedEdges());
  12440. eles.forEach(dirty);
  12441. } else {
  12442. this.forEach(function (ele) {
  12443. dirty(ele);
  12444. ele.connectedEdges().forEach(dirty);
  12445. });
  12446. }
  12447. return this;
  12448. },
  12449. // fully updates (recalculates) the style for the elements
  12450. updateStyle: function updateStyle(notifyRenderer) {
  12451. var cy = this._private.cy;
  12452. if (!cy.styleEnabled()) {
  12453. return this;
  12454. }
  12455. if (cy.batching()) {
  12456. var bEles = cy._private.batchStyleEles;
  12457. bEles.merge(this);
  12458. return this; // chaining and exit early when batching
  12459. }
  12460. var hasCompounds = cy.hasCompoundNodes();
  12461. var updatedEles = this;
  12462. notifyRenderer = notifyRenderer || notifyRenderer === undefined ? true : false;
  12463. if (hasCompounds) {
  12464. // then add everything up and down for compound selector checks
  12465. updatedEles = this.spawnSelf().merge(this.descendants()).merge(this.parents());
  12466. }
  12467. // let changedEles = style.apply( updatedEles );
  12468. var changedEles = updatedEles;
  12469. if (notifyRenderer) {
  12470. changedEles.emitAndNotify('style'); // let renderer know we changed style
  12471. } else {
  12472. changedEles.emit('style'); // just fire the event
  12473. }
  12474. updatedEles.forEach(function (ele) {
  12475. return ele._private.styleDirty = true;
  12476. });
  12477. return this; // chaining
  12478. },
  12479. // private: clears dirty flag and recalculates style
  12480. cleanStyle: function cleanStyle() {
  12481. var cy = this.cy();
  12482. if (!cy.styleEnabled()) {
  12483. return;
  12484. }
  12485. for (var i = 0; i < this.length; i++) {
  12486. var ele = this[i];
  12487. if (ele._private.styleDirty) {
  12488. // n.b. this flag should be set before apply() to avoid potential infinite recursion
  12489. ele._private.styleDirty = false;
  12490. cy.style().apply(ele);
  12491. }
  12492. }
  12493. },
  12494. // get the internal parsed style object for the specified property
  12495. parsedStyle: function parsedStyle(property) {
  12496. var includeNonDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  12497. var ele = this[0];
  12498. var cy = ele.cy();
  12499. if (!cy.styleEnabled()) {
  12500. return;
  12501. }
  12502. if (ele) {
  12503. // this.cleanStyle();
  12504. // Inline the important part of cleanStyle(), for raw performance
  12505. if (ele._private.styleDirty) {
  12506. // n.b. this flag should be set before apply() to avoid potential infinite recursion
  12507. ele._private.styleDirty = false;
  12508. cy.style().apply(ele);
  12509. }
  12510. var overriddenStyle = ele._private.style[property];
  12511. if (overriddenStyle != null) {
  12512. return overriddenStyle;
  12513. } else if (includeNonDefault) {
  12514. return cy.style().getDefaultProperty(property);
  12515. } else {
  12516. return null;
  12517. }
  12518. }
  12519. },
  12520. numericStyle: function numericStyle(property) {
  12521. var ele = this[0];
  12522. if (!ele.cy().styleEnabled()) {
  12523. return;
  12524. }
  12525. if (ele) {
  12526. var pstyle = ele.pstyle(property);
  12527. return pstyle.pfValue !== undefined ? pstyle.pfValue : pstyle.value;
  12528. }
  12529. },
  12530. numericStyleUnits: function numericStyleUnits(property) {
  12531. var ele = this[0];
  12532. if (!ele.cy().styleEnabled()) {
  12533. return;
  12534. }
  12535. if (ele) {
  12536. return ele.pstyle(property).units;
  12537. }
  12538. },
  12539. // get the specified css property as a rendered value (i.e. on-screen value)
  12540. // or get the whole rendered style if no property specified (NB doesn't allow setting)
  12541. renderedStyle: function renderedStyle(property) {
  12542. var cy = this.cy();
  12543. if (!cy.styleEnabled()) {
  12544. return this;
  12545. }
  12546. var ele = this[0];
  12547. if (ele) {
  12548. return cy.style().getRenderedStyle(ele, property);
  12549. }
  12550. },
  12551. // read the calculated css style of the element or override the style (via a bypass)
  12552. style: function style(name, value) {
  12553. var cy = this.cy();
  12554. if (!cy.styleEnabled()) {
  12555. return this;
  12556. }
  12557. var updateTransitions = false;
  12558. var style = cy.style();
  12559. if (plainObject(name)) {
  12560. // then extend the bypass
  12561. var props = name;
  12562. style.applyBypass(this, props, updateTransitions);
  12563. this.emitAndNotify('style'); // let the renderer know we've updated style
  12564. } else if (string(name)) {
  12565. if (value === undefined) {
  12566. // then get the property from the style
  12567. var ele = this[0];
  12568. if (ele) {
  12569. return style.getStylePropertyValue(ele, name);
  12570. } else {
  12571. // empty collection => can't get any value
  12572. return;
  12573. }
  12574. } else {
  12575. // then set the bypass with the property value
  12576. style.applyBypass(this, name, value, updateTransitions);
  12577. this.emitAndNotify('style'); // let the renderer know we've updated style
  12578. }
  12579. } else if (name === undefined) {
  12580. var _ele = this[0];
  12581. if (_ele) {
  12582. return style.getRawStyle(_ele);
  12583. } else {
  12584. // empty collection => can't get any value
  12585. return;
  12586. }
  12587. }
  12588. return this; // chaining
  12589. },
  12590. removeStyle: function removeStyle(names) {
  12591. var cy = this.cy();
  12592. if (!cy.styleEnabled()) {
  12593. return this;
  12594. }
  12595. var updateTransitions = false;
  12596. var style = cy.style();
  12597. var eles = this;
  12598. if (names === undefined) {
  12599. for (var i = 0; i < eles.length; i++) {
  12600. var ele = eles[i];
  12601. style.removeAllBypasses(ele, updateTransitions);
  12602. }
  12603. } else {
  12604. names = names.split(/\s+/);
  12605. for (var _i = 0; _i < eles.length; _i++) {
  12606. var _ele2 = eles[_i];
  12607. style.removeBypasses(_ele2, names, updateTransitions);
  12608. }
  12609. }
  12610. this.emitAndNotify('style'); // let the renderer know we've updated style
  12611. return this; // chaining
  12612. },
  12613. show: function show() {
  12614. this.css('display', 'element');
  12615. return this; // chaining
  12616. },
  12617. hide: function hide() {
  12618. this.css('display', 'none');
  12619. return this; // chaining
  12620. },
  12621. effectiveOpacity: function effectiveOpacity() {
  12622. var cy = this.cy();
  12623. if (!cy.styleEnabled()) {
  12624. return 1;
  12625. }
  12626. var hasCompoundNodes = cy.hasCompoundNodes();
  12627. var ele = this[0];
  12628. if (ele) {
  12629. var _p = ele._private;
  12630. var parentOpacity = ele.pstyle('opacity').value;
  12631. if (!hasCompoundNodes) {
  12632. return parentOpacity;
  12633. }
  12634. var parents = !_p.data.parent ? null : ele.parents();
  12635. if (parents) {
  12636. for (var i = 0; i < parents.length; i++) {
  12637. var parent = parents[i];
  12638. var opacity = parent.pstyle('opacity').value;
  12639. parentOpacity = opacity * parentOpacity;
  12640. }
  12641. }
  12642. return parentOpacity;
  12643. }
  12644. },
  12645. transparent: function transparent() {
  12646. var cy = this.cy();
  12647. if (!cy.styleEnabled()) {
  12648. return false;
  12649. }
  12650. var ele = this[0];
  12651. var hasCompoundNodes = ele.cy().hasCompoundNodes();
  12652. if (ele) {
  12653. if (!hasCompoundNodes) {
  12654. return ele.pstyle('opacity').value === 0;
  12655. } else {
  12656. return ele.effectiveOpacity() === 0;
  12657. }
  12658. }
  12659. },
  12660. backgrounding: function backgrounding() {
  12661. var cy = this.cy();
  12662. if (!cy.styleEnabled()) {
  12663. return false;
  12664. }
  12665. var ele = this[0];
  12666. return ele._private.backgrounding ? true : false;
  12667. }
  12668. };
  12669. function checkCompound(ele, parentOk) {
  12670. var _p = ele._private;
  12671. var parents = _p.data.parent ? ele.parents() : null;
  12672. if (parents) {
  12673. for (var i = 0; i < parents.length; i++) {
  12674. var parent = parents[i];
  12675. if (!parentOk(parent)) {
  12676. return false;
  12677. }
  12678. }
  12679. }
  12680. return true;
  12681. }
  12682. function defineDerivedStateFunction(specs) {
  12683. var ok = specs.ok;
  12684. var edgeOkViaNode = specs.edgeOkViaNode || specs.ok;
  12685. var parentOk = specs.parentOk || specs.ok;
  12686. return function () {
  12687. var cy = this.cy();
  12688. if (!cy.styleEnabled()) {
  12689. return true;
  12690. }
  12691. var ele = this[0];
  12692. var hasCompoundNodes = cy.hasCompoundNodes();
  12693. if (ele) {
  12694. var _p = ele._private;
  12695. if (!ok(ele)) {
  12696. return false;
  12697. }
  12698. if (ele.isNode()) {
  12699. return !hasCompoundNodes || checkCompound(ele, parentOk);
  12700. } else {
  12701. var src = _p.source;
  12702. var tgt = _p.target;
  12703. return edgeOkViaNode(src) && (!hasCompoundNodes || checkCompound(src, edgeOkViaNode)) && (src === tgt || edgeOkViaNode(tgt) && (!hasCompoundNodes || checkCompound(tgt, edgeOkViaNode)));
  12704. }
  12705. }
  12706. };
  12707. }
  12708. var eleTakesUpSpace = cacheStyleFunction('eleTakesUpSpace', function (ele) {
  12709. return ele.pstyle('display').value === 'element' && ele.width() !== 0 && (ele.isNode() ? ele.height() !== 0 : true);
  12710. });
  12711. elesfn$4.takesUpSpace = cachePrototypeStyleFunction('takesUpSpace', defineDerivedStateFunction({
  12712. ok: eleTakesUpSpace
  12713. }));
  12714. var eleInteractive = cacheStyleFunction('eleInteractive', function (ele) {
  12715. return ele.pstyle('events').value === 'yes' && ele.pstyle('visibility').value === 'visible' && eleTakesUpSpace(ele);
  12716. });
  12717. var parentInteractive = cacheStyleFunction('parentInteractive', function (parent) {
  12718. return parent.pstyle('visibility').value === 'visible' && eleTakesUpSpace(parent);
  12719. });
  12720. elesfn$4.interactive = cachePrototypeStyleFunction('interactive', defineDerivedStateFunction({
  12721. ok: eleInteractive,
  12722. parentOk: parentInteractive,
  12723. edgeOkViaNode: eleTakesUpSpace
  12724. }));
  12725. elesfn$4.noninteractive = function () {
  12726. var ele = this[0];
  12727. if (ele) {
  12728. return !ele.interactive();
  12729. }
  12730. };
  12731. var eleVisible = cacheStyleFunction('eleVisible', function (ele) {
  12732. return ele.pstyle('visibility').value === 'visible' && ele.pstyle('opacity').pfValue !== 0 && eleTakesUpSpace(ele);
  12733. });
  12734. var edgeVisibleViaNode = eleTakesUpSpace;
  12735. elesfn$4.visible = cachePrototypeStyleFunction('visible', defineDerivedStateFunction({
  12736. ok: eleVisible,
  12737. edgeOkViaNode: edgeVisibleViaNode
  12738. }));
  12739. elesfn$4.hidden = function () {
  12740. var ele = this[0];
  12741. if (ele) {
  12742. return !ele.visible();
  12743. }
  12744. };
  12745. elesfn$4.isBundledBezier = cachePrototypeStyleFunction('isBundledBezier', function () {
  12746. if (!this.cy().styleEnabled()) {
  12747. return false;
  12748. }
  12749. return !this.removed() && this.pstyle('curve-style').value === 'bezier' && this.takesUpSpace();
  12750. });
  12751. elesfn$4.bypass = elesfn$4.css = elesfn$4.style;
  12752. elesfn$4.renderedCss = elesfn$4.renderedStyle;
  12753. elesfn$4.removeBypass = elesfn$4.removeCss = elesfn$4.removeStyle;
  12754. elesfn$4.pstyle = elesfn$4.parsedStyle;
  12755. var elesfn$3 = {};
  12756. function defineSwitchFunction(params) {
  12757. return function () {
  12758. var args = arguments;
  12759. var changedEles = [];
  12760. // e.g. cy.nodes().select( data, handler )
  12761. if (args.length === 2) {
  12762. var data = args[0];
  12763. var handler = args[1];
  12764. this.on(params.event, data, handler);
  12765. }
  12766. // e.g. cy.nodes().select( handler )
  12767. else if (args.length === 1 && fn$6(args[0])) {
  12768. var _handler = args[0];
  12769. this.on(params.event, _handler);
  12770. }
  12771. // e.g. cy.nodes().select()
  12772. // e.g. (private) cy.nodes().select(['tapselect'])
  12773. else if (args.length === 0 || args.length === 1 && array(args[0])) {
  12774. var addlEvents = args.length === 1 ? args[0] : null;
  12775. for (var i = 0; i < this.length; i++) {
  12776. var ele = this[i];
  12777. var able = !params.ableField || ele._private[params.ableField];
  12778. var changed = ele._private[params.field] != params.value;
  12779. if (params.overrideAble) {
  12780. var overrideAble = params.overrideAble(ele);
  12781. if (overrideAble !== undefined) {
  12782. able = overrideAble;
  12783. if (!overrideAble) {
  12784. return this;
  12785. } // to save cycles assume not able for all on override
  12786. }
  12787. }
  12788. if (able) {
  12789. ele._private[params.field] = params.value;
  12790. if (changed) {
  12791. changedEles.push(ele);
  12792. }
  12793. }
  12794. }
  12795. var changedColl = this.spawn(changedEles);
  12796. changedColl.updateStyle(); // change of state => possible change of style
  12797. changedColl.emit(params.event);
  12798. if (addlEvents) {
  12799. changedColl.emit(addlEvents);
  12800. }
  12801. }
  12802. return this;
  12803. };
  12804. }
  12805. function defineSwitchSet(params) {
  12806. elesfn$3[params.field] = function () {
  12807. var ele = this[0];
  12808. if (ele) {
  12809. if (params.overrideField) {
  12810. var val = params.overrideField(ele);
  12811. if (val !== undefined) {
  12812. return val;
  12813. }
  12814. }
  12815. return ele._private[params.field];
  12816. }
  12817. };
  12818. elesfn$3[params.on] = defineSwitchFunction({
  12819. event: params.on,
  12820. field: params.field,
  12821. ableField: params.ableField,
  12822. overrideAble: params.overrideAble,
  12823. value: true
  12824. });
  12825. elesfn$3[params.off] = defineSwitchFunction({
  12826. event: params.off,
  12827. field: params.field,
  12828. ableField: params.ableField,
  12829. overrideAble: params.overrideAble,
  12830. value: false
  12831. });
  12832. }
  12833. defineSwitchSet({
  12834. field: 'locked',
  12835. overrideField: function overrideField(ele) {
  12836. return ele.cy().autolock() ? true : undefined;
  12837. },
  12838. on: 'lock',
  12839. off: 'unlock'
  12840. });
  12841. defineSwitchSet({
  12842. field: 'grabbable',
  12843. overrideField: function overrideField(ele) {
  12844. return ele.cy().autoungrabify() || ele.pannable() ? false : undefined;
  12845. },
  12846. on: 'grabify',
  12847. off: 'ungrabify'
  12848. });
  12849. defineSwitchSet({
  12850. field: 'selected',
  12851. ableField: 'selectable',
  12852. overrideAble: function overrideAble(ele) {
  12853. return ele.cy().autounselectify() ? false : undefined;
  12854. },
  12855. on: 'select',
  12856. off: 'unselect'
  12857. });
  12858. defineSwitchSet({
  12859. field: 'selectable',
  12860. overrideField: function overrideField(ele) {
  12861. return ele.cy().autounselectify() ? false : undefined;
  12862. },
  12863. on: 'selectify',
  12864. off: 'unselectify'
  12865. });
  12866. elesfn$3.deselect = elesfn$3.unselect;
  12867. elesfn$3.grabbed = function () {
  12868. var ele = this[0];
  12869. if (ele) {
  12870. return ele._private.grabbed;
  12871. }
  12872. };
  12873. defineSwitchSet({
  12874. field: 'active',
  12875. on: 'activate',
  12876. off: 'unactivate'
  12877. });
  12878. defineSwitchSet({
  12879. field: 'pannable',
  12880. on: 'panify',
  12881. off: 'unpanify'
  12882. });
  12883. elesfn$3.inactive = function () {
  12884. var ele = this[0];
  12885. if (ele) {
  12886. return !ele._private.active;
  12887. }
  12888. };
  12889. var elesfn$2 = {};
  12890. // DAG functions
  12891. ////////////////
  12892. var defineDagExtremity = function defineDagExtremity(params) {
  12893. return function dagExtremityImpl(selector) {
  12894. var eles = this;
  12895. var ret = [];
  12896. for (var i = 0; i < eles.length; i++) {
  12897. var ele = eles[i];
  12898. if (!ele.isNode()) {
  12899. continue;
  12900. }
  12901. var disqualified = false;
  12902. var edges = ele.connectedEdges();
  12903. for (var j = 0; j < edges.length; j++) {
  12904. var edge = edges[j];
  12905. var src = edge.source();
  12906. var tgt = edge.target();
  12907. if (params.noIncomingEdges && tgt === ele && src !== ele || params.noOutgoingEdges && src === ele && tgt !== ele) {
  12908. disqualified = true;
  12909. break;
  12910. }
  12911. }
  12912. if (!disqualified) {
  12913. ret.push(ele);
  12914. }
  12915. }
  12916. return this.spawn(ret, true).filter(selector);
  12917. };
  12918. };
  12919. var defineDagOneHop = function defineDagOneHop(params) {
  12920. return function (selector) {
  12921. var eles = this;
  12922. var oEles = [];
  12923. for (var i = 0; i < eles.length; i++) {
  12924. var ele = eles[i];
  12925. if (!ele.isNode()) {
  12926. continue;
  12927. }
  12928. var edges = ele.connectedEdges();
  12929. for (var j = 0; j < edges.length; j++) {
  12930. var edge = edges[j];
  12931. var src = edge.source();
  12932. var tgt = edge.target();
  12933. if (params.outgoing && src === ele) {
  12934. oEles.push(edge);
  12935. oEles.push(tgt);
  12936. } else if (params.incoming && tgt === ele) {
  12937. oEles.push(edge);
  12938. oEles.push(src);
  12939. }
  12940. }
  12941. }
  12942. return this.spawn(oEles, true).filter(selector);
  12943. };
  12944. };
  12945. var defineDagAllHops = function defineDagAllHops(params) {
  12946. return function (selector) {
  12947. var eles = this;
  12948. var sEles = [];
  12949. var sElesIds = {};
  12950. for (;;) {
  12951. var next = params.outgoing ? eles.outgoers() : eles.incomers();
  12952. if (next.length === 0) {
  12953. break;
  12954. } // done if none left
  12955. var newNext = false;
  12956. for (var i = 0; i < next.length; i++) {
  12957. var n = next[i];
  12958. var nid = n.id();
  12959. if (!sElesIds[nid]) {
  12960. sElesIds[nid] = true;
  12961. sEles.push(n);
  12962. newNext = true;
  12963. }
  12964. }
  12965. if (!newNext) {
  12966. break;
  12967. } // done if touched all outgoers already
  12968. eles = next;
  12969. }
  12970. return this.spawn(sEles, true).filter(selector);
  12971. };
  12972. };
  12973. elesfn$2.clearTraversalCache = function () {
  12974. for (var i = 0; i < this.length; i++) {
  12975. this[i]._private.traversalCache = null;
  12976. }
  12977. };
  12978. extend(elesfn$2, {
  12979. // get the root nodes in the DAG
  12980. roots: defineDagExtremity({
  12981. noIncomingEdges: true
  12982. }),
  12983. // get the leaf nodes in the DAG
  12984. leaves: defineDagExtremity({
  12985. noOutgoingEdges: true
  12986. }),
  12987. // normally called children in graph theory
  12988. // these nodes =edges=> outgoing nodes
  12989. outgoers: cache(defineDagOneHop({
  12990. outgoing: true
  12991. }), 'outgoers'),
  12992. // aka DAG descendants
  12993. successors: defineDagAllHops({
  12994. outgoing: true
  12995. }),
  12996. // normally called parents in graph theory
  12997. // these nodes <=edges= incoming nodes
  12998. incomers: cache(defineDagOneHop({
  12999. incoming: true
  13000. }), 'incomers'),
  13001. // aka DAG ancestors
  13002. predecessors: defineDagAllHops({
  13003. })
  13004. });
  13005. // Neighbourhood functions
  13006. //////////////////////////
  13007. extend(elesfn$2, {
  13008. neighborhood: cache(function (selector) {
  13009. var elements = [];
  13010. var nodes = this.nodes();
  13011. for (var i = 0; i < nodes.length; i++) {
  13012. // for all nodes
  13013. var node = nodes[i];
  13014. var connectedEdges = node.connectedEdges();
  13015. // for each connected edge, add the edge and the other node
  13016. for (var j = 0; j < connectedEdges.length; j++) {
  13017. var edge = connectedEdges[j];
  13018. var src = edge.source();
  13019. var tgt = edge.target();
  13020. var otherNode = node === src ? tgt : src;
  13021. // need check in case of loop
  13022. if (otherNode.length > 0) {
  13023. elements.push(otherNode[0]); // add node 1 hop away
  13024. }
  13025. // add connected edge
  13026. elements.push(edge[0]);
  13027. }
  13028. }
  13029. return this.spawn(elements, true).filter(selector);
  13030. }, 'neighborhood'),
  13031. closedNeighborhood: function closedNeighborhood(selector) {
  13032. return this.neighborhood().add(this).filter(selector);
  13033. },
  13034. openNeighborhood: function openNeighborhood(selector) {
  13035. return this.neighborhood(selector);
  13036. }
  13037. });
  13038. // aliases
  13039. elesfn$2.neighbourhood = elesfn$2.neighborhood;
  13040. elesfn$2.closedNeighbourhood = elesfn$2.closedNeighborhood;
  13041. elesfn$2.openNeighbourhood = elesfn$2.openNeighborhood;
  13042. // Edge functions
  13043. /////////////////
  13044. extend(elesfn$2, {
  13045. source: cache(function sourceImpl(selector) {
  13046. var ele = this[0];
  13047. var src;
  13048. if (ele) {
  13049. src = ele._private.source || ele.cy().collection();
  13050. }
  13051. return src && selector ? src.filter(selector) : src;
  13052. }, 'source'),
  13053. target: cache(function targetImpl(selector) {
  13054. var ele = this[0];
  13055. var tgt;
  13056. if (ele) {
  13057. tgt = ele._private.target || ele.cy().collection();
  13058. }
  13059. return tgt && selector ? tgt.filter(selector) : tgt;
  13060. }, 'target'),
  13061. sources: defineSourceFunction({
  13062. attr: 'source'
  13063. }),
  13064. targets: defineSourceFunction({
  13065. attr: 'target'
  13066. })
  13067. });
  13068. function defineSourceFunction(params) {
  13069. return function sourceImpl(selector) {
  13070. var sources = [];
  13071. for (var i = 0; i < this.length; i++) {
  13072. var ele = this[i];
  13073. var src = ele._private[params.attr];
  13074. if (src) {
  13075. sources.push(src);
  13076. }
  13077. }
  13078. return this.spawn(sources, true).filter(selector);
  13079. };
  13080. }
  13081. extend(elesfn$2, {
  13082. edgesWith: cache(defineEdgesWithFunction(), 'edgesWith'),
  13083. edgesTo: cache(defineEdgesWithFunction({
  13084. thisIsSrc: true
  13085. }), 'edgesTo')
  13086. });
  13087. function defineEdgesWithFunction(params) {
  13088. return function edgesWithImpl(otherNodes) {
  13089. var elements = [];
  13090. var cy = this._private.cy;
  13091. var p = params || {};
  13092. // get elements if a selector is specified
  13093. if (string(otherNodes)) {
  13094. otherNodes = cy.$(otherNodes);
  13095. }
  13096. for (var h = 0; h < otherNodes.length; h++) {
  13097. var edges = otherNodes[h]._private.edges;
  13098. for (var i = 0; i < edges.length; i++) {
  13099. var edge = edges[i];
  13100. var edgeData = edge._private.data;
  13101. var thisToOther = this.hasElementWithId(edgeData.source) && otherNodes.hasElementWithId(edgeData.target);
  13102. var otherToThis = otherNodes.hasElementWithId(edgeData.source) && this.hasElementWithId(edgeData.target);
  13103. var edgeConnectsThisAndOther = thisToOther || otherToThis;
  13104. if (!edgeConnectsThisAndOther) {
  13105. continue;
  13106. }
  13107. if (p.thisIsSrc || p.thisIsTgt) {
  13108. if (p.thisIsSrc && !thisToOther) {
  13109. continue;
  13110. }
  13111. if (p.thisIsTgt && !otherToThis) {
  13112. continue;
  13113. }
  13114. }
  13115. elements.push(edge);
  13116. }
  13117. }
  13118. return this.spawn(elements, true);
  13119. };
  13120. }
  13121. extend(elesfn$2, {
  13122. connectedEdges: cache(function (selector) {
  13123. var retEles = [];
  13124. var eles = this;
  13125. for (var i = 0; i < eles.length; i++) {
  13126. var node = eles[i];
  13127. if (!node.isNode()) {
  13128. continue;
  13129. }
  13130. var edges = node._private.edges;
  13131. for (var j = 0; j < edges.length; j++) {
  13132. var edge = edges[j];
  13133. retEles.push(edge);
  13134. }
  13135. }
  13136. return this.spawn(retEles, true).filter(selector);
  13137. }, 'connectedEdges'),
  13138. connectedNodes: cache(function (selector) {
  13139. var retEles = [];
  13140. var eles = this;
  13141. for (var i = 0; i < eles.length; i++) {
  13142. var edge = eles[i];
  13143. if (!edge.isEdge()) {
  13144. continue;
  13145. }
  13146. retEles.push(edge.source()[0]);
  13147. retEles.push(edge.target()[0]);
  13148. }
  13149. return this.spawn(retEles, true).filter(selector);
  13150. }, 'connectedNodes'),
  13151. parallelEdges: cache(defineParallelEdgesFunction(), 'parallelEdges'),
  13152. codirectedEdges: cache(defineParallelEdgesFunction({
  13153. codirected: true
  13154. }), 'codirectedEdges')
  13155. });
  13156. function defineParallelEdgesFunction(params) {
  13157. var defaults = {
  13158. codirected: false
  13159. };
  13160. params = extend({}, defaults, params);
  13161. return function parallelEdgesImpl(selector) {
  13162. // micro-optimised for renderer
  13163. var elements = [];
  13164. var edges = this.edges();
  13165. var p = params;
  13166. // look at all the edges in the collection
  13167. for (var i = 0; i < edges.length; i++) {
  13168. var edge1 = edges[i];
  13169. var edge1_p = edge1._private;
  13170. var src1 = edge1_p.source;
  13171. var srcid1 = src1._private.data.id;
  13172. var tgtid1 = edge1_p.data.target;
  13173. var srcEdges1 = src1._private.edges;
  13174. // look at edges connected to the src node of this edge
  13175. for (var j = 0; j < srcEdges1.length; j++) {
  13176. var edge2 = srcEdges1[j];
  13177. var edge2data = edge2._private.data;
  13178. var tgtid2 = edge2data.target;
  13179. var srcid2 = edge2data.source;
  13180. var codirected = tgtid2 === tgtid1 && srcid2 === srcid1;
  13181. var oppdirected = srcid1 === tgtid2 && tgtid1 === srcid2;
  13182. if (p.codirected && codirected || !p.codirected && (codirected || oppdirected)) {
  13183. elements.push(edge2);
  13184. }
  13185. }
  13186. }
  13187. return this.spawn(elements, true).filter(selector);
  13188. };
  13189. }
  13190. // Misc functions
  13191. /////////////////
  13192. extend(elesfn$2, {
  13193. components: function components(root) {
  13194. var self = this;
  13195. var cy = self.cy();
  13196. var visited = cy.collection();
  13197. var unvisited = root == null ? self.nodes() : root.nodes();
  13198. var components = [];
  13199. if (root != null && unvisited.empty()) {
  13200. // root may contain only edges
  13201. unvisited = root.sources(); // doesn't matter which node to use (undirected), so just use the source sides
  13202. }
  13203. var visitInComponent = function visitInComponent(node, component) {
  13204. visited.merge(node);
  13205. unvisited.unmerge(node);
  13206. component.merge(node);
  13207. };
  13208. if (unvisited.empty()) {
  13209. return self.spawn();
  13210. }
  13211. var _loop = function _loop() {
  13212. // each iteration yields a component
  13213. var cmpt = cy.collection();
  13214. components.push(cmpt);
  13215. var root = unvisited[0];
  13216. visitInComponent(root, cmpt);
  13217. self.bfs({
  13218. directed: false,
  13219. roots: root,
  13220. visit: function visit(v) {
  13221. return visitInComponent(v, cmpt);
  13222. }
  13223. });
  13224. cmpt.forEach(function (node) {
  13225. node.connectedEdges().forEach(function (e) {
  13226. // connectedEdges() usually cached
  13227. if (self.has(e) && cmpt.has(e.source()) && cmpt.has(e.target())) {
  13228. // has() is cheap
  13229. cmpt.merge(e); // forEach() only considers nodes -- sets N at call time
  13230. }
  13231. });
  13232. });
  13233. };
  13234. do {
  13235. _loop();
  13236. } while (unvisited.length > 0);
  13237. return components;
  13238. },
  13239. component: function component() {
  13240. var ele = this[0];
  13241. return ele.cy().mutableElements().components(ele)[0];
  13242. }
  13243. });
  13244. elesfn$2.componentsOf = elesfn$2.components;
  13245. // represents a set of nodes, edges, or both together
  13246. var Collection = function Collection(cy, elements) {
  13247. var unique = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  13248. var removed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  13249. if (cy === undefined) {
  13250. error('A collection must have a reference to the core');
  13251. return;
  13252. }
  13253. var map = new Map$1();
  13254. var createdElements = false;
  13255. if (!elements) {
  13256. elements = [];
  13257. } else if (elements.length > 0 && plainObject(elements[0]) && !element(elements[0])) {
  13258. createdElements = true;
  13259. // make elements from json and restore all at once later
  13260. var eles = [];
  13261. var elesIds = new Set$1();
  13262. for (var i = 0, l = elements.length; i < l; i++) {
  13263. var json = elements[i];
  13264. if (json.data == null) {
  13265. json.data = {};
  13266. }
  13267. var _data = json.data;
  13268. // make sure newly created elements have valid ids
  13269. if (_data.id == null) {
  13270. _data.id = uuid();
  13271. } else if (cy.hasElementWithId(_data.id) || elesIds.has(_data.id)) {
  13272. continue; // can't create element if prior id already exists
  13273. }
  13274. var ele = new Element(cy, json, false);
  13275. eles.push(ele);
  13276. elesIds.add(_data.id);
  13277. }
  13278. elements = eles;
  13279. }
  13280. this.length = 0;
  13281. for (var _i = 0, _l = elements.length; _i < _l; _i++) {
  13282. var element$1 = elements[_i][0]; // [0] in case elements is an array of collections, rather than array of elements
  13283. if (element$1 == null) {
  13284. continue;
  13285. }
  13286. var id = element$1._private.data.id;
  13287. if (!unique || !map.has(id)) {
  13288. if (unique) {
  13289. map.set(id, {
  13290. index: this.length,
  13291. ele: element$1
  13292. });
  13293. }
  13294. this[this.length] = element$1;
  13295. this.length++;
  13296. }
  13297. }
  13298. this._private = {
  13299. eles: this,
  13300. cy: cy,
  13301. get map() {
  13302. if (this.lazyMap == null) {
  13303. this.rebuildMap();
  13304. }
  13305. return this.lazyMap;
  13306. },
  13307. set map(m) {
  13308. this.lazyMap = m;
  13309. },
  13310. rebuildMap: function rebuildMap() {
  13311. var m = this.lazyMap = new Map$1();
  13312. var eles = this.eles;
  13313. for (var _i2 = 0; _i2 < eles.length; _i2++) {
  13314. var _ele = eles[_i2];
  13315. m.set(_ele.id(), {
  13316. index: _i2,
  13317. ele: _ele
  13318. });
  13319. }
  13320. }
  13321. };
  13322. if (unique) {
  13323. this._private.map = map;
  13324. }
  13325. // restore the elements if we created them from json
  13326. if (createdElements && !removed) {
  13327. this.restore();
  13328. }
  13329. };
  13330. // Functions
  13331. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13332. // keep the prototypes in sync (an element has the same functions as a collection)
  13333. // and use elefn and elesfn as shorthands to the prototypes
  13334. var elesfn$1 = Element.prototype = Collection.prototype = Object.create(Array.prototype);
  13335. elesfn$1.instanceString = function () {
  13336. return 'collection';
  13337. };
  13338. elesfn$1.spawn = function (eles, unique) {
  13339. return new Collection(this.cy(), eles, unique);
  13340. };
  13341. elesfn$1.spawnSelf = function () {
  13342. return this.spawn(this);
  13343. };
  13344. elesfn$1.cy = function () {
  13345. return this._private.cy;
  13346. };
  13347. elesfn$1.renderer = function () {
  13348. return this._private.cy.renderer();
  13349. };
  13350. elesfn$1.element = function () {
  13351. return this[0];
  13352. };
  13353. elesfn$1.collection = function () {
  13354. if (collection(this)) {
  13355. return this;
  13356. } else {
  13357. // an element
  13358. return new Collection(this._private.cy, [this]);
  13359. }
  13360. };
  13361. elesfn$1.unique = function () {
  13362. return new Collection(this._private.cy, this, true);
  13363. };
  13364. elesfn$1.hasElementWithId = function (id) {
  13365. id = '' + id; // id must be string
  13366. return this._private.map.has(id);
  13367. };
  13368. elesfn$1.getElementById = function (id) {
  13369. id = '' + id; // id must be string
  13370. var cy = this._private.cy;
  13371. var entry = this._private.map.get(id);
  13372. return entry ? entry.ele : new Collection(cy); // get ele or empty collection
  13373. };
  13374. elesfn$1.$id = elesfn$1.getElementById;
  13375. elesfn$1.poolIndex = function () {
  13376. var cy = this._private.cy;
  13377. var eles = cy._private.elements;
  13378. var id = this[0]._private.data.id;
  13379. return eles._private.map.get(id).index;
  13380. };
  13381. elesfn$1.indexOf = function (ele) {
  13382. var id = ele[0]._private.data.id;
  13383. return this._private.map.get(id).index;
  13384. };
  13385. elesfn$1.indexOfId = function (id) {
  13386. id = '' + id; // id must be string
  13387. return this._private.map.get(id).index;
  13388. };
  13389. elesfn$1.json = function (obj) {
  13390. var ele = this.element();
  13391. var cy = this.cy();
  13392. if (ele == null && obj) {
  13393. return this;
  13394. } // can't set to no eles
  13395. if (ele == null) {
  13396. return undefined;
  13397. } // can't get from no eles
  13398. var p = ele._private;
  13399. if (plainObject(obj)) {
  13400. // set
  13401. cy.startBatch();
  13402. if (obj.data) {
  13403. ele.data(obj.data);
  13404. var _data2 = p.data;
  13405. if (ele.isEdge()) {
  13406. // source and target are immutable via data()
  13407. var move = false;
  13408. var spec = {};
  13409. var src = obj.data.source;
  13410. var tgt = obj.data.target;
  13411. if (src != null && src != _data2.source) {
  13412. spec.source = '' + src; // id must be string
  13413. move = true;
  13414. }
  13415. if (tgt != null && tgt != _data2.target) {
  13416. spec.target = '' + tgt; // id must be string
  13417. move = true;
  13418. }
  13419. if (move) {
  13420. ele = ele.move(spec);
  13421. }
  13422. } else {
  13423. // parent is immutable via data()
  13424. var newParentValSpecd = 'parent' in obj.data;
  13425. var parent = obj.data.parent;
  13426. if (newParentValSpecd && (parent != null || _data2.parent != null) && parent != _data2.parent) {
  13427. if (parent === undefined) {
  13428. // can't set undefined imperatively, so use null
  13429. parent = null;
  13430. }
  13431. if (parent != null) {
  13432. parent = '' + parent; // id must be string
  13433. }
  13434. ele = ele.move({
  13435. parent: parent
  13436. });
  13437. }
  13438. }
  13439. }
  13440. if (obj.position) {
  13441. ele.position(obj.position);
  13442. }
  13443. // ignore group -- immutable
  13444. var checkSwitch = function checkSwitch(k, trueFnName, falseFnName) {
  13445. var obj_k = obj[k];
  13446. if (obj_k != null && obj_k !== p[k]) {
  13447. if (obj_k) {
  13448. ele[trueFnName]();
  13449. } else {
  13450. ele[falseFnName]();
  13451. }
  13452. }
  13453. };
  13454. checkSwitch('removed', 'remove', 'restore');
  13455. checkSwitch('selected', 'select', 'unselect');
  13456. checkSwitch('selectable', 'selectify', 'unselectify');
  13457. checkSwitch('locked', 'lock', 'unlock');
  13458. checkSwitch('grabbable', 'grabify', 'ungrabify');
  13459. checkSwitch('pannable', 'panify', 'unpanify');
  13460. if (obj.classes != null) {
  13461. ele.classes(obj.classes);
  13462. }
  13463. cy.endBatch();
  13464. return this;
  13465. } else if (obj === undefined) {
  13466. // get
  13467. var json = {
  13468. data: copy(p.data),
  13469. position: copy(p.position),
  13470. group: p.group,
  13471. removed: p.removed,
  13472. selected: p.selected,
  13473. selectable: p.selectable,
  13474. locked: p.locked,
  13475. grabbable: p.grabbable,
  13476. pannable: p.pannable,
  13477. classes: null
  13478. };
  13479. json.classes = '';
  13480. var i = 0;
  13481. p.classes.forEach(function (cls) {
  13482. return json.classes += i++ === 0 ? cls : ' ' + cls;
  13483. });
  13484. return json;
  13485. }
  13486. };
  13487. elesfn$1.jsons = function () {
  13488. var jsons = [];
  13489. for (var i = 0; i < this.length; i++) {
  13490. var ele = this[i];
  13491. var json = ele.json();
  13492. jsons.push(json);
  13493. }
  13494. return jsons;
  13495. };
  13496. elesfn$1.clone = function () {
  13497. var cy = this.cy();
  13498. var elesArr = [];
  13499. for (var i = 0; i < this.length; i++) {
  13500. var ele = this[i];
  13501. var json = ele.json();
  13502. var clone = new Element(cy, json, false); // NB no restore
  13503. elesArr.push(clone);
  13504. }
  13505. return new Collection(cy, elesArr);
  13506. };
  13507. elesfn$1.copy = elesfn$1.clone;
  13508. elesfn$1.restore = function () {
  13509. var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  13510. var addToPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  13511. var self = this;
  13512. var cy = self.cy();
  13513. var cy_p = cy._private;
  13514. // create arrays of nodes and edges, since we need to
  13515. // restore the nodes first
  13516. var nodes = [];
  13517. var edges = [];
  13518. var elements;
  13519. for (var _i3 = 0, l = self.length; _i3 < l; _i3++) {
  13520. var ele = self[_i3];
  13521. if (addToPool && !ele.removed()) {
  13522. // don't need to handle this ele
  13523. continue;
  13524. }
  13525. // keep nodes first in the array and edges after
  13526. if (ele.isNode()) {
  13527. // put to front of array if node
  13528. nodes.push(ele);
  13529. } else {
  13530. // put to end of array if edge
  13531. edges.push(ele);
  13532. }
  13533. }
  13534. elements = nodes.concat(edges);
  13535. var i;
  13536. var removeFromElements = function removeFromElements() {
  13537. elements.splice(i, 1);
  13538. i--;
  13539. };
  13540. // now, restore each element
  13541. for (i = 0; i < elements.length; i++) {
  13542. var _ele2 = elements[i];
  13543. var _private = _ele2._private;
  13544. var _data3 = _private.data;
  13545. // the traversal cache should start fresh when ele is added
  13546. _ele2.clearTraversalCache();
  13547. // set id and validate
  13548. if (!addToPool && !_private.removed) ; else if (_data3.id === undefined) {
  13549. _data3.id = uuid();
  13550. } else if (number$1(_data3.id)) {
  13551. _data3.id = '' + _data3.id; // now it's a string
  13552. } else if (emptyString(_data3.id) || !string(_data3.id)) {
  13553. error('Can not create element with invalid string ID `' + _data3.id + '`');
  13554. // can't create element if it has empty string as id or non-string id
  13555. removeFromElements();
  13556. continue;
  13557. } else if (cy.hasElementWithId(_data3.id)) {
  13558. error('Can not create second element with ID `' + _data3.id + '`');
  13559. // can't create element if one already has that id
  13560. removeFromElements();
  13561. continue;
  13562. }
  13563. var id = _data3.id; // id is finalised, now let's keep a ref
  13564. if (_ele2.isNode()) {
  13565. // extra checks for nodes
  13566. var pos = _private.position;
  13567. // make sure the nodes have a defined position
  13568. if (pos.x == null) {
  13569. pos.x = 0;
  13570. }
  13571. if (pos.y == null) {
  13572. pos.y = 0;
  13573. }
  13574. }
  13575. if (_ele2.isEdge()) {
  13576. // extra checks for edges
  13577. var edge = _ele2;
  13578. var fields = ['source', 'target'];
  13579. var fieldsLength = fields.length;
  13580. var badSourceOrTarget = false;
  13581. for (var j = 0; j < fieldsLength; j++) {
  13582. var field = fields[j];
  13583. var val = _data3[field];
  13584. if (number$1(val)) {
  13585. val = _data3[field] = '' + _data3[field]; // now string
  13586. }
  13587. if (val == null || val === '') {
  13588. // can't create if source or target is not defined properly
  13589. error('Can not create edge `' + id + '` with unspecified ' + field);
  13590. badSourceOrTarget = true;
  13591. } else if (!cy.hasElementWithId(val)) {
  13592. // can't create edge if one of its nodes doesn't exist
  13593. error('Can not create edge `' + id + '` with nonexistent ' + field + ' `' + val + '`');
  13594. badSourceOrTarget = true;
  13595. }
  13596. }
  13597. if (badSourceOrTarget) {
  13598. removeFromElements();
  13599. continue;
  13600. } // can't create this
  13601. var src = cy.getElementById(_data3.source);
  13602. var tgt = cy.getElementById(_data3.target);
  13603. // only one edge in node if loop
  13604. if (src.same(tgt)) {
  13605. src._private.edges.push(edge);
  13606. } else {
  13607. src._private.edges.push(edge);
  13608. tgt._private.edges.push(edge);
  13609. }
  13610. edge._private.source = src;
  13611. edge._private.target = tgt;
  13612. } // if is edge
  13613. // create mock ids / indexes maps for element so it can be used like collections
  13614. _private.map = new Map$1();
  13615. _private.map.set(id, {
  13616. ele: _ele2,
  13617. index: 0
  13618. });
  13619. _private.removed = false;
  13620. if (addToPool) {
  13621. cy.addToPool(_ele2);
  13622. }
  13623. } // for each element
  13624. // do compound node sanity checks
  13625. for (var _i4 = 0; _i4 < nodes.length; _i4++) {
  13626. // each node
  13627. var node = nodes[_i4];
  13628. var _data4 = node._private.data;
  13629. if (number$1(_data4.parent)) {
  13630. // then automake string
  13631. _data4.parent = '' + _data4.parent;
  13632. }
  13633. var parentId = _data4.parent;
  13634. var specifiedParent = parentId != null;
  13635. if (specifiedParent || node._private.parent) {
  13636. var parent = node._private.parent ? cy.collection().merge(node._private.parent) : cy.getElementById(parentId);
  13637. if (parent.empty()) {
  13638. // non-existant parent; just remove it
  13639. _data4.parent = undefined;
  13640. } else if (parent[0].removed()) {
  13641. warn('Node added with missing parent, reference to parent removed');
  13642. _data4.parent = undefined;
  13643. node._private.parent = null;
  13644. } else {
  13645. var selfAsParent = false;
  13646. var ancestor = parent;
  13647. while (!ancestor.empty()) {
  13648. if (node.same(ancestor)) {
  13649. // mark self as parent and remove from data
  13650. selfAsParent = true;
  13651. _data4.parent = undefined; // remove parent reference
  13652. // exit or we loop forever
  13653. break;
  13654. }
  13655. ancestor = ancestor.parent();
  13656. }
  13657. if (!selfAsParent) {
  13658. // connect with children
  13659. parent[0]._private.children.push(node);
  13660. node._private.parent = parent[0];
  13661. // let the core know we have a compound graph
  13662. cy_p.hasCompoundNodes = true;
  13663. }
  13664. } // else
  13665. } // if specified parent
  13666. } // for each node
  13667. if (elements.length > 0) {
  13668. var restored = elements.length === self.length ? self : new Collection(cy, elements);
  13669. for (var _i5 = 0; _i5 < restored.length; _i5++) {
  13670. var _ele3 = restored[_i5];
  13671. if (_ele3.isNode()) {
  13672. continue;
  13673. }
  13674. // adding an edge invalidates the traversal caches for the parallel edges
  13675. _ele3.parallelEdges().clearTraversalCache();
  13676. // adding an edge invalidates the traversal cache for the connected nodes
  13677. _ele3.source().clearTraversalCache();
  13678. _ele3.target().clearTraversalCache();
  13679. }
  13680. var toUpdateStyle;
  13681. if (cy_p.hasCompoundNodes) {
  13682. toUpdateStyle = cy.collection().merge(restored).merge(restored.connectedNodes()).merge(restored.parent());
  13683. } else {
  13684. toUpdateStyle = restored;
  13685. }
  13686. toUpdateStyle.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(notifyRenderer);
  13687. if (notifyRenderer) {
  13688. restored.emitAndNotify('add');
  13689. } else if (addToPool) {
  13690. restored.emit('add');
  13691. }
  13692. }
  13693. return self; // chainability
  13694. };
  13695. elesfn$1.removed = function () {
  13696. var ele = this[0];
  13697. return ele && ele._private.removed;
  13698. };
  13699. elesfn$1.inside = function () {
  13700. var ele = this[0];
  13701. return ele && !ele._private.removed;
  13702. };
  13703. elesfn$1.remove = function () {
  13704. var notifyRenderer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  13705. var removeFromPool = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  13706. var self = this;
  13707. var elesToRemove = [];
  13708. var elesToRemoveIds = {};
  13709. var cy = self._private.cy;
  13710. // add connected edges
  13711. function addConnectedEdges(node) {
  13712. var edges = node._private.edges;
  13713. for (var i = 0; i < edges.length; i++) {
  13714. add(edges[i]);
  13715. }
  13716. }
  13717. // add descendant nodes
  13718. function addChildren(node) {
  13719. var children = node._private.children;
  13720. for (var i = 0; i < children.length; i++) {
  13721. add(children[i]);
  13722. }
  13723. }
  13724. function add(ele) {
  13725. var alreadyAdded = elesToRemoveIds[ele.id()];
  13726. if (removeFromPool && ele.removed() || alreadyAdded) {
  13727. return;
  13728. } else {
  13729. elesToRemoveIds[ele.id()] = true;
  13730. }
  13731. if (ele.isNode()) {
  13732. elesToRemove.push(ele); // nodes are removed last
  13733. addConnectedEdges(ele);
  13734. addChildren(ele);
  13735. } else {
  13736. elesToRemove.unshift(ele); // edges are removed first
  13737. }
  13738. }
  13739. // make the list of elements to remove
  13740. // (may be removing more than specified due to connected edges etc)
  13741. for (var i = 0, l = self.length; i < l; i++) {
  13742. var ele = self[i];
  13743. add(ele);
  13744. }
  13745. function removeEdgeRef(node, edge) {
  13746. var connectedEdges = node._private.edges;
  13747. removeFromArray(connectedEdges, edge);
  13748. // removing an edges invalidates the traversal cache for its nodes
  13749. node.clearTraversalCache();
  13750. }
  13751. function removeParallelRef(pllEdge) {
  13752. // removing an edge invalidates the traversal caches for the parallel edges
  13753. pllEdge.clearTraversalCache();
  13754. }
  13755. var alteredParents = [];
  13756. alteredParents.ids = {};
  13757. function removeChildRef(parent, ele) {
  13758. ele = ele[0];
  13759. parent = parent[0];
  13760. var children = parent._private.children;
  13761. var pid = parent.id();
  13762. removeFromArray(children, ele); // remove parent => child ref
  13763. ele._private.parent = null; // remove child => parent ref
  13764. if (!alteredParents.ids[pid]) {
  13765. alteredParents.ids[pid] = true;
  13766. alteredParents.push(parent);
  13767. }
  13768. }
  13769. self.dirtyCompoundBoundsCache();
  13770. if (removeFromPool) {
  13771. cy.removeFromPool(elesToRemove); // remove from core pool
  13772. }
  13773. for (var _i6 = 0; _i6 < elesToRemove.length; _i6++) {
  13774. var _ele4 = elesToRemove[_i6];
  13775. if (_ele4.isEdge()) {
  13776. // remove references to this edge in its connected nodes
  13777. var src = _ele4.source()[0];
  13778. var tgt = _ele4.target()[0];
  13779. removeEdgeRef(src, _ele4);
  13780. removeEdgeRef(tgt, _ele4);
  13781. var pllEdges = _ele4.parallelEdges();
  13782. for (var j = 0; j < pllEdges.length; j++) {
  13783. var pllEdge = pllEdges[j];
  13784. removeParallelRef(pllEdge);
  13785. if (pllEdge.isBundledBezier()) {
  13786. pllEdge.dirtyBoundingBoxCache();
  13787. }
  13788. }
  13789. } else {
  13790. // remove reference to parent
  13791. var parent = _ele4.parent();
  13792. if (parent.length !== 0) {
  13793. removeChildRef(parent, _ele4);
  13794. }
  13795. }
  13796. if (removeFromPool) {
  13797. // mark as removed
  13798. _ele4._private.removed = true;
  13799. }
  13800. }
  13801. // check to see if we have a compound graph or not
  13802. var elesStillInside = cy._private.elements;
  13803. cy._private.hasCompoundNodes = false;
  13804. for (var _i7 = 0; _i7 < elesStillInside.length; _i7++) {
  13805. var _ele5 = elesStillInside[_i7];
  13806. if (_ele5.isParent()) {
  13807. cy._private.hasCompoundNodes = true;
  13808. break;
  13809. }
  13810. }
  13811. var removedElements = new Collection(this.cy(), elesToRemove);
  13812. if (removedElements.size() > 0) {
  13813. // must manually notify since trigger won't do this automatically once removed
  13814. if (notifyRenderer) {
  13815. removedElements.emitAndNotify('remove');
  13816. } else if (removeFromPool) {
  13817. removedElements.emit('remove');
  13818. }
  13819. }
  13820. // the parents who were modified by the removal need their style updated
  13821. for (var _i8 = 0; _i8 < alteredParents.length; _i8++) {
  13822. var _ele6 = alteredParents[_i8];
  13823. if (!removeFromPool || !_ele6.removed()) {
  13824. _ele6.updateStyle();
  13825. }
  13826. }
  13827. return removedElements;
  13828. };
  13829. elesfn$1.move = function (struct) {
  13830. var cy = this._private.cy;
  13831. var eles = this;
  13832. // just clean up refs, caches, etc. in the same way as when removing and then restoring
  13833. // (our calls to remove/restore do not remove from the graph or make events)
  13834. var notifyRenderer = false;
  13835. var modifyPool = false;
  13836. var toString = function toString(id) {
  13837. return id == null ? id : '' + id;
  13838. }; // id must be string
  13839. if (struct.source !== undefined || struct.target !== undefined) {
  13840. var srcId = toString(struct.source);
  13841. var tgtId = toString(struct.target);
  13842. var srcExists = srcId != null && cy.hasElementWithId(srcId);
  13843. var tgtExists = tgtId != null && cy.hasElementWithId(tgtId);
  13844. if (srcExists || tgtExists) {
  13845. cy.batch(function () {
  13846. // avoid duplicate style updates
  13847. eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
  13848. eles.emitAndNotify('moveout');
  13849. for (var i = 0; i < eles.length; i++) {
  13850. var ele = eles[i];
  13851. var _data5 = ele._private.data;
  13852. if (ele.isEdge()) {
  13853. if (srcExists) {
  13854. _data5.source = srcId;
  13855. }
  13856. if (tgtExists) {
  13857. _data5.target = tgtId;
  13858. }
  13859. }
  13860. }
  13861. eles.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
  13862. });
  13863. eles.emitAndNotify('move');
  13864. }
  13865. } else if (struct.parent !== undefined) {
  13866. // move node to new parent
  13867. var parentId = toString(struct.parent);
  13868. var parentExists = parentId === null || cy.hasElementWithId(parentId);
  13869. if (parentExists) {
  13870. var pidToAssign = parentId === null ? undefined : parentId;
  13871. cy.batch(function () {
  13872. // avoid duplicate style updates
  13873. var updated = eles.remove(notifyRenderer, modifyPool); // clean up refs etc.
  13874. updated.emitAndNotify('moveout');
  13875. for (var i = 0; i < eles.length; i++) {
  13876. var ele = eles[i];
  13877. var _data6 = ele._private.data;
  13878. if (ele.isNode()) {
  13879. _data6.parent = pidToAssign;
  13880. }
  13881. }
  13882. updated.restore(notifyRenderer, modifyPool); // make new refs, style, etc.
  13883. });
  13884. eles.emitAndNotify('move');
  13885. }
  13886. }
  13887. return this;
  13888. };
  13889. [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) {
  13890. extend(elesfn$1, props);
  13891. });
  13892. var corefn$9 = {
  13893. add: function add(opts) {
  13894. var elements;
  13895. var cy = this;
  13896. // add the elements
  13897. if (elementOrCollection(opts)) {
  13898. var eles = opts;
  13899. if (eles._private.cy === cy) {
  13900. // same instance => just restore
  13901. elements = eles.restore();
  13902. } else {
  13903. // otherwise, copy from json
  13904. var jsons = [];
  13905. for (var i = 0; i < eles.length; i++) {
  13906. var ele = eles[i];
  13907. jsons.push(ele.json());
  13908. }
  13909. elements = new Collection(cy, jsons);
  13910. }
  13911. }
  13912. // specify an array of options
  13913. else if (array(opts)) {
  13914. var _jsons = opts;
  13915. elements = new Collection(cy, _jsons);
  13916. }
  13917. // specify via opts.nodes and opts.edges
  13918. else if (plainObject(opts) && (array(opts.nodes) || array(opts.edges))) {
  13919. var elesByGroup = opts;
  13920. var _jsons2 = [];
  13921. var grs = ['nodes', 'edges'];
  13922. for (var _i = 0, il = grs.length; _i < il; _i++) {
  13923. var group = grs[_i];
  13924. var elesArray = elesByGroup[group];
  13925. if (array(elesArray)) {
  13926. for (var j = 0, jl = elesArray.length; j < jl; j++) {
  13927. var json = extend({
  13928. group: group
  13929. }, elesArray[j]);
  13930. _jsons2.push(json);
  13931. }
  13932. }
  13933. }
  13934. elements = new Collection(cy, _jsons2);
  13935. }
  13936. // specify options for one element
  13937. else {
  13938. var _json = opts;
  13939. elements = new Element(cy, _json).collection();
  13940. }
  13941. return elements;
  13942. },
  13943. remove: function remove(collection) {
  13944. if (elementOrCollection(collection)) ; else if (string(collection)) {
  13945. var selector = collection;
  13946. collection = this.$(selector);
  13947. }
  13948. return collection.remove();
  13949. }
  13950. };
  13951. /* global Float32Array */
  13952. /*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
  13953. function generateCubicBezier(mX1, mY1, mX2, mY2) {
  13954. var NEWTON_ITERATIONS = 4,
  13955. NEWTON_MIN_SLOPE = 0.001,
  13956. SUBDIVISION_PRECISION = 0.0000001,
  13957. SUBDIVISION_MAX_ITERATIONS = 10,
  13958. kSplineTableSize = 11,
  13959. kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
  13960. float32ArraySupported = typeof Float32Array !== 'undefined';
  13961. /* Must contain four arguments. */
  13962. if (arguments.length !== 4) {
  13963. return false;
  13964. }
  13965. /* Arguments must be numbers. */
  13966. for (var i = 0; i < 4; ++i) {
  13967. if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
  13968. return false;
  13969. }
  13970. }
  13971. /* X values must be in the [0, 1] range. */
  13972. mX1 = Math.min(mX1, 1);
  13973. mX2 = Math.min(mX2, 1);
  13974. mX1 = Math.max(mX1, 0);
  13975. mX2 = Math.max(mX2, 0);
  13976. var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  13977. function A(aA1, aA2) {
  13978. return 1.0 - 3.0 * aA2 + 3.0 * aA1;
  13979. }
  13980. function B(aA1, aA2) {
  13981. return 3.0 * aA2 - 6.0 * aA1;
  13982. }
  13983. function C(aA1) {
  13984. return 3.0 * aA1;
  13985. }
  13986. function calcBezier(aT, aA1, aA2) {
  13987. return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  13988. }
  13989. function getSlope(aT, aA1, aA2) {
  13990. return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  13991. }
  13992. function newtonRaphsonIterate(aX, aGuessT) {
  13993. for (var _i = 0; _i < NEWTON_ITERATIONS; ++_i) {
  13994. var currentSlope = getSlope(aGuessT, mX1, mX2);
  13995. if (currentSlope === 0.0) {
  13996. return aGuessT;
  13997. }
  13998. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  13999. aGuessT -= currentX / currentSlope;
  14000. }
  14001. return aGuessT;
  14002. }
  14003. function calcSampleValues() {
  14004. for (var _i2 = 0; _i2 < kSplineTableSize; ++_i2) {
  14005. mSampleValues[_i2] = calcBezier(_i2 * kSampleStepSize, mX1, mX2);
  14006. }
  14007. }
  14008. function binarySubdivide(aX, aA, aB) {
  14009. var currentX,
  14010. currentT,
  14011. i = 0;
  14012. do {
  14013. currentT = aA + (aB - aA) / 2.0;
  14014. currentX = calcBezier(currentT, mX1, mX2) - aX;
  14015. if (currentX > 0.0) {
  14016. aB = currentT;
  14017. } else {
  14018. aA = currentT;
  14019. }
  14020. } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
  14021. return currentT;
  14022. }
  14023. function getTForX(aX) {
  14024. var intervalStart = 0.0,
  14025. currentSample = 1,
  14026. lastSample = kSplineTableSize - 1;
  14027. for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
  14028. intervalStart += kSampleStepSize;
  14029. }
  14030. --currentSample;
  14031. var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]),
  14032. guessForT = intervalStart + dist * kSampleStepSize,
  14033. initialSlope = getSlope(guessForT, mX1, mX2);
  14034. if (initialSlope >= NEWTON_MIN_SLOPE) {
  14035. return newtonRaphsonIterate(aX, guessForT);
  14036. } else if (initialSlope === 0.0) {
  14037. return guessForT;
  14038. } else {
  14039. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
  14040. }
  14041. }
  14042. var _precomputed = false;
  14043. function precompute() {
  14044. _precomputed = true;
  14045. if (mX1 !== mY1 || mX2 !== mY2) {
  14046. calcSampleValues();
  14047. }
  14048. }
  14049. var f = function f(aX) {
  14050. if (!_precomputed) {
  14051. precompute();
  14052. }
  14053. if (mX1 === mY1 && mX2 === mY2) {
  14054. return aX;
  14055. }
  14056. if (aX === 0) {
  14057. return 0;
  14058. }
  14059. if (aX === 1) {
  14060. return 1;
  14061. }
  14062. return calcBezier(getTForX(aX), mY1, mY2);
  14063. };
  14064. f.getControlPoints = function () {
  14065. return [{
  14066. x: mX1,
  14067. y: mY1
  14068. }, {
  14069. x: mX2,
  14070. y: mY2
  14071. }];
  14072. };
  14073. var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
  14074. f.toString = function () {
  14075. return str;
  14076. };
  14077. return f;
  14078. }
  14079. /*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
  14080. /* 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
  14081. then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
  14082. var generateSpringRK4 = function () {
  14083. function springAccelerationForState(state) {
  14084. return -state.tension * state.x - state.friction * state.v;
  14085. }
  14086. function springEvaluateStateWithDerivative(initialState, dt, derivative) {
  14087. var state = {
  14088. x: initialState.x + derivative.dx * dt,
  14089. v: initialState.v + derivative.dv * dt,
  14090. tension: initialState.tension,
  14091. friction: initialState.friction
  14092. };
  14093. return {
  14094. dx: state.v,
  14095. dv: springAccelerationForState(state)
  14096. };
  14097. }
  14098. function springIntegrateState(state, dt) {
  14099. var a = {
  14100. dx: state.v,
  14101. dv: springAccelerationForState(state)
  14102. },
  14103. b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
  14104. c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
  14105. d = springEvaluateStateWithDerivative(state, dt, c),
  14106. dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
  14107. dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
  14108. state.x = state.x + dxdt * dt;
  14109. state.v = state.v + dvdt * dt;
  14110. return state;
  14111. }
  14112. return function springRK4Factory(tension, friction, duration) {
  14113. var initState = {
  14114. x: -1,
  14115. v: 0,
  14116. tension: null,
  14117. friction: null
  14118. },
  14119. path = [0],
  14120. time_lapsed = 0,
  14121. tolerance = 1 / 10000,
  14122. DT = 16 / 1000,
  14123. have_duration,
  14124. dt,
  14125. last_state;
  14126. tension = parseFloat(tension) || 500;
  14127. friction = parseFloat(friction) || 20;
  14128. duration = duration || null;
  14129. initState.tension = tension;
  14130. initState.friction = friction;
  14131. have_duration = duration !== null;
  14132. /* Calculate the actual time it takes for this animation to complete with the provided conditions. */
  14133. if (have_duration) {
  14134. /* Run the simulation without a duration. */
  14135. time_lapsed = springRK4Factory(tension, friction);
  14136. /* Compute the adjusted time delta. */
  14137. dt = time_lapsed / duration * DT;
  14138. } else {
  14139. dt = DT;
  14140. }
  14141. for (;;) {
  14142. /* Next/step function .*/
  14143. last_state = springIntegrateState(last_state || initState, dt);
  14144. /* Store the position. */
  14145. path.push(1 + last_state.x);
  14146. time_lapsed += 16;
  14147. /* If the change threshold is reached, break. */
  14148. if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
  14149. break;
  14150. }
  14151. }
  14152. /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
  14153. computed path and returns a snapshot of the position according to a given percentComplete. */
  14154. return !have_duration ? time_lapsed : function (percentComplete) {
  14155. return path[percentComplete * (path.length - 1) | 0];
  14156. };
  14157. };
  14158. }();
  14159. var cubicBezier = function cubicBezier(t1, p1, t2, p2) {
  14160. var bezier = generateCubicBezier(t1, p1, t2, p2);
  14161. return function (start, end, percent) {
  14162. return start + (end - start) * bezier(percent);
  14163. };
  14164. };
  14165. var easings = {
  14166. 'linear': function linear(start, end, percent) {
  14167. return start + (end - start) * percent;
  14168. },
  14169. // default easings
  14170. 'ease': cubicBezier(0.25, 0.1, 0.25, 1),
  14171. 'ease-in': cubicBezier(0.42, 0, 1, 1),
  14172. 'ease-out': cubicBezier(0, 0, 0.58, 1),
  14173. 'ease-in-out': cubicBezier(0.42, 0, 0.58, 1),
  14174. // sine
  14175. 'ease-in-sine': cubicBezier(0.47, 0, 0.745, 0.715),
  14176. 'ease-out-sine': cubicBezier(0.39, 0.575, 0.565, 1),
  14177. 'ease-in-out-sine': cubicBezier(0.445, 0.05, 0.55, 0.95),
  14178. // quad
  14179. 'ease-in-quad': cubicBezier(0.55, 0.085, 0.68, 0.53),
  14180. 'ease-out-quad': cubicBezier(0.25, 0.46, 0.45, 0.94),
  14181. 'ease-in-out-quad': cubicBezier(0.455, 0.03, 0.515, 0.955),
  14182. // cubic
  14183. 'ease-in-cubic': cubicBezier(0.55, 0.055, 0.675, 0.19),
  14184. 'ease-out-cubic': cubicBezier(0.215, 0.61, 0.355, 1),
  14185. 'ease-in-out-cubic': cubicBezier(0.645, 0.045, 0.355, 1),
  14186. // quart
  14187. 'ease-in-quart': cubicBezier(0.895, 0.03, 0.685, 0.22),
  14188. 'ease-out-quart': cubicBezier(0.165, 0.84, 0.44, 1),
  14189. 'ease-in-out-quart': cubicBezier(0.77, 0, 0.175, 1),
  14190. // quint
  14191. 'ease-in-quint': cubicBezier(0.755, 0.05, 0.855, 0.06),
  14192. 'ease-out-quint': cubicBezier(0.23, 1, 0.32, 1),
  14193. 'ease-in-out-quint': cubicBezier(0.86, 0, 0.07, 1),
  14194. // expo
  14195. 'ease-in-expo': cubicBezier(0.95, 0.05, 0.795, 0.035),
  14196. 'ease-out-expo': cubicBezier(0.19, 1, 0.22, 1),
  14197. 'ease-in-out-expo': cubicBezier(1, 0, 0, 1),
  14198. // circ
  14199. 'ease-in-circ': cubicBezier(0.6, 0.04, 0.98, 0.335),
  14200. 'ease-out-circ': cubicBezier(0.075, 0.82, 0.165, 1),
  14201. 'ease-in-out-circ': cubicBezier(0.785, 0.135, 0.15, 0.86),
  14202. // user param easings...
  14203. 'spring': function spring(tension, friction, duration) {
  14204. if (duration === 0) {
  14205. // can't get a spring w/ duration 0
  14206. return easings.linear; // duration 0 => jump to end so impl doesn't matter
  14207. }
  14208. var spring = generateSpringRK4(tension, friction, duration);
  14209. return function (start, end, percent) {
  14210. return start + (end - start) * spring(percent);
  14211. };
  14212. },
  14213. 'cubic-bezier': cubicBezier
  14214. };
  14215. function getEasedValue(type, start, end, percent, easingFn) {
  14216. if (percent === 1) {
  14217. return end;
  14218. }
  14219. if (start === end) {
  14220. return end;
  14221. }
  14222. var val = easingFn(start, end, percent);
  14223. if (type == null) {
  14224. return val;
  14225. }
  14226. if (type.roundValue || type.color) {
  14227. val = Math.round(val);
  14228. }
  14229. if (type.min !== undefined) {
  14230. val = Math.max(val, type.min);
  14231. }
  14232. if (type.max !== undefined) {
  14233. val = Math.min(val, type.max);
  14234. }
  14235. return val;
  14236. }
  14237. function getValue(prop, spec) {
  14238. if (prop.pfValue != null || prop.value != null) {
  14239. if (prop.pfValue != null && (spec == null || spec.type.units !== '%')) {
  14240. return prop.pfValue;
  14241. } else {
  14242. return prop.value;
  14243. }
  14244. } else {
  14245. return prop;
  14246. }
  14247. }
  14248. function ease(startProp, endProp, percent, easingFn, propSpec) {
  14249. var type = propSpec != null ? propSpec.type : null;
  14250. if (percent < 0) {
  14251. percent = 0;
  14252. } else if (percent > 1) {
  14253. percent = 1;
  14254. }
  14255. var start = getValue(startProp, propSpec);
  14256. var end = getValue(endProp, propSpec);
  14257. if (number$1(start) && number$1(end)) {
  14258. return getEasedValue(type, start, end, percent, easingFn);
  14259. } else if (array(start) && array(end)) {
  14260. var easedArr = [];
  14261. for (var i = 0; i < end.length; i++) {
  14262. var si = start[i];
  14263. var ei = end[i];
  14264. if (si != null && ei != null) {
  14265. var val = getEasedValue(type, si, ei, percent, easingFn);
  14266. easedArr.push(val);
  14267. } else {
  14268. easedArr.push(ei);
  14269. }
  14270. }
  14271. return easedArr;
  14272. }
  14273. return undefined;
  14274. }
  14275. function step$1(self, ani, now, isCore) {
  14276. var isEles = !isCore;
  14277. var _p = self._private;
  14278. var ani_p = ani._private;
  14279. var pEasing = ani_p.easing;
  14280. var startTime = ani_p.startTime;
  14281. var cy = isCore ? self : self.cy();
  14282. var style = cy.style();
  14283. if (!ani_p.easingImpl) {
  14284. if (pEasing == null) {
  14285. // use default
  14286. ani_p.easingImpl = easings['linear'];
  14287. } else {
  14288. // then define w/ name
  14289. var easingVals;
  14290. if (string(pEasing)) {
  14291. var easingProp = style.parse('transition-timing-function', pEasing);
  14292. easingVals = easingProp.value;
  14293. } else {
  14294. // then assume preparsed array
  14295. easingVals = pEasing;
  14296. }
  14297. var name, args;
  14298. if (string(easingVals)) {
  14299. name = easingVals;
  14300. args = [];
  14301. } else {
  14302. name = easingVals[1];
  14303. args = easingVals.slice(2).map(function (n) {
  14304. return +n;
  14305. });
  14306. }
  14307. if (args.length > 0) {
  14308. // create with args
  14309. if (name === 'spring') {
  14310. args.push(ani_p.duration); // need duration to generate spring
  14311. }
  14312. ani_p.easingImpl = easings[name].apply(null, args);
  14313. } else {
  14314. // static impl by name
  14315. ani_p.easingImpl = easings[name];
  14316. }
  14317. }
  14318. }
  14319. var easing = ani_p.easingImpl;
  14320. var percent;
  14321. if (ani_p.duration === 0) {
  14322. percent = 1;
  14323. } else {
  14324. percent = (now - startTime) / ani_p.duration;
  14325. }
  14326. if (ani_p.applying) {
  14327. percent = ani_p.progress;
  14328. }
  14329. if (percent < 0) {
  14330. percent = 0;
  14331. } else if (percent > 1) {
  14332. percent = 1;
  14333. }
  14334. if (ani_p.delay == null) {
  14335. // then update
  14336. var startPos = ani_p.startPosition;
  14337. var endPos = ani_p.position;
  14338. if (endPos && isEles && !self.locked()) {
  14339. var newPos = {};
  14340. if (valid(startPos.x, endPos.x)) {
  14341. newPos.x = ease(startPos.x, endPos.x, percent, easing);
  14342. }
  14343. if (valid(startPos.y, endPos.y)) {
  14344. newPos.y = ease(startPos.y, endPos.y, percent, easing);
  14345. }
  14346. self.position(newPos);
  14347. }
  14348. var startPan = ani_p.startPan;
  14349. var endPan = ani_p.pan;
  14350. var pan = _p.pan;
  14351. var animatingPan = endPan != null && isCore;
  14352. if (animatingPan) {
  14353. if (valid(startPan.x, endPan.x)) {
  14354. pan.x = ease(startPan.x, endPan.x, percent, easing);
  14355. }
  14356. if (valid(startPan.y, endPan.y)) {
  14357. pan.y = ease(startPan.y, endPan.y, percent, easing);
  14358. }
  14359. self.emit('pan');
  14360. }
  14361. var startZoom = ani_p.startZoom;
  14362. var endZoom = ani_p.zoom;
  14363. var animatingZoom = endZoom != null && isCore;
  14364. if (animatingZoom) {
  14365. if (valid(startZoom, endZoom)) {
  14366. _p.zoom = bound(_p.minZoom, ease(startZoom, endZoom, percent, easing), _p.maxZoom);
  14367. }
  14368. self.emit('zoom');
  14369. }
  14370. if (animatingPan || animatingZoom) {
  14371. self.emit('viewport');
  14372. }
  14373. var props = ani_p.style;
  14374. if (props && props.length > 0 && isEles) {
  14375. for (var i = 0; i < props.length; i++) {
  14376. var prop = props[i];
  14377. var _name = prop.name;
  14378. var end = prop;
  14379. var start = ani_p.startStyle[_name];
  14380. var propSpec = style.properties[start.name];
  14381. var easedVal = ease(start, end, percent, easing, propSpec);
  14382. style.overrideBypass(self, _name, easedVal);
  14383. } // for props
  14384. self.emit('style');
  14385. } // if
  14386. }
  14387. ani_p.progress = percent;
  14388. return percent;
  14389. }
  14390. function valid(start, end) {
  14391. if (start == null || end == null) {
  14392. return false;
  14393. }
  14394. if (number$1(start) && number$1(end)) {
  14395. return true;
  14396. } else if (start && end) {
  14397. return true;
  14398. }
  14399. return false;
  14400. }
  14401. function startAnimation(self, ani, now, isCore) {
  14402. var ani_p = ani._private;
  14403. ani_p.started = true;
  14404. ani_p.startTime = now - ani_p.progress * ani_p.duration;
  14405. }
  14406. function stepAll(now, cy) {
  14407. var eles = cy._private.aniEles;
  14408. var doneEles = [];
  14409. function stepOne(ele, isCore) {
  14410. var _p = ele._private;
  14411. var current = _p.animation.current;
  14412. var queue = _p.animation.queue;
  14413. var ranAnis = false;
  14414. // if nothing currently animating, get something from the queue
  14415. if (current.length === 0) {
  14416. var next = queue.shift();
  14417. if (next) {
  14418. current.push(next);
  14419. }
  14420. }
  14421. var callbacks = function callbacks(_callbacks) {
  14422. for (var j = _callbacks.length - 1; j >= 0; j--) {
  14423. var cb = _callbacks[j];
  14424. cb();
  14425. }
  14426. _callbacks.splice(0, _callbacks.length);
  14427. };
  14428. // step and remove if done
  14429. for (var i = current.length - 1; i >= 0; i--) {
  14430. var ani = current[i];
  14431. var ani_p = ani._private;
  14432. if (ani_p.stopped) {
  14433. current.splice(i, 1);
  14434. ani_p.hooked = false;
  14435. ani_p.playing = false;
  14436. ani_p.started = false;
  14437. callbacks(ani_p.frames);
  14438. continue;
  14439. }
  14440. if (!ani_p.playing && !ani_p.applying) {
  14441. continue;
  14442. }
  14443. // an apply() while playing shouldn't do anything
  14444. if (ani_p.playing && ani_p.applying) {
  14445. ani_p.applying = false;
  14446. }
  14447. if (!ani_p.started) {
  14448. startAnimation(ele, ani, now);
  14449. }
  14450. step$1(ele, ani, now, isCore);
  14451. if (ani_p.applying) {
  14452. ani_p.applying = false;
  14453. }
  14454. callbacks(ani_p.frames);
  14455. if (ani_p.step != null) {
  14456. ani_p.step(now);
  14457. }
  14458. if (ani.completed()) {
  14459. current.splice(i, 1);
  14460. ani_p.hooked = false;
  14461. ani_p.playing = false;
  14462. ani_p.started = false;
  14463. callbacks(ani_p.completes);
  14464. }
  14465. ranAnis = true;
  14466. }
  14467. if (!isCore && current.length === 0 && queue.length === 0) {
  14468. doneEles.push(ele);
  14469. }
  14470. return ranAnis;
  14471. } // stepElement
  14472. // handle all eles
  14473. var ranEleAni = false;
  14474. for (var e = 0; e < eles.length; e++) {
  14475. var ele = eles[e];
  14476. var handledThisEle = stepOne(ele);
  14477. ranEleAni = ranEleAni || handledThisEle;
  14478. } // each element
  14479. var ranCoreAni = stepOne(cy, true);
  14480. // notify renderer
  14481. if (ranEleAni || ranCoreAni) {
  14482. if (eles.length > 0) {
  14483. cy.notify('draw', eles);
  14484. } else {
  14485. cy.notify('draw');
  14486. }
  14487. }
  14488. // remove elements from list of currently animating if its queues are empty
  14489. eles.unmerge(doneEles);
  14490. cy.emit('step');
  14491. } // stepAll
  14492. var corefn$8 = {
  14493. // pull in animation functions
  14494. animate: define.animate(),
  14495. animation: define.animation(),
  14496. animated: define.animated(),
  14497. clearQueue: define.clearQueue(),
  14498. delay: define.delay(),
  14499. delayAnimation: define.delayAnimation(),
  14500. stop: define.stop(),
  14501. addToAnimationPool: function addToAnimationPool(eles) {
  14502. var cy = this;
  14503. if (!cy.styleEnabled()) {
  14504. return;
  14505. } // save cycles when no style used
  14506. cy._private.aniEles.merge(eles);
  14507. },
  14508. stopAnimationLoop: function stopAnimationLoop() {
  14509. this._private.animationsRunning = false;
  14510. },
  14511. startAnimationLoop: function startAnimationLoop() {
  14512. var cy = this;
  14513. cy._private.animationsRunning = true;
  14514. if (!cy.styleEnabled()) {
  14515. return;
  14516. } // save cycles when no style used
  14517. // NB the animation loop will exec in headless environments if style enabled
  14518. // and explicit cy.destroy() is necessary to stop the loop
  14519. function headlessStep() {
  14520. if (!cy._private.animationsRunning) {
  14521. return;
  14522. }
  14523. requestAnimationFrame(function animationStep(now) {
  14524. stepAll(now, cy);
  14525. headlessStep();
  14526. });
  14527. }
  14528. var renderer = cy.renderer();
  14529. if (renderer && renderer.beforeRender) {
  14530. // let the renderer schedule animations
  14531. renderer.beforeRender(function rendererAnimationStep(willDraw, now) {
  14532. stepAll(now, cy);
  14533. }, renderer.beforeRenderPriorities.animations);
  14534. } else {
  14535. // manage the animation loop ourselves
  14536. headlessStep(); // first call
  14537. }
  14538. }
  14539. };
  14540. var emitterOptions = {
  14541. qualifierCompare: function qualifierCompare(selector1, selector2) {
  14542. if (selector1 == null || selector2 == null) {
  14543. return selector1 == null && selector2 == null;
  14544. } else {
  14545. return selector1.sameText(selector2);
  14546. }
  14547. },
  14548. eventMatches: function eventMatches(cy, listener, eventObj) {
  14549. var selector = listener.qualifier;
  14550. if (selector != null) {
  14551. return cy !== eventObj.target && element(eventObj.target) && selector.matches(eventObj.target);
  14552. }
  14553. return true;
  14554. },
  14555. addEventFields: function addEventFields(cy, evt) {
  14556. evt.cy = cy;
  14557. evt.target = cy;
  14558. },
  14559. callbackContext: function callbackContext(cy, listener, eventObj) {
  14560. return listener.qualifier != null ? eventObj.target : cy;
  14561. }
  14562. };
  14563. var argSelector = function argSelector(arg) {
  14564. if (string(arg)) {
  14565. return new Selector(arg);
  14566. } else {
  14567. return arg;
  14568. }
  14569. };
  14570. var elesfn = {
  14571. createEmitter: function createEmitter() {
  14572. var _p = this._private;
  14573. if (!_p.emitter) {
  14574. _p.emitter = new Emitter(emitterOptions, this);
  14575. }
  14576. return this;
  14577. },
  14578. emitter: function emitter() {
  14579. return this._private.emitter;
  14580. },
  14581. on: function on(events, selector, callback) {
  14582. this.emitter().on(events, argSelector(selector), callback);
  14583. return this;
  14584. },
  14585. removeListener: function removeListener(events, selector, callback) {
  14586. this.emitter().removeListener(events, argSelector(selector), callback);
  14587. return this;
  14588. },
  14589. removeAllListeners: function removeAllListeners() {
  14590. this.emitter().removeAllListeners();
  14591. return this;
  14592. },
  14593. one: function one(events, selector, callback) {
  14594. this.emitter().one(events, argSelector(selector), callback);
  14595. return this;
  14596. },
  14597. once: function once(events, selector, callback) {
  14598. this.emitter().one(events, argSelector(selector), callback);
  14599. return this;
  14600. },
  14601. emit: function emit(events, extraParams) {
  14602. this.emitter().emit(events, extraParams);
  14603. return this;
  14604. },
  14605. emitAndNotify: function emitAndNotify(event, eles) {
  14606. this.emit(event);
  14607. this.notify(event, eles);
  14608. return this;
  14609. }
  14610. };
  14611. define.eventAliasesOn(elesfn);
  14612. var corefn$7 = {
  14613. png: function png(options) {
  14614. var renderer = this._private.renderer;
  14615. options = options || {};
  14616. return renderer.png(options);
  14617. },
  14618. jpg: function jpg(options) {
  14619. var renderer = this._private.renderer;
  14620. options = options || {};
  14621. options.bg = options.bg || '#fff';
  14622. return renderer.jpg(options);
  14623. }
  14624. };
  14625. corefn$7.jpeg = corefn$7.jpg;
  14626. var corefn$6 = {
  14627. layout: function layout(options) {
  14628. var cy = this;
  14629. if (options == null) {
  14630. error('Layout options must be specified to make a layout');
  14631. return;
  14632. }
  14633. if (options.name == null) {
  14634. error('A `name` must be specified to make a layout');
  14635. return;
  14636. }
  14637. var name = options.name;
  14638. var Layout = cy.extension('layout', name);
  14639. if (Layout == null) {
  14640. error('No such layout `' + name + '` found. Did you forget to import it and `cytoscape.use()` it?');
  14641. return;
  14642. }
  14643. var eles;
  14644. if (string(options.eles)) {
  14645. eles = cy.$(options.eles);
  14646. } else {
  14647. eles = options.eles != null ? options.eles : cy.$();
  14648. }
  14649. var layout = new Layout(extend({}, options, {
  14650. cy: cy,
  14651. eles: eles
  14652. }));
  14653. return layout;
  14654. }
  14655. };
  14656. corefn$6.createLayout = corefn$6.makeLayout = corefn$6.layout;
  14657. var corefn$5 = {
  14658. notify: function notify(eventName, eventEles) {
  14659. var _p = this._private;
  14660. if (this.batching()) {
  14661. _p.batchNotifications = _p.batchNotifications || {};
  14662. var eles = _p.batchNotifications[eventName] = _p.batchNotifications[eventName] || this.collection();
  14663. if (eventEles != null) {
  14664. eles.merge(eventEles);
  14665. }
  14666. return; // notifications are disabled during batching
  14667. }
  14668. if (!_p.notificationsEnabled) {
  14669. return;
  14670. } // exit on disabled
  14671. var renderer = this.renderer();
  14672. // exit if destroy() called on core or renderer in between frames #1499 #1528
  14673. if (this.destroyed() || !renderer) {
  14674. return;
  14675. }
  14676. renderer.notify(eventName, eventEles);
  14677. },
  14678. notifications: function notifications(bool) {
  14679. var p = this._private;
  14680. if (bool === undefined) {
  14681. return p.notificationsEnabled;
  14682. } else {
  14683. p.notificationsEnabled = bool ? true : false;
  14684. }
  14685. return this;
  14686. },
  14687. noNotifications: function noNotifications(callback) {
  14688. this.notifications(false);
  14689. callback();
  14690. this.notifications(true);
  14691. },
  14692. batching: function batching() {
  14693. return this._private.batchCount > 0;
  14694. },
  14695. startBatch: function startBatch() {
  14696. var _p = this._private;
  14697. if (_p.batchCount == null) {
  14698. _p.batchCount = 0;
  14699. }
  14700. if (_p.batchCount === 0) {
  14701. _p.batchStyleEles = this.collection();
  14702. _p.batchNotifications = {};
  14703. }
  14704. _p.batchCount++;
  14705. return this;
  14706. },
  14707. endBatch: function endBatch() {
  14708. var _p = this._private;
  14709. if (_p.batchCount === 0) {
  14710. return this;
  14711. }
  14712. _p.batchCount--;
  14713. if (_p.batchCount === 0) {
  14714. // update style for dirty eles
  14715. _p.batchStyleEles.updateStyle();
  14716. var renderer = this.renderer();
  14717. // notify the renderer of queued eles and event types
  14718. Object.keys(_p.batchNotifications).forEach(function (eventName) {
  14719. var eles = _p.batchNotifications[eventName];
  14720. if (eles.empty()) {
  14721. renderer.notify(eventName);
  14722. } else {
  14723. renderer.notify(eventName, eles);
  14724. }
  14725. });
  14726. }
  14727. return this;
  14728. },
  14729. batch: function batch(callback) {
  14730. this.startBatch();
  14731. callback();
  14732. this.endBatch();
  14733. return this;
  14734. },
  14735. // for backwards compatibility
  14736. batchData: function batchData(map) {
  14737. var cy = this;
  14738. return this.batch(function () {
  14739. var ids = Object.keys(map);
  14740. for (var i = 0; i < ids.length; i++) {
  14741. var id = ids[i];
  14742. var data = map[id];
  14743. var ele = cy.getElementById(id);
  14744. ele.data(data);
  14745. }
  14746. });
  14747. }
  14748. };
  14749. var rendererDefaults = defaults$g({
  14750. hideEdgesOnViewport: false,
  14751. textureOnViewport: false,
  14752. motionBlur: false,
  14753. motionBlurOpacity: 0.05,
  14754. pixelRatio: undefined,
  14755. desktopTapThreshold: 4,
  14756. touchTapThreshold: 8,
  14757. wheelSensitivity: 1,
  14758. debug: false,
  14759. showFps: false,
  14760. // webgl options
  14761. webgl: false,
  14762. webglDebug: false,
  14763. webglDebugShowAtlases: false,
  14764. // defaults good for mobile
  14765. webglTexSize: 2048,
  14766. webglTexRows: 36,
  14767. webglTexRowsNodes: 18,
  14768. webglBatchSize: 2048,
  14769. webglTexPerBatch: 14,
  14770. webglBgColor: [255, 255, 255]
  14771. });
  14772. var corefn$4 = {
  14773. renderTo: function renderTo(context, zoom, pan, pxRatio) {
  14774. var r = this._private.renderer;
  14775. r.renderTo(context, zoom, pan, pxRatio);
  14776. return this;
  14777. },
  14778. renderer: function renderer() {
  14779. return this._private.renderer;
  14780. },
  14781. forceRender: function forceRender() {
  14782. this.notify('draw');
  14783. return this;
  14784. },
  14785. resize: function resize() {
  14786. this.invalidateSize();
  14787. this.emitAndNotify('resize');
  14788. return this;
  14789. },
  14790. initRenderer: function initRenderer(options) {
  14791. var cy = this;
  14792. var RendererProto = cy.extension('renderer', options.name);
  14793. if (RendererProto == null) {
  14794. error("Can not initialise: No such renderer `".concat(options.name, "` found. Did you forget to import it and `cytoscape.use()` it?"));
  14795. return;
  14796. }
  14797. if (options.wheelSensitivity !== undefined) {
  14798. 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.");
  14799. }
  14800. var rOpts = rendererDefaults(options);
  14801. rOpts.cy = cy;
  14802. cy._private.renderer = new RendererProto(rOpts);
  14803. this.notify('init');
  14804. },
  14805. destroyRenderer: function destroyRenderer() {
  14806. var cy = this;
  14807. cy.notify('destroy'); // destroy the renderer
  14808. var domEle = cy.container();
  14809. if (domEle) {
  14810. domEle._cyreg = null;
  14811. while (domEle.childNodes.length > 0) {
  14812. domEle.removeChild(domEle.childNodes[0]);
  14813. }
  14814. }
  14815. cy._private.renderer = null; // to be extra safe, remove the ref
  14816. cy.mutableElements().forEach(function (ele) {
  14817. var _p = ele._private;
  14818. _p.rscratch = {};
  14819. _p.rstyle = {};
  14820. _p.animation.current = [];
  14821. _p.animation.queue = [];
  14822. });
  14823. },
  14824. onRender: function onRender(fn) {
  14825. return this.on('render', fn);
  14826. },
  14827. offRender: function offRender(fn) {
  14828. return this.off('render', fn);
  14829. }
  14830. };
  14831. corefn$4.invalidateDimensions = corefn$4.resize;
  14832. var corefn$3 = {
  14833. // get a collection
  14834. // - empty collection on no args
  14835. // - collection of elements in the graph on selector arg
  14836. // - guarantee a returned collection when elements or collection specified
  14837. collection: function collection(eles, opts) {
  14838. if (string(eles)) {
  14839. return this.$(eles);
  14840. } else if (elementOrCollection(eles)) {
  14841. return eles.collection();
  14842. } else if (array(eles)) {
  14843. if (!opts) {
  14844. opts = {};
  14845. }
  14846. return new Collection(this, eles, opts.unique, opts.removed);
  14847. }
  14848. return new Collection(this);
  14849. },
  14850. nodes: function nodes(selector) {
  14851. var nodes = this.$(function (ele) {
  14852. return ele.isNode();
  14853. });
  14854. if (selector) {
  14855. return nodes.filter(selector);
  14856. }
  14857. return nodes;
  14858. },
  14859. edges: function edges(selector) {
  14860. var edges = this.$(function (ele) {
  14861. return ele.isEdge();
  14862. });
  14863. if (selector) {
  14864. return edges.filter(selector);
  14865. }
  14866. return edges;
  14867. },
  14868. // search the graph like jQuery
  14869. $: function $(selector) {
  14870. var eles = this._private.elements;
  14871. if (selector) {
  14872. return eles.filter(selector);
  14873. } else {
  14874. return eles.spawnSelf();
  14875. }
  14876. },
  14877. mutableElements: function mutableElements() {
  14878. return this._private.elements;
  14879. }
  14880. };
  14881. // aliases
  14882. corefn$3.elements = corefn$3.filter = corefn$3.$;
  14883. var styfn$8 = {};
  14884. // keys for style blocks, e.g. ttfftt
  14885. var TRUE = 't';
  14886. var FALSE = 'f';
  14887. // (potentially expensive calculation)
  14888. // apply the style to the element based on
  14889. // - its bypass
  14890. // - what selectors match it
  14891. styfn$8.apply = function (eles) {
  14892. var self = this;
  14893. var _p = self._private;
  14894. var cy = _p.cy;
  14895. var updatedEles = cy.collection();
  14896. for (var ie = 0; ie < eles.length; ie++) {
  14897. var ele = eles[ie];
  14898. var cxtMeta = self.getContextMeta(ele);
  14899. if (cxtMeta.empty) {
  14900. continue;
  14901. }
  14902. var cxtStyle = self.getContextStyle(cxtMeta);
  14903. var app = self.applyContextStyle(cxtMeta, cxtStyle, ele);
  14904. if (ele._private.appliedInitStyle) {
  14905. self.updateTransitions(ele, app.diffProps);
  14906. } else {
  14907. ele._private.appliedInitStyle = true;
  14908. }
  14909. var hintsDiff = self.updateStyleHints(ele);
  14910. if (hintsDiff) {
  14911. updatedEles.push(ele);
  14912. }
  14913. } // for elements
  14914. return updatedEles;
  14915. };
  14916. styfn$8.getPropertiesDiff = function (oldCxtKey, newCxtKey) {
  14917. var self = this;
  14918. var cache = self._private.propDiffs = self._private.propDiffs || {};
  14919. var dualCxtKey = oldCxtKey + '-' + newCxtKey;
  14920. var cachedVal = cache[dualCxtKey];
  14921. if (cachedVal) {
  14922. return cachedVal;
  14923. }
  14924. var diffProps = [];
  14925. var addedProp = {};
  14926. for (var i = 0; i < self.length; i++) {
  14927. var cxt = self[i];
  14928. var oldHasCxt = oldCxtKey[i] === TRUE;
  14929. var newHasCxt = newCxtKey[i] === TRUE;
  14930. var cxtHasDiffed = oldHasCxt !== newHasCxt;
  14931. var cxtHasMappedProps = cxt.mappedProperties.length > 0;
  14932. if (cxtHasDiffed || newHasCxt && cxtHasMappedProps) {
  14933. var props = undefined;
  14934. if (cxtHasDiffed && cxtHasMappedProps) {
  14935. props = cxt.properties; // suffices b/c mappedProperties is a subset of properties
  14936. } else if (cxtHasDiffed) {
  14937. props = cxt.properties; // need to check them all
  14938. } else if (cxtHasMappedProps) {
  14939. props = cxt.mappedProperties; // only need to check mapped
  14940. }
  14941. for (var j = 0; j < props.length; j++) {
  14942. var prop = props[j];
  14943. var name = prop.name;
  14944. // if a later context overrides this property, then the fact that this context has switched/diffed doesn't matter
  14945. // (semi expensive check since it makes this function O(n^2) on context length, but worth it since overall result
  14946. // is cached)
  14947. var laterCxtOverrides = false;
  14948. for (var k = i + 1; k < self.length; k++) {
  14949. var laterCxt = self[k];
  14950. var hasLaterCxt = newCxtKey[k] === TRUE;
  14951. if (!hasLaterCxt) {
  14952. continue;
  14953. } // can't override unless the context is active
  14954. laterCxtOverrides = laterCxt.properties[prop.name] != null;
  14955. if (laterCxtOverrides) {
  14956. break;
  14957. } // exit early as long as one later context overrides
  14958. }
  14959. if (!addedProp[name] && !laterCxtOverrides) {
  14960. addedProp[name] = true;
  14961. diffProps.push(name);
  14962. }
  14963. } // for props
  14964. } // if
  14965. } // for contexts
  14966. cache[dualCxtKey] = diffProps;
  14967. return diffProps;
  14968. };
  14969. styfn$8.getContextMeta = function (ele) {
  14970. var self = this;
  14971. var cxtKey = '';
  14972. var diffProps;
  14973. var prevKey = ele._private.styleCxtKey || '';
  14974. // get the cxt key
  14975. for (var i = 0; i < self.length; i++) {
  14976. var context = self[i];
  14977. var contextSelectorMatches = context.selector && context.selector.matches(ele); // NB: context.selector may be null for 'core'
  14978. if (contextSelectorMatches) {
  14979. cxtKey += TRUE;
  14980. } else {
  14981. cxtKey += FALSE;
  14982. }
  14983. } // for context
  14984. diffProps = self.getPropertiesDiff(prevKey, cxtKey);
  14985. ele._private.styleCxtKey = cxtKey;
  14986. return {
  14987. key: cxtKey,
  14988. diffPropNames: diffProps,
  14989. empty: diffProps.length === 0
  14990. };
  14991. };
  14992. // gets a computed ele style object based on matched contexts
  14993. styfn$8.getContextStyle = function (cxtMeta) {
  14994. var cxtKey = cxtMeta.key;
  14995. var self = this;
  14996. var cxtStyles = this._private.contextStyles = this._private.contextStyles || {};
  14997. // if already computed style, returned cached copy
  14998. if (cxtStyles[cxtKey]) {
  14999. return cxtStyles[cxtKey];
  15000. }
  15001. var style = {
  15002. _private: {
  15003. key: cxtKey
  15004. }
  15005. };
  15006. for (var i = 0; i < self.length; i++) {
  15007. var cxt = self[i];
  15008. var hasCxt = cxtKey[i] === TRUE;
  15009. if (!hasCxt) {
  15010. continue;
  15011. }
  15012. for (var j = 0; j < cxt.properties.length; j++) {
  15013. var prop = cxt.properties[j];
  15014. style[prop.name] = prop;
  15015. }
  15016. }
  15017. cxtStyles[cxtKey] = style;
  15018. return style;
  15019. };
  15020. styfn$8.applyContextStyle = function (cxtMeta, cxtStyle, ele) {
  15021. var self = this;
  15022. var diffProps = cxtMeta.diffPropNames;
  15023. var retDiffProps = {};
  15024. var types = self.types;
  15025. for (var i = 0; i < diffProps.length; i++) {
  15026. var diffPropName = diffProps[i];
  15027. var cxtProp = cxtStyle[diffPropName];
  15028. var eleProp = ele.pstyle(diffPropName);
  15029. if (!cxtProp) {
  15030. // no context prop means delete
  15031. if (!eleProp) {
  15032. continue; // no existing prop means nothing needs to be removed
  15033. // nb affects initial application on mapped values like control-point-distances
  15034. } else if (eleProp.bypass) {
  15035. cxtProp = {
  15036. name: diffPropName,
  15037. deleteBypassed: true
  15038. };
  15039. } else {
  15040. cxtProp = {
  15041. name: diffPropName,
  15042. "delete": true
  15043. };
  15044. }
  15045. }
  15046. // save cycles when the context prop doesn't need to be applied
  15047. if (eleProp === cxtProp) {
  15048. continue;
  15049. }
  15050. // save cycles when a mapped context prop doesn't need to be applied
  15051. if (cxtProp.mapped === types.fn // context prop is function mapper
  15052. && eleProp != null // some props can be null even by default (e.g. a prop that overrides another one)
  15053. && eleProp.mapping != null // ele prop is a concrete value from from a mapper
  15054. && eleProp.mapping.value === cxtProp.value // the current prop on the ele is a flat prop value for the function mapper
  15055. ) {
  15056. // NB don't write to cxtProp, as it's shared among eles (stored in stylesheet)
  15057. var mapping = eleProp.mapping; // can write to mapping, as it's a per-ele copy
  15058. var fnValue = mapping.fnValue = cxtProp.value(ele); // temporarily cache the value in case of a miss
  15059. if (fnValue === mapping.prevFnValue) {
  15060. continue;
  15061. }
  15062. }
  15063. var retDiffProp = retDiffProps[diffPropName] = {
  15064. prev: eleProp
  15065. };
  15066. self.applyParsedProperty(ele, cxtProp);
  15067. retDiffProp.next = ele.pstyle(diffPropName);
  15068. if (retDiffProp.next && retDiffProp.next.bypass) {
  15069. retDiffProp.next = retDiffProp.next.bypassed;
  15070. }
  15071. }
  15072. return {
  15073. diffProps: retDiffProps
  15074. };
  15075. };
  15076. styfn$8.updateStyleHints = function (ele) {
  15077. var _p = ele._private;
  15078. var self = this;
  15079. var propNames = self.propertyGroupNames;
  15080. var propGrKeys = self.propertyGroupKeys;
  15081. var propHash = function propHash(ele, propNames, seedKey) {
  15082. return self.getPropertiesHash(ele, propNames, seedKey);
  15083. };
  15084. var oldStyleKey = _p.styleKey;
  15085. if (ele.removed()) {
  15086. return false;
  15087. }
  15088. var isNode = _p.group === 'nodes';
  15089. // get the style key hashes per prop group
  15090. // but lazily -- only use non-default prop values to reduce the number of hashes
  15091. //
  15092. var overriddenStyles = ele._private.style;
  15093. propNames = Object.keys(overriddenStyles);
  15094. for (var i = 0; i < propGrKeys.length; i++) {
  15095. var grKey = propGrKeys[i];
  15096. _p.styleKeys[grKey] = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  15097. }
  15098. var updateGrKey1 = function updateGrKey1(val, grKey) {
  15099. return _p.styleKeys[grKey][0] = hashInt(val, _p.styleKeys[grKey][0]);
  15100. };
  15101. var updateGrKey2 = function updateGrKey2(val, grKey) {
  15102. return _p.styleKeys[grKey][1] = hashIntAlt(val, _p.styleKeys[grKey][1]);
  15103. };
  15104. var updateGrKey = function updateGrKey(val, grKey) {
  15105. updateGrKey1(val, grKey);
  15106. updateGrKey2(val, grKey);
  15107. };
  15108. var updateGrKeyWStr = function updateGrKeyWStr(strVal, grKey) {
  15109. for (var j = 0; j < strVal.length; j++) {
  15110. var ch = strVal.charCodeAt(j);
  15111. updateGrKey1(ch, grKey);
  15112. updateGrKey2(ch, grKey);
  15113. }
  15114. };
  15115. // - hashing works on 32 bit ints b/c we use bitwise ops
  15116. // - small numbers get cut off (e.g. 0.123 is seen as 0 by the hashing function)
  15117. // - raise up small numbers so more significant digits are seen by hashing
  15118. // - make small numbers larger than a normal value to avoid collisions
  15119. // - works in practice and it's relatively cheap
  15120. var N = 2000000000;
  15121. var cleanNum = function cleanNum(val) {
  15122. return -128 < val && val < 128 && Math.floor(val) !== val ? N - (val * 1024 | 0) : val;
  15123. };
  15124. for (var _i = 0; _i < propNames.length; _i++) {
  15125. var name = propNames[_i];
  15126. var parsedProp = overriddenStyles[name];
  15127. if (parsedProp == null) {
  15128. continue;
  15129. }
  15130. var propInfo = this.properties[name];
  15131. var type = propInfo.type;
  15132. var _grKey = propInfo.groupKey;
  15133. var normalizedNumberVal = undefined;
  15134. if (propInfo.hashOverride != null) {
  15135. normalizedNumberVal = propInfo.hashOverride(ele, parsedProp);
  15136. } else if (parsedProp.pfValue != null) {
  15137. normalizedNumberVal = parsedProp.pfValue;
  15138. }
  15139. // might not be a number if it allows enums
  15140. var numberVal = propInfo.enums == null ? parsedProp.value : null;
  15141. var haveNormNum = normalizedNumberVal != null;
  15142. var haveUnitedNum = numberVal != null;
  15143. var haveNum = haveNormNum || haveUnitedNum;
  15144. var units = parsedProp.units;
  15145. // numbers are cheaper to hash than strings
  15146. // 1 hash op vs n hash ops (for length n string)
  15147. if (type.number && haveNum && !type.multiple) {
  15148. var v = haveNormNum ? normalizedNumberVal : numberVal;
  15149. updateGrKey(cleanNum(v), _grKey);
  15150. if (!haveNormNum && units != null) {
  15151. updateGrKeyWStr(units, _grKey);
  15152. }
  15153. } else {
  15154. updateGrKeyWStr(parsedProp.strValue, _grKey);
  15155. }
  15156. }
  15157. // overall style key
  15158. //
  15159. var hash = [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT];
  15160. for (var _i2 = 0; _i2 < propGrKeys.length; _i2++) {
  15161. var _grKey2 = propGrKeys[_i2];
  15162. var grHash = _p.styleKeys[_grKey2];
  15163. hash[0] = hashInt(grHash[0], hash[0]);
  15164. hash[1] = hashIntAlt(grHash[1], hash[1]);
  15165. }
  15166. _p.styleKey = combineHashes(hash[0], hash[1]);
  15167. // label dims
  15168. //
  15169. var sk = _p.styleKeys;
  15170. _p.labelDimsKey = combineHashesArray(sk.labelDimensions);
  15171. var labelKeys = propHash(ele, ['label'], sk.labelDimensions);
  15172. _p.labelKey = combineHashesArray(labelKeys);
  15173. _p.labelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, labelKeys));
  15174. if (!isNode) {
  15175. var sourceLabelKeys = propHash(ele, ['source-label'], sk.labelDimensions);
  15176. _p.sourceLabelKey = combineHashesArray(sourceLabelKeys);
  15177. _p.sourceLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, sourceLabelKeys));
  15178. var targetLabelKeys = propHash(ele, ['target-label'], sk.labelDimensions);
  15179. _p.targetLabelKey = combineHashesArray(targetLabelKeys);
  15180. _p.targetLabelStyleKey = combineHashesArray(hashArrays(sk.commonLabel, targetLabelKeys));
  15181. }
  15182. // node
  15183. //
  15184. if (isNode) {
  15185. var _p$styleKeys = _p.styleKeys,
  15186. nodeBody = _p$styleKeys.nodeBody,
  15187. nodeBorder = _p$styleKeys.nodeBorder,
  15188. nodeOutline = _p$styleKeys.nodeOutline,
  15189. backgroundImage = _p$styleKeys.backgroundImage,
  15190. compound = _p$styleKeys.compound,
  15191. pie = _p$styleKeys.pie,
  15192. stripe = _p$styleKeys.stripe;
  15193. var nodeKeys = [nodeBody, nodeBorder, nodeOutline, backgroundImage, compound, pie, stripe].filter(function (k) {
  15194. return k != null;
  15195. }).reduce(hashArrays, [DEFAULT_HASH_SEED, DEFAULT_HASH_SEED_ALT]);
  15196. _p.nodeKey = combineHashesArray(nodeKeys);
  15197. _p.hasPie = pie != null && pie[0] !== DEFAULT_HASH_SEED && pie[1] !== DEFAULT_HASH_SEED_ALT;
  15198. _p.hasStripe = stripe != null && stripe[0] !== DEFAULT_HASH_SEED && stripe[1] !== DEFAULT_HASH_SEED_ALT;
  15199. }
  15200. return oldStyleKey !== _p.styleKey;
  15201. };
  15202. styfn$8.clearStyleHints = function (ele) {
  15203. var _p = ele._private;
  15204. _p.styleCxtKey = '';
  15205. _p.styleKeys = {};
  15206. _p.styleKey = null;
  15207. _p.labelKey = null;
  15208. _p.labelStyleKey = null;
  15209. _p.sourceLabelKey = null;
  15210. _p.sourceLabelStyleKey = null;
  15211. _p.targetLabelKey = null;
  15212. _p.targetLabelStyleKey = null;
  15213. _p.nodeKey = null;
  15214. _p.hasPie = null;
  15215. _p.hasStripe = null;
  15216. };
  15217. // apply a property to the style (for internal use)
  15218. // returns whether application was successful
  15219. //
  15220. // now, this function flattens the property, and here's how:
  15221. //
  15222. // for parsedProp:{ bypass: true, deleteBypass: true }
  15223. // no property is generated, instead the bypass property in the
  15224. // element's style is replaced by what's pointed to by the `bypassed`
  15225. // field in the bypass property (i.e. restoring the property the
  15226. // bypass was overriding)
  15227. //
  15228. // for parsedProp:{ mapped: truthy }
  15229. // the generated flattenedProp:{ mapping: prop }
  15230. //
  15231. // for parsedProp:{ bypass: true }
  15232. // the generated flattenedProp:{ bypassed: parsedProp }
  15233. styfn$8.applyParsedProperty = function (ele, parsedProp) {
  15234. var self = this;
  15235. var prop = parsedProp;
  15236. var style = ele._private.style;
  15237. var flatProp;
  15238. var types = self.types;
  15239. var type = self.properties[prop.name].type;
  15240. var propIsBypass = prop.bypass;
  15241. var origProp = style[prop.name];
  15242. var origPropIsBypass = origProp && origProp.bypass;
  15243. var _p = ele._private;
  15244. var flatPropMapping = 'mapping';
  15245. var getVal = function getVal(p) {
  15246. if (p == null) {
  15247. return null;
  15248. } else if (p.pfValue != null) {
  15249. return p.pfValue;
  15250. } else {
  15251. return p.value;
  15252. }
  15253. };
  15254. var checkTriggers = function checkTriggers() {
  15255. var fromVal = getVal(origProp);
  15256. var toVal = getVal(prop);
  15257. self.checkTriggers(ele, prop.name, fromVal, toVal);
  15258. };
  15259. // edge sanity checks to prevent the client from making serious mistakes
  15260. if (parsedProp.name === 'curve-style' && ele.isEdge() && (
  15261. // loops must be bundled beziers
  15262. parsedProp.value !== 'bezier' && ele.isLoop() ||
  15263. // edges connected to compound nodes can not be haystacks
  15264. parsedProp.value === 'haystack' && (ele.source().isParent() || ele.target().isParent()))) {
  15265. prop = parsedProp = this.parse(parsedProp.name, 'bezier', propIsBypass);
  15266. }
  15267. if (prop["delete"]) {
  15268. // delete the property and use the default value on falsey value
  15269. style[prop.name] = undefined;
  15270. checkTriggers();
  15271. return true;
  15272. }
  15273. if (prop.deleteBypassed) {
  15274. // delete the property that the
  15275. if (!origProp) {
  15276. checkTriggers();
  15277. return true; // can't delete if no prop
  15278. } else if (origProp.bypass) {
  15279. // delete bypassed
  15280. origProp.bypassed = undefined;
  15281. checkTriggers();
  15282. return true;
  15283. } else {
  15284. return false; // we're unsuccessful deleting the bypassed
  15285. }
  15286. }
  15287. // check if we need to delete the current bypass
  15288. if (prop.deleteBypass) {
  15289. // then this property is just here to indicate we need to delete
  15290. if (!origProp) {
  15291. checkTriggers();
  15292. return true; // property is already not defined
  15293. } else if (origProp.bypass) {
  15294. // then replace the bypass property with the original
  15295. // because the bypassed property was already applied (and therefore parsed), we can just replace it (no reapplying necessary)
  15296. style[prop.name] = origProp.bypassed;
  15297. checkTriggers();
  15298. return true;
  15299. } else {
  15300. return false; // we're unsuccessful deleting the bypass
  15301. }
  15302. }
  15303. var printMappingErr = function printMappingErr() {
  15304. 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');
  15305. };
  15306. // put the property in the style objects
  15307. switch (prop.mapped) {
  15308. // flatten the property if mapped
  15309. case types.mapData:
  15310. {
  15311. // flatten the field (e.g. data.foo.bar)
  15312. var fields = prop.field.split('.');
  15313. var fieldVal = _p.data;
  15314. for (var i = 0; i < fields.length && fieldVal; i++) {
  15315. var field = fields[i];
  15316. fieldVal = fieldVal[field];
  15317. }
  15318. if (fieldVal == null) {
  15319. printMappingErr();
  15320. return false;
  15321. }
  15322. var percent;
  15323. if (!number$1(fieldVal)) {
  15324. // then don't apply and fall back on the existing style
  15325. warn('Do not use continuous mappers without specifying numeric data (i.e. `' + prop.field + ': ' + fieldVal + '` for `' + ele.id() + '` is non-numeric)');
  15326. return false;
  15327. } else {
  15328. var fieldWidth = prop.fieldMax - prop.fieldMin;
  15329. if (fieldWidth === 0) {
  15330. // safety check -- not strictly necessary as no props of zero range should be passed here
  15331. percent = 0;
  15332. } else {
  15333. percent = (fieldVal - prop.fieldMin) / fieldWidth;
  15334. }
  15335. }
  15336. // make sure to bound percent value
  15337. if (percent < 0) {
  15338. percent = 0;
  15339. } else if (percent > 1) {
  15340. percent = 1;
  15341. }
  15342. if (type.color) {
  15343. var r1 = prop.valueMin[0];
  15344. var r2 = prop.valueMax[0];
  15345. var g1 = prop.valueMin[1];
  15346. var g2 = prop.valueMax[1];
  15347. var b1 = prop.valueMin[2];
  15348. var b2 = prop.valueMax[2];
  15349. var a1 = prop.valueMin[3] == null ? 1 : prop.valueMin[3];
  15350. var a2 = prop.valueMax[3] == null ? 1 : prop.valueMax[3];
  15351. 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)];
  15352. flatProp = {
  15353. // colours are simple, so just create the flat property instead of expensive string parsing
  15354. bypass: prop.bypass,
  15355. // we're a bypass if the mapping property is a bypass
  15356. name: prop.name,
  15357. value: clr,
  15358. strValue: 'rgb(' + clr[0] + ', ' + clr[1] + ', ' + clr[2] + ')'
  15359. };
  15360. } else if (type.number) {
  15361. var calcValue = prop.valueMin + (prop.valueMax - prop.valueMin) * percent;
  15362. flatProp = this.parse(prop.name, calcValue, prop.bypass, flatPropMapping);
  15363. } else {
  15364. return false; // can only map to colours and numbers
  15365. }
  15366. if (!flatProp) {
  15367. // if we can't flatten the property, then don't apply the property and fall back on the existing style
  15368. printMappingErr();
  15369. return false;
  15370. }
  15371. flatProp.mapping = prop; // keep a reference to the mapping
  15372. prop = flatProp; // the flattened (mapped) property is the one we want
  15373. break;
  15374. }
  15375. // direct mapping
  15376. case types.data:
  15377. {
  15378. // flatten the field (e.g. data.foo.bar)
  15379. var _fields = prop.field.split('.');
  15380. var _fieldVal = _p.data;
  15381. for (var _i3 = 0; _i3 < _fields.length && _fieldVal; _i3++) {
  15382. var _field = _fields[_i3];
  15383. _fieldVal = _fieldVal[_field];
  15384. }
  15385. if (_fieldVal != null) {
  15386. flatProp = this.parse(prop.name, _fieldVal, prop.bypass, flatPropMapping);
  15387. }
  15388. if (!flatProp) {
  15389. // if we can't flatten the property, then don't apply and fall back on the existing style
  15390. printMappingErr();
  15391. return false;
  15392. }
  15393. flatProp.mapping = prop; // keep a reference to the mapping
  15394. prop = flatProp; // the flattened (mapped) property is the one we want
  15395. break;
  15396. }
  15397. case types.fn:
  15398. {
  15399. var fn = prop.value;
  15400. var fnRetVal = prop.fnValue != null ? prop.fnValue : fn(ele); // check for cached value before calling function
  15401. prop.prevFnValue = fnRetVal;
  15402. if (fnRetVal == null) {
  15403. warn('Custom function mappers may not return null (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is null)');
  15404. return false;
  15405. }
  15406. flatProp = this.parse(prop.name, fnRetVal, prop.bypass, flatPropMapping);
  15407. if (!flatProp) {
  15408. warn('Custom function mappers may not return invalid values for the property type (i.e. `' + prop.name + '` for ele `' + ele.id() + '` is invalid)');
  15409. return false;
  15410. }
  15411. flatProp.mapping = copy(prop); // keep a reference to the mapping
  15412. prop = flatProp; // the flattened (mapped) property is the one we want
  15413. break;
  15414. }
  15415. case undefined:
  15416. break;
  15417. // just set the property
  15418. default:
  15419. return false;
  15420. // not a valid mapping
  15421. }
  15422. // if the property is a bypass property, then link the resultant property to the original one
  15423. if (propIsBypass) {
  15424. if (origPropIsBypass) {
  15425. // then this bypass overrides the existing one
  15426. prop.bypassed = origProp.bypassed; // steal bypassed prop from old bypass
  15427. } else {
  15428. // then link the orig prop to the new bypass
  15429. prop.bypassed = origProp;
  15430. }
  15431. style[prop.name] = prop; // and set
  15432. } else {
  15433. // prop is not bypass
  15434. if (origPropIsBypass) {
  15435. // then keep the orig prop (since it's a bypass) and link to the new prop
  15436. origProp.bypassed = prop;
  15437. } else {
  15438. // then just replace the old prop with the new one
  15439. style[prop.name] = prop;
  15440. }
  15441. }
  15442. checkTriggers();
  15443. return true;
  15444. };
  15445. styfn$8.cleanElements = function (eles, keepBypasses) {
  15446. for (var i = 0; i < eles.length; i++) {
  15447. var ele = eles[i];
  15448. this.clearStyleHints(ele);
  15449. ele.dirtyCompoundBoundsCache();
  15450. ele.dirtyBoundingBoxCache();
  15451. if (!keepBypasses) {
  15452. ele._private.style = {};
  15453. } else {
  15454. var style = ele._private.style;
  15455. var propNames = Object.keys(style);
  15456. for (var j = 0; j < propNames.length; j++) {
  15457. var propName = propNames[j];
  15458. var eleProp = style[propName];
  15459. if (eleProp != null) {
  15460. if (eleProp.bypass) {
  15461. eleProp.bypassed = null;
  15462. } else {
  15463. style[propName] = null;
  15464. }
  15465. }
  15466. }
  15467. }
  15468. }
  15469. };
  15470. // updates the visual style for all elements (useful for manual style modification after init)
  15471. styfn$8.update = function () {
  15472. var cy = this._private.cy;
  15473. var eles = cy.mutableElements();
  15474. eles.updateStyle();
  15475. };
  15476. // diffProps : { name => { prev, next } }
  15477. styfn$8.updateTransitions = function (ele, diffProps) {
  15478. var self = this;
  15479. var _p = ele._private;
  15480. var props = ele.pstyle('transition-property').value;
  15481. var duration = ele.pstyle('transition-duration').pfValue;
  15482. var delay = ele.pstyle('transition-delay').pfValue;
  15483. if (props.length > 0 && duration > 0) {
  15484. var style = {};
  15485. // build up the style to animate towards
  15486. var anyPrev = false;
  15487. for (var i = 0; i < props.length; i++) {
  15488. var prop = props[i];
  15489. var styProp = ele.pstyle(prop);
  15490. var diffProp = diffProps[prop];
  15491. if (!diffProp) {
  15492. continue;
  15493. }
  15494. var prevProp = diffProp.prev;
  15495. var fromProp = prevProp;
  15496. var toProp = diffProp.next != null ? diffProp.next : styProp;
  15497. var diff = false;
  15498. var initVal = undefined;
  15499. var initDt = 0.000001; // delta time % value for initVal (allows animating out of init zero opacity)
  15500. if (!fromProp) {
  15501. continue;
  15502. }
  15503. // consider px values
  15504. if (number$1(fromProp.pfValue) && number$1(toProp.pfValue)) {
  15505. diff = toProp.pfValue - fromProp.pfValue; // nonzero is truthy
  15506. initVal = fromProp.pfValue + initDt * diff;
  15507. // consider numerical values
  15508. } else if (number$1(fromProp.value) && number$1(toProp.value)) {
  15509. diff = toProp.value - fromProp.value; // nonzero is truthy
  15510. initVal = fromProp.value + initDt * diff;
  15511. // consider colour values
  15512. } else if (array(fromProp.value) && array(toProp.value)) {
  15513. diff = fromProp.value[0] !== toProp.value[0] || fromProp.value[1] !== toProp.value[1] || fromProp.value[2] !== toProp.value[2];
  15514. initVal = fromProp.strValue;
  15515. }
  15516. // the previous value is good for an animation only if it's different
  15517. if (diff) {
  15518. style[prop] = toProp.strValue; // to val
  15519. this.applyBypass(ele, prop, initVal); // from val
  15520. anyPrev = true;
  15521. }
  15522. } // end if props allow ani
  15523. // can't transition if there's nothing previous to transition from
  15524. if (!anyPrev) {
  15525. return;
  15526. }
  15527. _p.transitioning = true;
  15528. new Promise$1(function (resolve) {
  15529. if (delay > 0) {
  15530. ele.delayAnimation(delay).play().promise().then(resolve);
  15531. } else {
  15532. resolve();
  15533. }
  15534. }).then(function () {
  15535. return ele.animation({
  15536. style: style,
  15537. duration: duration,
  15538. easing: ele.pstyle('transition-timing-function').value,
  15539. queue: false
  15540. }).play().promise();
  15541. }).then(function () {
  15542. // if( !isBypass ){
  15543. self.removeBypasses(ele, props);
  15544. ele.emitAndNotify('style');
  15545. // }
  15546. _p.transitioning = false;
  15547. });
  15548. } else if (_p.transitioning) {
  15549. this.removeBypasses(ele, props);
  15550. ele.emitAndNotify('style');
  15551. _p.transitioning = false;
  15552. }
  15553. };
  15554. styfn$8.checkTrigger = function (ele, name, fromValue, toValue, getTrigger, onTrigger) {
  15555. var prop = this.properties[name];
  15556. var triggerCheck = getTrigger(prop);
  15557. if (ele.removed()) {
  15558. return;
  15559. }
  15560. if (triggerCheck != null && triggerCheck(fromValue, toValue, ele)) {
  15561. onTrigger(prop);
  15562. }
  15563. };
  15564. styfn$8.checkZOrderTrigger = function (ele, name, fromValue, toValue) {
  15565. var _this = this;
  15566. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15567. return prop.triggersZOrder;
  15568. }, function () {
  15569. _this._private.cy.notify('zorder', ele);
  15570. });
  15571. };
  15572. styfn$8.checkBoundsTrigger = function (ele, name, fromValue, toValue) {
  15573. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15574. return prop.triggersBounds;
  15575. }, function (prop) {
  15576. ele.dirtyCompoundBoundsCache();
  15577. ele.dirtyBoundingBoxCache();
  15578. });
  15579. };
  15580. styfn$8.checkConnectedEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  15581. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15582. return prop.triggersBoundsOfConnectedEdges;
  15583. }, function (prop) {
  15584. ele.connectedEdges().forEach(function (edge) {
  15585. edge.dirtyBoundingBoxCache();
  15586. });
  15587. });
  15588. };
  15589. styfn$8.checkParallelEdgesBoundsTrigger = function (ele, name, fromValue, toValue) {
  15590. this.checkTrigger(ele, name, fromValue, toValue, function (prop) {
  15591. return prop.triggersBoundsOfParallelEdges;
  15592. }, function (prop) {
  15593. ele.parallelEdges().forEach(function (pllEdge) {
  15594. pllEdge.dirtyBoundingBoxCache();
  15595. });
  15596. });
  15597. };
  15598. styfn$8.checkTriggers = function (ele, name, fromValue, toValue) {
  15599. ele.dirtyStyleCache();
  15600. this.checkZOrderTrigger(ele, name, fromValue, toValue);
  15601. this.checkBoundsTrigger(ele, name, fromValue, toValue);
  15602. this.checkConnectedEdgesBoundsTrigger(ele, name, fromValue, toValue);
  15603. this.checkParallelEdgesBoundsTrigger(ele, name, fromValue, toValue);
  15604. };
  15605. var styfn$7 = {};
  15606. // bypasses are applied to an existing style on an element, and just tacked on temporarily
  15607. // returns true iff application was successful for at least 1 specified property
  15608. styfn$7.applyBypass = function (eles, name, value, updateTransitions) {
  15609. var self = this;
  15610. var props = [];
  15611. var isBypass = true;
  15612. // put all the properties (can specify one or many) in an array after parsing them
  15613. if (name === '*' || name === '**') {
  15614. // apply to all property names
  15615. if (value !== undefined) {
  15616. for (var i = 0; i < self.properties.length; i++) {
  15617. var prop = self.properties[i];
  15618. var _name = prop.name;
  15619. var parsedProp = this.parse(_name, value, true);
  15620. if (parsedProp) {
  15621. props.push(parsedProp);
  15622. }
  15623. }
  15624. }
  15625. } else if (string(name)) {
  15626. // then parse the single property
  15627. var _parsedProp = this.parse(name, value, true);
  15628. if (_parsedProp) {
  15629. props.push(_parsedProp);
  15630. }
  15631. } else if (plainObject(name)) {
  15632. // then parse each property
  15633. var specifiedProps = name;
  15634. updateTransitions = value;
  15635. var names = Object.keys(specifiedProps);
  15636. for (var _i = 0; _i < names.length; _i++) {
  15637. var _name2 = names[_i];
  15638. var _value = specifiedProps[_name2];
  15639. if (_value === undefined) {
  15640. // try camel case name too
  15641. _value = specifiedProps[dash2camel(_name2)];
  15642. }
  15643. if (_value !== undefined) {
  15644. var _parsedProp2 = this.parse(_name2, _value, true);
  15645. if (_parsedProp2) {
  15646. props.push(_parsedProp2);
  15647. }
  15648. }
  15649. }
  15650. } else {
  15651. // can't do anything without well defined properties
  15652. return false;
  15653. }
  15654. // we've failed if there are no valid properties
  15655. if (props.length === 0) {
  15656. return false;
  15657. }
  15658. // now, apply the bypass properties on the elements
  15659. var ret = false; // return true if at least one succesful bypass applied
  15660. for (var _i2 = 0; _i2 < eles.length; _i2++) {
  15661. // for each ele
  15662. var ele = eles[_i2];
  15663. var diffProps = {};
  15664. var diffProp = undefined;
  15665. for (var j = 0; j < props.length; j++) {
  15666. // for each prop
  15667. var _prop = props[j];
  15668. if (updateTransitions) {
  15669. var prevProp = ele.pstyle(_prop.name);
  15670. diffProp = diffProps[_prop.name] = {
  15671. prev: prevProp
  15672. };
  15673. }
  15674. ret = this.applyParsedProperty(ele, copy(_prop)) || ret;
  15675. if (updateTransitions) {
  15676. diffProp.next = ele.pstyle(_prop.name);
  15677. }
  15678. } // for props
  15679. if (ret) {
  15680. this.updateStyleHints(ele);
  15681. }
  15682. if (updateTransitions) {
  15683. this.updateTransitions(ele, diffProps, isBypass);
  15684. }
  15685. } // for eles
  15686. return ret;
  15687. };
  15688. // only useful in specific cases like animation
  15689. styfn$7.overrideBypass = function (eles, name, value) {
  15690. name = camel2dash(name);
  15691. for (var i = 0; i < eles.length; i++) {
  15692. var ele = eles[i];
  15693. var prop = ele._private.style[name];
  15694. var type = this.properties[name].type;
  15695. var isColor = type.color;
  15696. var isMulti = type.mutiple;
  15697. var oldValue = !prop ? null : prop.pfValue != null ? prop.pfValue : prop.value;
  15698. if (!prop || !prop.bypass) {
  15699. // need a bypass if one doesn't exist
  15700. this.applyBypass(ele, name, value);
  15701. } else {
  15702. prop.value = value;
  15703. if (prop.pfValue != null) {
  15704. prop.pfValue = value;
  15705. }
  15706. if (isColor) {
  15707. prop.strValue = 'rgb(' + value.join(',') + ')';
  15708. } else if (isMulti) {
  15709. prop.strValue = value.join(' ');
  15710. } else {
  15711. prop.strValue = '' + value;
  15712. }
  15713. this.updateStyleHints(ele);
  15714. }
  15715. this.checkTriggers(ele, name, oldValue, value);
  15716. }
  15717. };
  15718. styfn$7.removeAllBypasses = function (eles, updateTransitions) {
  15719. return this.removeBypasses(eles, this.propertyNames, updateTransitions);
  15720. };
  15721. styfn$7.removeBypasses = function (eles, props, updateTransitions) {
  15722. var isBypass = true;
  15723. for (var j = 0; j < eles.length; j++) {
  15724. var ele = eles[j];
  15725. var diffProps = {};
  15726. for (var i = 0; i < props.length; i++) {
  15727. var name = props[i];
  15728. var prop = this.properties[name];
  15729. var prevProp = ele.pstyle(prop.name);
  15730. if (!prevProp || !prevProp.bypass) {
  15731. // if a bypass doesn't exist for the prop, nothing needs to be removed
  15732. continue;
  15733. }
  15734. var value = ''; // empty => remove bypass
  15735. var parsedProp = this.parse(name, value, true);
  15736. var diffProp = diffProps[prop.name] = {
  15737. prev: prevProp
  15738. };
  15739. this.applyParsedProperty(ele, parsedProp);
  15740. diffProp.next = ele.pstyle(prop.name);
  15741. } // for props
  15742. this.updateStyleHints(ele);
  15743. if (updateTransitions) {
  15744. this.updateTransitions(ele, diffProps, isBypass);
  15745. }
  15746. } // for eles
  15747. };
  15748. var styfn$6 = {};
  15749. // gets what an em size corresponds to in pixels relative to a dom element
  15750. styfn$6.getEmSizeInPixels = function () {
  15751. var px = this.containerCss('font-size');
  15752. if (px != null) {
  15753. return parseFloat(px);
  15754. } else {
  15755. return 1; // for headless
  15756. }
  15757. };
  15758. // gets css property from the core container
  15759. styfn$6.containerCss = function (propName) {
  15760. var cy = this._private.cy;
  15761. var domElement = cy.container();
  15762. var containerWindow = cy.window();
  15763. if (containerWindow && domElement && containerWindow.getComputedStyle) {
  15764. return containerWindow.getComputedStyle(domElement).getPropertyValue(propName);
  15765. }
  15766. };
  15767. var styfn$5 = {};
  15768. // gets the rendered style for an element
  15769. styfn$5.getRenderedStyle = function (ele, prop) {
  15770. if (prop) {
  15771. return this.getStylePropertyValue(ele, prop, true);
  15772. } else {
  15773. return this.getRawStyle(ele, true);
  15774. }
  15775. };
  15776. // gets the raw style for an element
  15777. styfn$5.getRawStyle = function (ele, isRenderedVal) {
  15778. var self = this;
  15779. ele = ele[0]; // insure it's an element
  15780. if (ele) {
  15781. var rstyle = {};
  15782. for (var i = 0; i < self.properties.length; i++) {
  15783. var prop = self.properties[i];
  15784. var val = self.getStylePropertyValue(ele, prop.name, isRenderedVal);
  15785. if (val != null) {
  15786. rstyle[prop.name] = val;
  15787. rstyle[dash2camel(prop.name)] = val;
  15788. }
  15789. }
  15790. return rstyle;
  15791. }
  15792. };
  15793. styfn$5.getIndexedStyle = function (ele, property, subproperty, index) {
  15794. var pstyle = ele.pstyle(property)[subproperty][index];
  15795. return pstyle != null ? pstyle : ele.cy().style().getDefaultProperty(property)[subproperty][0];
  15796. };
  15797. styfn$5.getStylePropertyValue = function (ele, propName, isRenderedVal) {
  15798. var self = this;
  15799. ele = ele[0]; // insure it's an element
  15800. if (ele) {
  15801. var prop = self.properties[propName];
  15802. if (prop.alias) {
  15803. prop = prop.pointsTo;
  15804. }
  15805. var type = prop.type;
  15806. var styleProp = ele.pstyle(prop.name);
  15807. if (styleProp) {
  15808. var value = styleProp.value,
  15809. units = styleProp.units,
  15810. strValue = styleProp.strValue;
  15811. if (isRenderedVal && type.number && value != null && number$1(value)) {
  15812. var zoom = ele.cy().zoom();
  15813. var getRenderedValue = function getRenderedValue(val) {
  15814. return val * zoom;
  15815. };
  15816. var getValueStringWithUnits = function getValueStringWithUnits(val, units) {
  15817. return getRenderedValue(val) + units;
  15818. };
  15819. var isArrayValue = array(value);
  15820. var haveUnits = isArrayValue ? units.every(function (u) {
  15821. return u != null;
  15822. }) : units != null;
  15823. if (haveUnits) {
  15824. if (isArrayValue) {
  15825. return value.map(function (v, i) {
  15826. return getValueStringWithUnits(v, units[i]);
  15827. }).join(' ');
  15828. } else {
  15829. return getValueStringWithUnits(value, units);
  15830. }
  15831. } else {
  15832. if (isArrayValue) {
  15833. return value.map(function (v) {
  15834. return string(v) ? v : '' + getRenderedValue(v);
  15835. }).join(' ');
  15836. } else {
  15837. return '' + getRenderedValue(value);
  15838. }
  15839. }
  15840. } else if (strValue != null) {
  15841. return strValue;
  15842. }
  15843. }
  15844. return null;
  15845. }
  15846. };
  15847. styfn$5.getAnimationStartStyle = function (ele, aniProps) {
  15848. var rstyle = {};
  15849. for (var i = 0; i < aniProps.length; i++) {
  15850. var aniProp = aniProps[i];
  15851. var name = aniProp.name;
  15852. var styleProp = ele.pstyle(name);
  15853. if (styleProp !== undefined) {
  15854. // then make a prop of it
  15855. if (plainObject(styleProp)) {
  15856. styleProp = this.parse(name, styleProp.strValue);
  15857. } else {
  15858. styleProp = this.parse(name, styleProp);
  15859. }
  15860. }
  15861. if (styleProp) {
  15862. rstyle[name] = styleProp;
  15863. }
  15864. }
  15865. return rstyle;
  15866. };
  15867. styfn$5.getPropsList = function (propsObj) {
  15868. var self = this;
  15869. var rstyle = [];
  15870. var style = propsObj;
  15871. var props = self.properties;
  15872. if (style) {
  15873. var names = Object.keys(style);
  15874. for (var i = 0; i < names.length; i++) {
  15875. var name = names[i];
  15876. var val = style[name];
  15877. var prop = props[name] || props[camel2dash(name)];
  15878. var styleProp = this.parse(prop.name, val);
  15879. if (styleProp) {
  15880. rstyle.push(styleProp);
  15881. }
  15882. }
  15883. }
  15884. return rstyle;
  15885. };
  15886. styfn$5.getNonDefaultPropertiesHash = function (ele, propNames, seed) {
  15887. var hash = seed.slice();
  15888. var name, val, strVal, chVal;
  15889. var i, j;
  15890. for (i = 0; i < propNames.length; i++) {
  15891. name = propNames[i];
  15892. val = ele.pstyle(name, false);
  15893. if (val == null) {
  15894. continue;
  15895. } else if (val.pfValue != null) {
  15896. hash[0] = hashInt(chVal, hash[0]);
  15897. hash[1] = hashIntAlt(chVal, hash[1]);
  15898. } else {
  15899. strVal = val.strValue;
  15900. for (j = 0; j < strVal.length; j++) {
  15901. chVal = strVal.charCodeAt(j);
  15902. hash[0] = hashInt(chVal, hash[0]);
  15903. hash[1] = hashIntAlt(chVal, hash[1]);
  15904. }
  15905. }
  15906. }
  15907. return hash;
  15908. };
  15909. styfn$5.getPropertiesHash = styfn$5.getNonDefaultPropertiesHash;
  15910. var styfn$4 = {};
  15911. styfn$4.appendFromJson = function (json) {
  15912. var style = this;
  15913. for (var i = 0; i < json.length; i++) {
  15914. var context = json[i];
  15915. var selector = context.selector;
  15916. var props = context.style || context.css;
  15917. var names = Object.keys(props);
  15918. style.selector(selector); // apply selector
  15919. for (var j = 0; j < names.length; j++) {
  15920. var name = names[j];
  15921. var value = props[name];
  15922. style.css(name, value); // apply property
  15923. }
  15924. }
  15925. return style;
  15926. };
  15927. // accessible cy.style() function
  15928. styfn$4.fromJson = function (json) {
  15929. var style = this;
  15930. style.resetToDefault();
  15931. style.appendFromJson(json);
  15932. return style;
  15933. };
  15934. // get json from cy.style() api
  15935. styfn$4.json = function () {
  15936. var json = [];
  15937. for (var i = this.defaultLength; i < this.length; i++) {
  15938. var cxt = this[i];
  15939. var selector = cxt.selector;
  15940. var props = cxt.properties;
  15941. var css = {};
  15942. for (var j = 0; j < props.length; j++) {
  15943. var prop = props[j];
  15944. css[prop.name] = prop.strValue;
  15945. }
  15946. json.push({
  15947. selector: !selector ? 'core' : selector.toString(),
  15948. style: css
  15949. });
  15950. }
  15951. return json;
  15952. };
  15953. var styfn$3 = {};
  15954. styfn$3.appendFromString = function (string) {
  15955. var self = this;
  15956. var style = this;
  15957. var remaining = '' + string;
  15958. var selAndBlockStr;
  15959. var blockRem;
  15960. var propAndValStr;
  15961. // remove comments from the style string
  15962. remaining = remaining.replace(/[/][*](\s|.)+?[*][/]/g, '');
  15963. function removeSelAndBlockFromRemaining() {
  15964. // remove the parsed selector and block from the remaining text to parse
  15965. if (remaining.length > selAndBlockStr.length) {
  15966. remaining = remaining.substr(selAndBlockStr.length);
  15967. } else {
  15968. remaining = '';
  15969. }
  15970. }
  15971. function removePropAndValFromRem() {
  15972. // remove the parsed property and value from the remaining block text to parse
  15973. if (blockRem.length > propAndValStr.length) {
  15974. blockRem = blockRem.substr(propAndValStr.length);
  15975. } else {
  15976. blockRem = '';
  15977. }
  15978. }
  15979. for (;;) {
  15980. var nothingLeftToParse = remaining.match(/^\s*$/);
  15981. if (nothingLeftToParse) {
  15982. break;
  15983. }
  15984. var selAndBlock = remaining.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);
  15985. if (!selAndBlock) {
  15986. warn('Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: ' + remaining);
  15987. break;
  15988. }
  15989. selAndBlockStr = selAndBlock[0];
  15990. // parse the selector
  15991. var selectorStr = selAndBlock[1];
  15992. if (selectorStr !== 'core') {
  15993. var selector = new Selector(selectorStr);
  15994. if (selector.invalid) {
  15995. warn('Skipping parsing of block: Invalid selector found in string stylesheet: ' + selectorStr);
  15996. // skip this selector and block
  15997. removeSelAndBlockFromRemaining();
  15998. continue;
  15999. }
  16000. }
  16001. // parse the block of properties and values
  16002. var blockStr = selAndBlock[2];
  16003. var invalidBlock = false;
  16004. blockRem = blockStr;
  16005. var props = [];
  16006. for (;;) {
  16007. var _nothingLeftToParse = blockRem.match(/^\s*$/);
  16008. if (_nothingLeftToParse) {
  16009. break;
  16010. }
  16011. var propAndVal = blockRem.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);
  16012. if (!propAndVal) {
  16013. warn('Skipping parsing of block: Invalid formatting of style property and value definitions found in:' + blockStr);
  16014. invalidBlock = true;
  16015. break;
  16016. }
  16017. propAndValStr = propAndVal[0];
  16018. var propStr = propAndVal[1];
  16019. var valStr = propAndVal[2];
  16020. var prop = self.properties[propStr];
  16021. if (!prop) {
  16022. warn('Skipping property: Invalid property name in: ' + propAndValStr);
  16023. // skip this property in the block
  16024. removePropAndValFromRem();
  16025. continue;
  16026. }
  16027. var parsedProp = style.parse(propStr, valStr);
  16028. if (!parsedProp) {
  16029. warn('Skipping property: Invalid property definition in: ' + propAndValStr);
  16030. // skip this property in the block
  16031. removePropAndValFromRem();
  16032. continue;
  16033. }
  16034. props.push({
  16035. name: propStr,
  16036. val: valStr
  16037. });
  16038. removePropAndValFromRem();
  16039. }
  16040. if (invalidBlock) {
  16041. removeSelAndBlockFromRemaining();
  16042. break;
  16043. }
  16044. // put the parsed block in the style
  16045. style.selector(selectorStr);
  16046. for (var i = 0; i < props.length; i++) {
  16047. var _prop = props[i];
  16048. style.css(_prop.name, _prop.val);
  16049. }
  16050. removeSelAndBlockFromRemaining();
  16051. }
  16052. return style;
  16053. };
  16054. styfn$3.fromString = function (string) {
  16055. var style = this;
  16056. style.resetToDefault();
  16057. style.appendFromString(string);
  16058. return style;
  16059. };
  16060. var styfn$2 = {};
  16061. (function () {
  16062. var number$1 = number;
  16063. var rgba = rgbaNoBackRefs;
  16064. var hsla = hslaNoBackRefs;
  16065. var hex3$1 = hex3;
  16066. var hex6$1 = hex6;
  16067. var data = function data(prefix) {
  16068. return '^' + prefix + '\\s*\\(\\s*([\\w\\.]+)\\s*\\)$';
  16069. };
  16070. var mapData = function mapData(prefix) {
  16071. var mapArg = number$1 + '|\\w+|' + rgba + '|' + hsla + '|' + hex3$1 + '|' + hex6$1;
  16072. return '^' + prefix + '\\s*\\(([\\w\\.]+)\\s*\\,\\s*(' + number$1 + ')\\s*\\,\\s*(' + number$1 + ')\\s*,\\s*(' + mapArg + ')\\s*\\,\\s*(' + mapArg + ')\\)$';
  16073. };
  16074. var urlRegexes = ['^url\\s*\\(\\s*[\'"]?(.+?)[\'"]?\\s*\\)$', '^(none)$', '^(.+)$'];
  16075. // each visual style property has a type and needs to be validated according to it
  16076. styfn$2.types = {
  16077. time: {
  16078. number: true,
  16079. min: 0,
  16080. units: 's|ms',
  16081. implicitUnits: 'ms'
  16082. },
  16083. percent: {
  16084. number: true,
  16085. min: 0,
  16086. max: 100,
  16087. units: '%',
  16088. implicitUnits: '%'
  16089. },
  16090. percentages: {
  16091. number: true,
  16092. min: 0,
  16093. max: 100,
  16094. units: '%',
  16095. implicitUnits: '%',
  16096. multiple: true
  16097. },
  16098. zeroOneNumber: {
  16099. number: true,
  16100. min: 0,
  16101. max: 1,
  16102. unitless: true
  16103. },
  16104. zeroOneNumbers: {
  16105. number: true,
  16106. min: 0,
  16107. max: 1,
  16108. unitless: true,
  16109. multiple: true
  16110. },
  16111. nOneOneNumber: {
  16112. number: true,
  16113. min: -1,
  16114. max: 1,
  16115. unitless: true
  16116. },
  16117. nonNegativeInt: {
  16118. number: true,
  16119. min: 0,
  16120. integer: true,
  16121. unitless: true
  16122. },
  16123. nonNegativeNumber: {
  16124. number: true,
  16125. min: 0,
  16126. unitless: true
  16127. },
  16128. position: {
  16129. enums: ['parent', 'origin']
  16130. },
  16131. nodeSize: {
  16132. number: true,
  16133. min: 0,
  16134. enums: ['label']
  16135. },
  16136. number: {
  16137. number: true,
  16138. unitless: true
  16139. },
  16140. numbers: {
  16141. number: true,
  16142. unitless: true,
  16143. multiple: true
  16144. },
  16145. positiveNumber: {
  16146. number: true,
  16147. unitless: true,
  16148. min: 0,
  16149. strictMin: true
  16150. },
  16151. size: {
  16152. number: true,
  16153. min: 0
  16154. },
  16155. bidirectionalSize: {
  16156. number: true
  16157. },
  16158. // allows negative
  16159. bidirectionalSizeMaybePercent: {
  16160. number: true,
  16161. allowPercent: true
  16162. },
  16163. // allows negative
  16164. bidirectionalSizes: {
  16165. number: true,
  16166. multiple: true
  16167. },
  16168. // allows negative
  16169. sizeMaybePercent: {
  16170. number: true,
  16171. min: 0,
  16172. allowPercent: true
  16173. },
  16174. axisDirection: {
  16175. enums: ['horizontal', 'leftward', 'rightward', 'vertical', 'upward', 'downward', 'auto']
  16176. },
  16177. axisDirectionExplicit: {
  16178. enums: ['leftward', 'rightward', 'upward', 'downward']
  16179. },
  16180. axisDirectionPrimary: {
  16181. enums: ['horizontal', 'vertical']
  16182. },
  16183. paddingRelativeTo: {
  16184. enums: ['width', 'height', 'average', 'min', 'max']
  16185. },
  16186. bgWH: {
  16187. number: true,
  16188. min: 0,
  16189. allowPercent: true,
  16190. enums: ['auto'],
  16191. multiple: true
  16192. },
  16193. bgPos: {
  16194. number: true,
  16195. allowPercent: true,
  16196. multiple: true
  16197. },
  16198. bgRelativeTo: {
  16199. enums: ['inner', 'include-padding'],
  16200. multiple: true
  16201. },
  16202. bgRepeat: {
  16203. enums: ['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],
  16204. multiple: true
  16205. },
  16206. bgFit: {
  16207. enums: ['none', 'contain', 'cover'],
  16208. multiple: true
  16209. },
  16210. bgCrossOrigin: {
  16211. enums: ['anonymous', 'use-credentials', 'null'],
  16212. multiple: true
  16213. },
  16214. bgClip: {
  16215. enums: ['none', 'node'],
  16216. multiple: true
  16217. },
  16218. bgContainment: {
  16219. enums: ['inside', 'over'],
  16220. multiple: true
  16221. },
  16222. boxSelection: {
  16223. enums: ['contain', 'overlap', 'none']
  16224. },
  16225. color: {
  16226. color: true
  16227. },
  16228. colors: {
  16229. color: true,
  16230. multiple: true
  16231. },
  16232. fill: {
  16233. enums: ['solid', 'linear-gradient', 'radial-gradient']
  16234. },
  16235. bool: {
  16236. enums: ['yes', 'no']
  16237. },
  16238. bools: {
  16239. enums: ['yes', 'no'],
  16240. multiple: true
  16241. },
  16242. lineStyle: {
  16243. enums: ['solid', 'dotted', 'dashed']
  16244. },
  16245. lineCap: {
  16246. enums: ['butt', 'round', 'square']
  16247. },
  16248. linePosition: {
  16249. enums: ['center', 'inside', 'outside']
  16250. },
  16251. lineJoin: {
  16252. enums: ['round', 'bevel', 'miter']
  16253. },
  16254. borderStyle: {
  16255. enums: ['solid', 'dotted', 'dashed', 'double']
  16256. },
  16257. curveStyle: {
  16258. enums: ['bezier', 'unbundled-bezier', 'haystack', 'segments', 'straight', 'straight-triangle', 'taxi', 'round-segments', 'round-taxi']
  16259. },
  16260. radiusType: {
  16261. enums: ['arc-radius', 'influence-radius'],
  16262. multiple: true
  16263. },
  16264. fontFamily: {
  16265. regex: '^([\\w- \\"]+(?:\\s*,\\s*[\\w- \\"]+)*)$'
  16266. },
  16267. fontStyle: {
  16268. enums: ['italic', 'normal', 'oblique']
  16269. },
  16270. fontWeight: {
  16271. enums: ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '800', '900', 100, 200, 300, 400, 500, 600, 700, 800, 900]
  16272. },
  16273. textDecoration: {
  16274. enums: ['none', 'underline', 'overline', 'line-through']
  16275. },
  16276. textTransform: {
  16277. enums: ['none', 'uppercase', 'lowercase']
  16278. },
  16279. textWrap: {
  16280. enums: ['none', 'wrap', 'ellipsis']
  16281. },
  16282. textOverflowWrap: {
  16283. enums: ['whitespace', 'anywhere']
  16284. },
  16285. textBackgroundShape: {
  16286. enums: ['rectangle', 'roundrectangle', 'round-rectangle', 'circle']
  16287. },
  16288. nodeShape: {
  16289. 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']
  16290. },
  16291. overlayShape: {
  16292. enums: ['roundrectangle', 'round-rectangle', 'ellipse']
  16293. },
  16294. cornerRadius: {
  16295. number: true,
  16296. min: 0,
  16297. units: 'px|em',
  16298. implicitUnits: 'px',
  16299. enums: ['auto']
  16300. },
  16301. compoundIncludeLabels: {
  16302. enums: ['include', 'exclude']
  16303. },
  16304. arrowShape: {
  16305. enums: ['tee', 'triangle', 'triangle-tee', 'circle-triangle', 'triangle-cross', 'triangle-backcurve', 'vee', 'square', 'circle', 'diamond', 'chevron', 'none']
  16306. },
  16307. arrowFill: {
  16308. enums: ['filled', 'hollow']
  16309. },
  16310. arrowWidth: {
  16311. number: true,
  16312. units: '%|px|em',
  16313. implicitUnits: 'px',
  16314. enums: ['match-line']
  16315. },
  16316. display: {
  16317. enums: ['element', 'none']
  16318. },
  16319. visibility: {
  16320. enums: ['hidden', 'visible']
  16321. },
  16322. zCompoundDepth: {
  16323. enums: ['bottom', 'orphan', 'auto', 'top']
  16324. },
  16325. zIndexCompare: {
  16326. enums: ['auto', 'manual']
  16327. },
  16328. valign: {
  16329. enums: ['top', 'center', 'bottom']
  16330. },
  16331. halign: {
  16332. enums: ['left', 'center', 'right']
  16333. },
  16334. justification: {
  16335. enums: ['left', 'center', 'right', 'auto']
  16336. },
  16337. text: {
  16338. string: true
  16339. },
  16340. data: {
  16341. mapping: true,
  16342. regex: data('data')
  16343. },
  16344. layoutData: {
  16345. mapping: true,
  16346. regex: data('layoutData')
  16347. },
  16348. scratch: {
  16349. mapping: true,
  16350. regex: data('scratch')
  16351. },
  16352. mapData: {
  16353. mapping: true,
  16354. regex: mapData('mapData')
  16355. },
  16356. mapLayoutData: {
  16357. mapping: true,
  16358. regex: mapData('mapLayoutData')
  16359. },
  16360. mapScratch: {
  16361. mapping: true,
  16362. regex: mapData('mapScratch')
  16363. },
  16364. fn: {
  16365. mapping: true,
  16366. fn: true
  16367. },
  16368. url: {
  16369. regexes: urlRegexes,
  16370. singleRegexMatchValue: true
  16371. },
  16372. urls: {
  16373. regexes: urlRegexes,
  16374. singleRegexMatchValue: true,
  16375. multiple: true
  16376. },
  16377. propList: {
  16378. propList: true
  16379. },
  16380. angle: {
  16381. number: true,
  16382. units: 'deg|rad',
  16383. implicitUnits: 'rad'
  16384. },
  16385. textRotation: {
  16386. number: true,
  16387. units: 'deg|rad',
  16388. implicitUnits: 'rad',
  16389. enums: ['none', 'autorotate']
  16390. },
  16391. polygonPointList: {
  16392. number: true,
  16393. multiple: true,
  16394. evenMultiple: true,
  16395. min: -1,
  16396. max: 1,
  16397. unitless: true
  16398. },
  16399. edgeDistances: {
  16400. enums: ['intersection', 'node-position', 'endpoints']
  16401. },
  16402. edgeEndpoint: {
  16403. number: true,
  16404. multiple: true,
  16405. units: '%|px|em|deg|rad',
  16406. implicitUnits: 'px',
  16407. enums: ['inside-to-node', 'outside-to-node', 'outside-to-node-or-label', 'outside-to-line', 'outside-to-line-or-label'],
  16408. singleEnum: true,
  16409. validate: function validate(valArr, unitsArr) {
  16410. switch (valArr.length) {
  16411. case 2:
  16412. // can be % or px only
  16413. return unitsArr[0] !== 'deg' && unitsArr[0] !== 'rad' && unitsArr[1] !== 'deg' && unitsArr[1] !== 'rad';
  16414. case 1:
  16415. // can be enum, deg, or rad only
  16416. return string(valArr[0]) || unitsArr[0] === 'deg' || unitsArr[0] === 'rad';
  16417. default:
  16418. return false;
  16419. }
  16420. }
  16421. },
  16422. easing: {
  16423. 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*\\)$'],
  16424. 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']
  16425. },
  16426. gradientDirection: {
  16427. 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
  16428. ]
  16429. },
  16430. boundsExpansion: {
  16431. number: true,
  16432. multiple: true,
  16433. min: 0,
  16434. validate: function validate(valArr) {
  16435. var length = valArr.length;
  16436. return length === 1 || length === 2 || length === 4;
  16437. }
  16438. }
  16439. };
  16440. var diff = {
  16441. zeroNonZero: function zeroNonZero(val1, val2) {
  16442. if ((val1 == null || val2 == null) && val1 !== val2) {
  16443. return true; // null cases could represent any value
  16444. }
  16445. if (val1 == 0 && val2 != 0) {
  16446. return true;
  16447. } else if (val1 != 0 && val2 == 0) {
  16448. return true;
  16449. } else {
  16450. return false;
  16451. }
  16452. },
  16453. any: function any(val1, val2) {
  16454. return val1 != val2;
  16455. },
  16456. emptyNonEmpty: function emptyNonEmpty(str1, str2) {
  16457. var empty1 = emptyString(str1);
  16458. var empty2 = emptyString(str2);
  16459. return empty1 && !empty2 || !empty1 && empty2;
  16460. }
  16461. };
  16462. // define visual style properties
  16463. //
  16464. // - n.b. adding a new group of props may require updates to updateStyleHints()
  16465. // - adding new props to an existing group gets handled automatically
  16466. var t = styfn$2.types;
  16467. var mainLabel = [{
  16468. name: 'label',
  16469. type: t.text,
  16470. triggersBounds: diff.any,
  16471. triggersZOrder: diff.emptyNonEmpty
  16472. }, {
  16473. name: 'text-rotation',
  16474. type: t.textRotation,
  16475. triggersBounds: diff.any
  16476. }, {
  16477. name: 'text-margin-x',
  16478. type: t.bidirectionalSize,
  16479. triggersBounds: diff.any
  16480. }, {
  16481. name: 'text-margin-y',
  16482. type: t.bidirectionalSize,
  16483. triggersBounds: diff.any
  16484. }];
  16485. var sourceLabel = [{
  16486. name: 'source-label',
  16487. type: t.text,
  16488. triggersBounds: diff.any
  16489. }, {
  16490. name: 'source-text-rotation',
  16491. type: t.textRotation,
  16492. triggersBounds: diff.any
  16493. }, {
  16494. name: 'source-text-margin-x',
  16495. type: t.bidirectionalSize,
  16496. triggersBounds: diff.any
  16497. }, {
  16498. name: 'source-text-margin-y',
  16499. type: t.bidirectionalSize,
  16500. triggersBounds: diff.any
  16501. }, {
  16502. name: 'source-text-offset',
  16503. type: t.size,
  16504. triggersBounds: diff.any
  16505. }];
  16506. var targetLabel = [{
  16507. name: 'target-label',
  16508. type: t.text,
  16509. triggersBounds: diff.any
  16510. }, {
  16511. name: 'target-text-rotation',
  16512. type: t.textRotation,
  16513. triggersBounds: diff.any
  16514. }, {
  16515. name: 'target-text-margin-x',
  16516. type: t.bidirectionalSize,
  16517. triggersBounds: diff.any
  16518. }, {
  16519. name: 'target-text-margin-y',
  16520. type: t.bidirectionalSize,
  16521. triggersBounds: diff.any
  16522. }, {
  16523. name: 'target-text-offset',
  16524. type: t.size,
  16525. triggersBounds: diff.any
  16526. }];
  16527. var labelDimensions = [{
  16528. name: 'font-family',
  16529. type: t.fontFamily,
  16530. triggersBounds: diff.any
  16531. }, {
  16532. name: 'font-style',
  16533. type: t.fontStyle,
  16534. triggersBounds: diff.any
  16535. }, {
  16536. name: 'font-weight',
  16537. type: t.fontWeight,
  16538. triggersBounds: diff.any
  16539. }, {
  16540. name: 'font-size',
  16541. type: t.size,
  16542. triggersBounds: diff.any
  16543. }, {
  16544. name: 'text-transform',
  16545. type: t.textTransform,
  16546. triggersBounds: diff.any
  16547. }, {
  16548. name: 'text-wrap',
  16549. type: t.textWrap,
  16550. triggersBounds: diff.any
  16551. }, {
  16552. name: 'text-overflow-wrap',
  16553. type: t.textOverflowWrap,
  16554. triggersBounds: diff.any
  16555. }, {
  16556. name: 'text-max-width',
  16557. type: t.size,
  16558. triggersBounds: diff.any
  16559. }, {
  16560. name: 'text-outline-width',
  16561. type: t.size,
  16562. triggersBounds: diff.any
  16563. }, {
  16564. name: 'line-height',
  16565. type: t.positiveNumber,
  16566. triggersBounds: diff.any
  16567. }];
  16568. var commonLabel = [{
  16569. name: 'text-valign',
  16570. type: t.valign,
  16571. triggersBounds: diff.any
  16572. }, {
  16573. name: 'text-halign',
  16574. type: t.halign,
  16575. triggersBounds: diff.any
  16576. }, {
  16577. name: 'color',
  16578. type: t.color
  16579. }, {
  16580. name: 'text-outline-color',
  16581. type: t.color
  16582. }, {
  16583. name: 'text-outline-opacity',
  16584. type: t.zeroOneNumber
  16585. }, {
  16586. name: 'text-background-color',
  16587. type: t.color
  16588. }, {
  16589. name: 'text-background-opacity',
  16590. type: t.zeroOneNumber
  16591. }, {
  16592. name: 'text-background-padding',
  16593. type: t.size,
  16594. triggersBounds: diff.any
  16595. }, {
  16596. name: 'text-border-opacity',
  16597. type: t.zeroOneNumber
  16598. }, {
  16599. name: 'text-border-color',
  16600. type: t.color
  16601. }, {
  16602. name: 'text-border-width',
  16603. type: t.size,
  16604. triggersBounds: diff.any
  16605. }, {
  16606. name: 'text-border-style',
  16607. type: t.borderStyle,
  16608. triggersBounds: diff.any
  16609. }, {
  16610. name: 'text-background-shape',
  16611. type: t.textBackgroundShape,
  16612. triggersBounds: diff.any
  16613. }, {
  16614. name: 'text-justification',
  16615. type: t.justification
  16616. }, {
  16617. name: 'box-select-labels',
  16618. type: t.bool,
  16619. triggersBounds: diff.any
  16620. }];
  16621. var behavior = [{
  16622. name: 'events',
  16623. type: t.bool,
  16624. triggersZOrder: diff.any
  16625. }, {
  16626. name: 'text-events',
  16627. type: t.bool,
  16628. triggersZOrder: diff.any
  16629. }, {
  16630. name: 'box-selection',
  16631. type: t.boxSelection,
  16632. triggersZOrder: diff.any
  16633. }];
  16634. var visibility = [{
  16635. name: 'display',
  16636. type: t.display,
  16637. triggersZOrder: diff.any,
  16638. triggersBounds: diff.any,
  16639. triggersBoundsOfConnectedEdges: diff.any,
  16640. triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue, ele) {
  16641. if (fromValue === toValue) {
  16642. return false;
  16643. }
  16644. // only if edge is bundled bezier (so as not to affect performance of other edges)
  16645. return ele.pstyle('curve-style').value === 'bezier';
  16646. }
  16647. }, {
  16648. name: 'visibility',
  16649. type: t.visibility,
  16650. triggersZOrder: diff.any
  16651. }, {
  16652. name: 'opacity',
  16653. type: t.zeroOneNumber,
  16654. triggersZOrder: diff.zeroNonZero
  16655. }, {
  16656. name: 'text-opacity',
  16657. type: t.zeroOneNumber
  16658. }, {
  16659. name: 'min-zoomed-font-size',
  16660. type: t.size
  16661. }, {
  16662. name: 'z-compound-depth',
  16663. type: t.zCompoundDepth,
  16664. triggersZOrder: diff.any
  16665. }, {
  16666. name: 'z-index-compare',
  16667. type: t.zIndexCompare,
  16668. triggersZOrder: diff.any
  16669. }, {
  16670. name: 'z-index',
  16671. type: t.number,
  16672. triggersZOrder: diff.any
  16673. }];
  16674. var overlay = [{
  16675. name: 'overlay-padding',
  16676. type: t.size,
  16677. triggersBounds: diff.any
  16678. }, {
  16679. name: 'overlay-color',
  16680. type: t.color
  16681. }, {
  16682. name: 'overlay-opacity',
  16683. type: t.zeroOneNumber,
  16684. triggersBounds: diff.zeroNonZero
  16685. }, {
  16686. name: 'overlay-shape',
  16687. type: t.overlayShape,
  16688. triggersBounds: diff.any
  16689. }, {
  16690. name: 'overlay-corner-radius',
  16691. type: t.cornerRadius
  16692. }];
  16693. var underlay = [{
  16694. name: 'underlay-padding',
  16695. type: t.size,
  16696. triggersBounds: diff.any
  16697. }, {
  16698. name: 'underlay-color',
  16699. type: t.color
  16700. }, {
  16701. name: 'underlay-opacity',
  16702. type: t.zeroOneNumber,
  16703. triggersBounds: diff.zeroNonZero
  16704. }, {
  16705. name: 'underlay-shape',
  16706. type: t.overlayShape,
  16707. triggersBounds: diff.any
  16708. }, {
  16709. name: 'underlay-corner-radius',
  16710. type: t.cornerRadius
  16711. }];
  16712. var transition = [{
  16713. name: 'transition-property',
  16714. type: t.propList
  16715. }, {
  16716. name: 'transition-duration',
  16717. type: t.time
  16718. }, {
  16719. name: 'transition-delay',
  16720. type: t.time
  16721. }, {
  16722. name: 'transition-timing-function',
  16723. type: t.easing
  16724. }];
  16725. var nodeSizeHashOverride = function nodeSizeHashOverride(ele, parsedProp) {
  16726. if (parsedProp.value === 'label') {
  16727. return -ele.poolIndex(); // no hash key hits is using label size (hitrate for perf probably low anyway)
  16728. } else {
  16729. return parsedProp.pfValue;
  16730. }
  16731. };
  16732. var nodeBody = [{
  16733. name: 'height',
  16734. type: t.nodeSize,
  16735. triggersBounds: diff.any,
  16736. hashOverride: nodeSizeHashOverride
  16737. }, {
  16738. name: 'width',
  16739. type: t.nodeSize,
  16740. triggersBounds: diff.any,
  16741. hashOverride: nodeSizeHashOverride
  16742. }, {
  16743. name: 'shape',
  16744. type: t.nodeShape,
  16745. triggersBounds: diff.any
  16746. }, {
  16747. name: 'shape-polygon-points',
  16748. type: t.polygonPointList,
  16749. triggersBounds: diff.any
  16750. }, {
  16751. name: 'corner-radius',
  16752. type: t.cornerRadius
  16753. }, {
  16754. name: 'background-color',
  16755. type: t.color
  16756. }, {
  16757. name: 'background-fill',
  16758. type: t.fill
  16759. }, {
  16760. name: 'background-opacity',
  16761. type: t.zeroOneNumber
  16762. }, {
  16763. name: 'background-blacken',
  16764. type: t.nOneOneNumber
  16765. }, {
  16766. name: 'background-gradient-stop-colors',
  16767. type: t.colors
  16768. }, {
  16769. name: 'background-gradient-stop-positions',
  16770. type: t.percentages
  16771. }, {
  16772. name: 'background-gradient-direction',
  16773. type: t.gradientDirection
  16774. }, {
  16775. name: 'padding',
  16776. type: t.sizeMaybePercent,
  16777. triggersBounds: diff.any
  16778. }, {
  16779. name: 'padding-relative-to',
  16780. type: t.paddingRelativeTo,
  16781. triggersBounds: diff.any
  16782. }, {
  16783. name: 'bounds-expansion',
  16784. type: t.boundsExpansion,
  16785. triggersBounds: diff.any
  16786. }];
  16787. var nodeBorder = [{
  16788. name: 'border-color',
  16789. type: t.color
  16790. }, {
  16791. name: 'border-opacity',
  16792. type: t.zeroOneNumber
  16793. }, {
  16794. name: 'border-width',
  16795. type: t.size,
  16796. triggersBounds: diff.any
  16797. }, {
  16798. name: 'border-style',
  16799. type: t.borderStyle
  16800. }, {
  16801. name: 'border-cap',
  16802. type: t.lineCap
  16803. }, {
  16804. name: 'border-join',
  16805. type: t.lineJoin
  16806. }, {
  16807. name: 'border-dash-pattern',
  16808. type: t.numbers
  16809. }, {
  16810. name: 'border-dash-offset',
  16811. type: t.number
  16812. }, {
  16813. name: 'border-position',
  16814. type: t.linePosition
  16815. }];
  16816. var nodeOutline = [{
  16817. name: 'outline-color',
  16818. type: t.color
  16819. }, {
  16820. name: 'outline-opacity',
  16821. type: t.zeroOneNumber
  16822. }, {
  16823. name: 'outline-width',
  16824. type: t.size,
  16825. triggersBounds: diff.any
  16826. }, {
  16827. name: 'outline-style',
  16828. type: t.borderStyle
  16829. }, {
  16830. name: 'outline-offset',
  16831. type: t.size,
  16832. triggersBounds: diff.any
  16833. }];
  16834. var backgroundImage = [{
  16835. name: 'background-image',
  16836. type: t.urls
  16837. }, {
  16838. name: 'background-image-crossorigin',
  16839. type: t.bgCrossOrigin
  16840. }, {
  16841. name: 'background-image-opacity',
  16842. type: t.zeroOneNumbers
  16843. }, {
  16844. name: 'background-image-containment',
  16845. type: t.bgContainment
  16846. }, {
  16847. name: 'background-image-smoothing',
  16848. type: t.bools
  16849. }, {
  16850. name: 'background-position-x',
  16851. type: t.bgPos
  16852. }, {
  16853. name: 'background-position-y',
  16854. type: t.bgPos
  16855. }, {
  16856. name: 'background-width-relative-to',
  16857. type: t.bgRelativeTo
  16858. }, {
  16859. name: 'background-height-relative-to',
  16860. type: t.bgRelativeTo
  16861. }, {
  16862. name: 'background-repeat',
  16863. type: t.bgRepeat
  16864. }, {
  16865. name: 'background-fit',
  16866. type: t.bgFit
  16867. }, {
  16868. name: 'background-clip',
  16869. type: t.bgClip
  16870. }, {
  16871. name: 'background-width',
  16872. type: t.bgWH
  16873. }, {
  16874. name: 'background-height',
  16875. type: t.bgWH
  16876. }, {
  16877. name: 'background-offset-x',
  16878. type: t.bgPos
  16879. }, {
  16880. name: 'background-offset-y',
  16881. type: t.bgPos
  16882. }];
  16883. var compound = [{
  16884. name: 'position',
  16885. type: t.position,
  16886. triggersBounds: diff.any
  16887. }, {
  16888. name: 'compound-sizing-wrt-labels',
  16889. type: t.compoundIncludeLabels,
  16890. triggersBounds: diff.any
  16891. }, {
  16892. name: 'min-width',
  16893. type: t.size,
  16894. triggersBounds: diff.any
  16895. }, {
  16896. name: 'min-width-bias-left',
  16897. type: t.sizeMaybePercent,
  16898. triggersBounds: diff.any
  16899. }, {
  16900. name: 'min-width-bias-right',
  16901. type: t.sizeMaybePercent,
  16902. triggersBounds: diff.any
  16903. }, {
  16904. name: 'min-height',
  16905. type: t.size,
  16906. triggersBounds: diff.any
  16907. }, {
  16908. name: 'min-height-bias-top',
  16909. type: t.sizeMaybePercent,
  16910. triggersBounds: diff.any
  16911. }, {
  16912. name: 'min-height-bias-bottom',
  16913. type: t.sizeMaybePercent,
  16914. triggersBounds: diff.any
  16915. }];
  16916. var edgeLine = [{
  16917. name: 'line-style',
  16918. type: t.lineStyle
  16919. }, {
  16920. name: 'line-color',
  16921. type: t.color
  16922. }, {
  16923. name: 'line-fill',
  16924. type: t.fill
  16925. }, {
  16926. name: 'line-cap',
  16927. type: t.lineCap
  16928. }, {
  16929. name: 'line-opacity',
  16930. type: t.zeroOneNumber
  16931. }, {
  16932. name: 'line-dash-pattern',
  16933. type: t.numbers
  16934. }, {
  16935. name: 'line-dash-offset',
  16936. type: t.number
  16937. }, {
  16938. name: 'line-outline-width',
  16939. type: t.size
  16940. }, {
  16941. name: 'line-outline-color',
  16942. type: t.color
  16943. }, {
  16944. name: 'line-gradient-stop-colors',
  16945. type: t.colors
  16946. }, {
  16947. name: 'line-gradient-stop-positions',
  16948. type: t.percentages
  16949. }, {
  16950. name: 'curve-style',
  16951. type: t.curveStyle,
  16952. triggersBounds: diff.any,
  16953. triggersBoundsOfParallelEdges: function triggersBoundsOfParallelEdges(fromValue, toValue) {
  16954. if (fromValue === toValue) {
  16955. return false;
  16956. } // must have diff
  16957. return fromValue === 'bezier' ||
  16958. // remove from bundle
  16959. toValue === 'bezier'; // add to bundle
  16960. }
  16961. }, {
  16962. name: 'haystack-radius',
  16963. type: t.zeroOneNumber,
  16964. triggersBounds: diff.any
  16965. }, {
  16966. name: 'source-endpoint',
  16967. type: t.edgeEndpoint,
  16968. triggersBounds: diff.any
  16969. }, {
  16970. name: 'target-endpoint',
  16971. type: t.edgeEndpoint,
  16972. triggersBounds: diff.any
  16973. }, {
  16974. name: 'control-point-step-size',
  16975. type: t.size,
  16976. triggersBounds: diff.any
  16977. }, {
  16978. name: 'control-point-distances',
  16979. type: t.bidirectionalSizes,
  16980. triggersBounds: diff.any
  16981. }, {
  16982. name: 'control-point-weights',
  16983. type: t.numbers,
  16984. triggersBounds: diff.any
  16985. }, {
  16986. name: 'segment-distances',
  16987. type: t.bidirectionalSizes,
  16988. triggersBounds: diff.any
  16989. }, {
  16990. name: 'segment-weights',
  16991. type: t.numbers,
  16992. triggersBounds: diff.any
  16993. }, {
  16994. name: 'segment-radii',
  16995. type: t.numbers,
  16996. triggersBounds: diff.any
  16997. }, {
  16998. name: 'radius-type',
  16999. type: t.radiusType,
  17000. triggersBounds: diff.any
  17001. }, {
  17002. name: 'taxi-turn',
  17003. type: t.bidirectionalSizeMaybePercent,
  17004. triggersBounds: diff.any
  17005. }, {
  17006. name: 'taxi-turn-min-distance',
  17007. type: t.size,
  17008. triggersBounds: diff.any
  17009. }, {
  17010. name: 'taxi-direction',
  17011. type: t.axisDirection,
  17012. triggersBounds: diff.any
  17013. }, {
  17014. name: 'taxi-radius',
  17015. type: t.number,
  17016. triggersBounds: diff.any
  17017. }, {
  17018. name: 'edge-distances',
  17019. type: t.edgeDistances,
  17020. triggersBounds: diff.any
  17021. }, {
  17022. name: 'arrow-scale',
  17023. type: t.positiveNumber,
  17024. triggersBounds: diff.any
  17025. }, {
  17026. name: 'loop-direction',
  17027. type: t.angle,
  17028. triggersBounds: diff.any
  17029. }, {
  17030. name: 'loop-sweep',
  17031. type: t.angle,
  17032. triggersBounds: diff.any
  17033. }, {
  17034. name: 'source-distance-from-node',
  17035. type: t.size,
  17036. triggersBounds: diff.any
  17037. }, {
  17038. name: 'target-distance-from-node',
  17039. type: t.size,
  17040. triggersBounds: diff.any
  17041. }];
  17042. var ghost = [{
  17043. name: 'ghost',
  17044. type: t.bool,
  17045. triggersBounds: diff.any
  17046. }, {
  17047. name: 'ghost-offset-x',
  17048. type: t.bidirectionalSize,
  17049. triggersBounds: diff.any
  17050. }, {
  17051. name: 'ghost-offset-y',
  17052. type: t.bidirectionalSize,
  17053. triggersBounds: diff.any
  17054. }, {
  17055. name: 'ghost-opacity',
  17056. type: t.zeroOneNumber
  17057. }];
  17058. var core = [{
  17059. name: 'selection-box-color',
  17060. type: t.color
  17061. }, {
  17062. name: 'selection-box-opacity',
  17063. type: t.zeroOneNumber
  17064. }, {
  17065. name: 'selection-box-border-color',
  17066. type: t.color
  17067. }, {
  17068. name: 'selection-box-border-width',
  17069. type: t.size
  17070. }, {
  17071. name: 'active-bg-color',
  17072. type: t.color
  17073. }, {
  17074. name: 'active-bg-opacity',
  17075. type: t.zeroOneNumber
  17076. }, {
  17077. name: 'active-bg-size',
  17078. type: t.size
  17079. }, {
  17080. name: 'outside-texture-bg-color',
  17081. type: t.color
  17082. }, {
  17083. name: 'outside-texture-bg-opacity',
  17084. type: t.zeroOneNumber
  17085. }];
  17086. // pie backgrounds for nodes
  17087. var pie = [];
  17088. styfn$2.pieBackgroundN = 16; // because the pie properties are numbered, give access to a constant N (for renderer use)
  17089. pie.push({
  17090. name: 'pie-size',
  17091. type: t.sizeMaybePercent
  17092. });
  17093. pie.push({
  17094. name: 'pie-hole',
  17095. type: t.sizeMaybePercent
  17096. });
  17097. pie.push({
  17098. name: 'pie-start-angle',
  17099. type: t.angle
  17100. });
  17101. for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
  17102. pie.push({
  17103. name: 'pie-' + i + '-background-color',
  17104. type: t.color
  17105. });
  17106. pie.push({
  17107. name: 'pie-' + i + '-background-size',
  17108. type: t.percent
  17109. });
  17110. pie.push({
  17111. name: 'pie-' + i + '-background-opacity',
  17112. type: t.zeroOneNumber
  17113. });
  17114. }
  17115. // stripe backgrounds for nodes
  17116. var stripe = [];
  17117. styfn$2.stripeBackgroundN = 16; // because the stripe properties are numbered, give access to a constant N (for renderer use)
  17118. stripe.push({
  17119. name: 'stripe-size',
  17120. type: t.sizeMaybePercent
  17121. });
  17122. stripe.push({
  17123. name: 'stripe-direction',
  17124. type: t.axisDirectionPrimary
  17125. });
  17126. for (var _i = 1; _i <= styfn$2.stripeBackgroundN; _i++) {
  17127. stripe.push({
  17128. name: 'stripe-' + _i + '-background-color',
  17129. type: t.color
  17130. });
  17131. stripe.push({
  17132. name: 'stripe-' + _i + '-background-size',
  17133. type: t.percent
  17134. });
  17135. stripe.push({
  17136. name: 'stripe-' + _i + '-background-opacity',
  17137. type: t.zeroOneNumber
  17138. });
  17139. }
  17140. // edge arrows
  17141. var edgeArrow = [];
  17142. var arrowPrefixes = styfn$2.arrowPrefixes = ['source', 'mid-source', 'target', 'mid-target'];
  17143. [{
  17144. name: 'arrow-shape',
  17145. type: t.arrowShape,
  17146. triggersBounds: diff.any
  17147. }, {
  17148. name: 'arrow-color',
  17149. type: t.color
  17150. }, {
  17151. name: 'arrow-fill',
  17152. type: t.arrowFill
  17153. }, {
  17154. name: 'arrow-width',
  17155. type: t.arrowWidth
  17156. }].forEach(function (prop) {
  17157. arrowPrefixes.forEach(function (prefix) {
  17158. var name = prefix + '-' + prop.name;
  17159. var type = prop.type,
  17160. triggersBounds = prop.triggersBounds;
  17161. edgeArrow.push({
  17162. name: name,
  17163. type: type,
  17164. triggersBounds: triggersBounds
  17165. });
  17166. });
  17167. }, {});
  17168. 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);
  17169. var propGroups = styfn$2.propertyGroups = {
  17170. // common to all eles
  17171. behavior: behavior,
  17172. transition: transition,
  17173. visibility: visibility,
  17174. overlay: overlay,
  17175. underlay: underlay,
  17176. ghost: ghost,
  17177. // labels
  17178. commonLabel: commonLabel,
  17179. labelDimensions: labelDimensions,
  17180. mainLabel: mainLabel,
  17181. sourceLabel: sourceLabel,
  17182. targetLabel: targetLabel,
  17183. // node props
  17184. nodeBody: nodeBody,
  17185. nodeBorder: nodeBorder,
  17186. nodeOutline: nodeOutline,
  17187. backgroundImage: backgroundImage,
  17188. pie: pie,
  17189. stripe: stripe,
  17190. compound: compound,
  17191. // edge props
  17192. edgeLine: edgeLine,
  17193. edgeArrow: edgeArrow,
  17194. core: core
  17195. };
  17196. var propGroupNames = styfn$2.propertyGroupNames = {};
  17197. var propGroupKeys = styfn$2.propertyGroupKeys = Object.keys(propGroups);
  17198. propGroupKeys.forEach(function (key) {
  17199. propGroupNames[key] = propGroups[key].map(function (prop) {
  17200. return prop.name;
  17201. });
  17202. propGroups[key].forEach(function (prop) {
  17203. return prop.groupKey = key;
  17204. });
  17205. });
  17206. // define aliases
  17207. var aliases = styfn$2.aliases = [{
  17208. name: 'content',
  17209. pointsTo: 'label'
  17210. }, {
  17211. name: 'control-point-distance',
  17212. pointsTo: 'control-point-distances'
  17213. }, {
  17214. name: 'control-point-weight',
  17215. pointsTo: 'control-point-weights'
  17216. }, {
  17217. name: 'segment-distance',
  17218. pointsTo: 'segment-distances'
  17219. }, {
  17220. name: 'segment-weight',
  17221. pointsTo: 'segment-weights'
  17222. }, {
  17223. name: 'segment-radius',
  17224. pointsTo: 'segment-radii'
  17225. }, {
  17226. name: 'edge-text-rotation',
  17227. pointsTo: 'text-rotation'
  17228. }, {
  17229. name: 'padding-left',
  17230. pointsTo: 'padding'
  17231. }, {
  17232. name: 'padding-right',
  17233. pointsTo: 'padding'
  17234. }, {
  17235. name: 'padding-top',
  17236. pointsTo: 'padding'
  17237. }, {
  17238. name: 'padding-bottom',
  17239. pointsTo: 'padding'
  17240. }];
  17241. // list of property names
  17242. styfn$2.propertyNames = props.map(function (p) {
  17243. return p.name;
  17244. });
  17245. // allow access of properties by name ( e.g. style.properties.height )
  17246. for (var _i2 = 0; _i2 < props.length; _i2++) {
  17247. var prop = props[_i2];
  17248. props[prop.name] = prop; // allow lookup by name
  17249. }
  17250. // map aliases
  17251. for (var _i3 = 0; _i3 < aliases.length; _i3++) {
  17252. var alias = aliases[_i3];
  17253. var pointsToProp = props[alias.pointsTo];
  17254. var aliasProp = {
  17255. name: alias.name,
  17256. alias: true,
  17257. pointsTo: pointsToProp
  17258. };
  17259. // add alias prop for parsing
  17260. props.push(aliasProp);
  17261. props[alias.name] = aliasProp; // allow lookup by name
  17262. }
  17263. })();
  17264. styfn$2.getDefaultProperty = function (name) {
  17265. return this.getDefaultProperties()[name];
  17266. };
  17267. styfn$2.getDefaultProperties = function () {
  17268. var _p = this._private;
  17269. if (_p.defaultProperties != null) {
  17270. return _p.defaultProperties;
  17271. }
  17272. var rawProps = extend({
  17273. // core props
  17274. 'selection-box-color': '#ddd',
  17275. 'selection-box-opacity': 0.65,
  17276. 'selection-box-border-color': '#aaa',
  17277. 'selection-box-border-width': 1,
  17278. 'active-bg-color': 'black',
  17279. 'active-bg-opacity': 0.15,
  17280. 'active-bg-size': 30,
  17281. 'outside-texture-bg-color': '#000',
  17282. 'outside-texture-bg-opacity': 0.125,
  17283. // common node/edge props
  17284. 'events': 'yes',
  17285. 'text-events': 'no',
  17286. 'text-valign': 'top',
  17287. 'text-halign': 'center',
  17288. 'text-justification': 'auto',
  17289. 'line-height': 1,
  17290. 'color': '#000',
  17291. 'box-selection': 'contain',
  17292. 'text-outline-color': '#000',
  17293. 'text-outline-width': 0,
  17294. 'text-outline-opacity': 1,
  17295. 'text-opacity': 1,
  17296. 'text-decoration': 'none',
  17297. 'text-transform': 'none',
  17298. 'text-wrap': 'none',
  17299. 'text-overflow-wrap': 'whitespace',
  17300. 'text-max-width': 9999,
  17301. 'text-background-color': '#000',
  17302. 'text-background-opacity': 0,
  17303. 'text-background-shape': 'rectangle',
  17304. 'text-background-padding': 0,
  17305. 'text-border-opacity': 0,
  17306. 'text-border-width': 0,
  17307. 'text-border-style': 'solid',
  17308. 'text-border-color': '#000',
  17309. 'font-family': 'Helvetica Neue, Helvetica, sans-serif',
  17310. 'font-style': 'normal',
  17311. 'font-weight': 'normal',
  17312. 'font-size': 16,
  17313. 'min-zoomed-font-size': 0,
  17314. 'text-rotation': 'none',
  17315. 'source-text-rotation': 'none',
  17316. 'target-text-rotation': 'none',
  17317. 'visibility': 'visible',
  17318. 'display': 'element',
  17319. 'opacity': 1,
  17320. 'z-compound-depth': 'auto',
  17321. 'z-index-compare': 'auto',
  17322. 'z-index': 0,
  17323. 'label': '',
  17324. 'text-margin-x': 0,
  17325. 'text-margin-y': 0,
  17326. 'source-label': '',
  17327. 'source-text-offset': 0,
  17328. 'source-text-margin-x': 0,
  17329. 'source-text-margin-y': 0,
  17330. 'target-label': '',
  17331. 'target-text-offset': 0,
  17332. 'target-text-margin-x': 0,
  17333. 'target-text-margin-y': 0,
  17334. 'overlay-opacity': 0,
  17335. 'overlay-color': '#000',
  17336. 'overlay-padding': 10,
  17337. 'overlay-shape': 'round-rectangle',
  17338. 'overlay-corner-radius': 'auto',
  17339. 'underlay-opacity': 0,
  17340. 'underlay-color': '#000',
  17341. 'underlay-padding': 10,
  17342. 'underlay-shape': 'round-rectangle',
  17343. 'underlay-corner-radius': 'auto',
  17344. 'transition-property': 'none',
  17345. 'transition-duration': 0,
  17346. 'transition-delay': 0,
  17347. 'transition-timing-function': 'linear',
  17348. 'box-select-labels': 'no',
  17349. // node props
  17350. 'background-blacken': 0,
  17351. 'background-color': '#999',
  17352. 'background-fill': 'solid',
  17353. 'background-opacity': 1,
  17354. 'background-image': 'none',
  17355. 'background-image-crossorigin': 'anonymous',
  17356. 'background-image-opacity': 1,
  17357. 'background-image-containment': 'inside',
  17358. 'background-image-smoothing': 'yes',
  17359. 'background-position-x': '50%',
  17360. 'background-position-y': '50%',
  17361. 'background-offset-x': 0,
  17362. 'background-offset-y': 0,
  17363. 'background-width-relative-to': 'include-padding',
  17364. 'background-height-relative-to': 'include-padding',
  17365. 'background-repeat': 'no-repeat',
  17366. 'background-fit': 'none',
  17367. 'background-clip': 'node',
  17368. 'background-width': 'auto',
  17369. 'background-height': 'auto',
  17370. 'border-color': '#000',
  17371. 'border-opacity': 1,
  17372. 'border-width': 0,
  17373. 'border-style': 'solid',
  17374. 'border-dash-pattern': [4, 2],
  17375. 'border-dash-offset': 0,
  17376. 'border-cap': 'butt',
  17377. 'border-join': 'miter',
  17378. 'border-position': 'center',
  17379. 'outline-color': '#999',
  17380. 'outline-opacity': 1,
  17381. 'outline-width': 0,
  17382. 'outline-offset': 0,
  17383. 'outline-style': 'solid',
  17384. 'height': 30,
  17385. 'width': 30,
  17386. 'shape': 'ellipse',
  17387. 'shape-polygon-points': '-1, -1, 1, -1, 1, 1, -1, 1',
  17388. 'corner-radius': 'auto',
  17389. 'bounds-expansion': 0,
  17390. // node gradient
  17391. 'background-gradient-direction': 'to-bottom',
  17392. 'background-gradient-stop-colors': '#999',
  17393. 'background-gradient-stop-positions': '0%',
  17394. // ghost props
  17395. 'ghost': 'no',
  17396. 'ghost-offset-y': 0,
  17397. 'ghost-offset-x': 0,
  17398. 'ghost-opacity': 0,
  17399. // compound props
  17400. 'padding': 0,
  17401. 'padding-relative-to': 'width',
  17402. 'position': 'origin',
  17403. 'compound-sizing-wrt-labels': 'include',
  17404. 'min-width': 0,
  17405. 'min-width-bias-left': 0,
  17406. 'min-width-bias-right': 0,
  17407. 'min-height': 0,
  17408. 'min-height-bias-top': 0,
  17409. 'min-height-bias-bottom': 0
  17410. }, {
  17411. // node pie bg
  17412. 'pie-size': '100%',
  17413. 'pie-hole': 0,
  17414. 'pie-start-angle': '0deg'
  17415. }, [{
  17416. name: 'pie-{{i}}-background-color',
  17417. value: 'black'
  17418. }, {
  17419. name: 'pie-{{i}}-background-size',
  17420. value: '0%'
  17421. }, {
  17422. name: 'pie-{{i}}-background-opacity',
  17423. value: 1
  17424. }].reduce(function (css, prop) {
  17425. for (var i = 1; i <= styfn$2.pieBackgroundN; i++) {
  17426. var name = prop.name.replace('{{i}}', i);
  17427. var val = prop.value;
  17428. css[name] = val;
  17429. }
  17430. return css;
  17431. }, {}), {
  17432. // node stripes bg
  17433. 'stripe-size': '100%',
  17434. 'stripe-direction': 'horizontal'
  17435. }, [{
  17436. name: 'stripe-{{i}}-background-color',
  17437. value: 'black'
  17438. }, {
  17439. name: 'stripe-{{i}}-background-size',
  17440. value: '0%'
  17441. }, {
  17442. name: 'stripe-{{i}}-background-opacity',
  17443. value: 1
  17444. }].reduce(function (css, prop) {
  17445. for (var i = 1; i <= styfn$2.stripeBackgroundN; i++) {
  17446. var name = prop.name.replace('{{i}}', i);
  17447. var val = prop.value;
  17448. css[name] = val;
  17449. }
  17450. return css;
  17451. }, {}), {
  17452. // edge props
  17453. 'line-style': 'solid',
  17454. 'line-color': '#999',
  17455. 'line-fill': 'solid',
  17456. 'line-cap': 'butt',
  17457. 'line-opacity': 1,
  17458. 'line-outline-width': 0,
  17459. 'line-outline-color': '#000',
  17460. 'line-gradient-stop-colors': '#999',
  17461. 'line-gradient-stop-positions': '0%',
  17462. 'control-point-step-size': 40,
  17463. 'control-point-weights': 0.5,
  17464. 'segment-weights': 0.5,
  17465. 'segment-distances': 20,
  17466. 'segment-radii': 15,
  17467. 'radius-type': 'arc-radius',
  17468. 'taxi-turn': '50%',
  17469. 'taxi-radius': 15,
  17470. 'taxi-turn-min-distance': 10,
  17471. 'taxi-direction': 'auto',
  17472. 'edge-distances': 'intersection',
  17473. 'curve-style': 'haystack',
  17474. 'haystack-radius': 0,
  17475. 'arrow-scale': 1,
  17476. 'loop-direction': '-45deg',
  17477. 'loop-sweep': '-90deg',
  17478. 'source-distance-from-node': 0,
  17479. 'target-distance-from-node': 0,
  17480. 'source-endpoint': 'outside-to-node',
  17481. 'target-endpoint': 'outside-to-node',
  17482. 'line-dash-pattern': [6, 3],
  17483. 'line-dash-offset': 0
  17484. }, [{
  17485. name: 'arrow-shape',
  17486. value: 'none'
  17487. }, {
  17488. name: 'arrow-color',
  17489. value: '#999'
  17490. }, {
  17491. name: 'arrow-fill',
  17492. value: 'filled'
  17493. }, {
  17494. name: 'arrow-width',
  17495. value: 1
  17496. }].reduce(function (css, prop) {
  17497. styfn$2.arrowPrefixes.forEach(function (prefix) {
  17498. var name = prefix + '-' + prop.name;
  17499. var val = prop.value;
  17500. css[name] = val;
  17501. });
  17502. return css;
  17503. }, {}));
  17504. var parsedProps = {};
  17505. for (var i = 0; i < this.properties.length; i++) {
  17506. var prop = this.properties[i];
  17507. if (prop.pointsTo) {
  17508. continue;
  17509. }
  17510. var name = prop.name;
  17511. var val = rawProps[name];
  17512. var parsedProp = this.parse(name, val);
  17513. parsedProps[name] = parsedProp;
  17514. }
  17515. _p.defaultProperties = parsedProps;
  17516. return _p.defaultProperties;
  17517. };
  17518. styfn$2.addDefaultStylesheet = function () {
  17519. this.selector(':parent').css({
  17520. 'shape': 'rectangle',
  17521. 'padding': 10,
  17522. 'background-color': '#eee',
  17523. 'border-color': '#ccc',
  17524. 'border-width': 1
  17525. }).selector('edge').css({
  17526. 'width': 3
  17527. }).selector(':loop').css({
  17528. 'curve-style': 'bezier'
  17529. }).selector('edge:compound').css({
  17530. 'curve-style': 'bezier',
  17531. 'source-endpoint': 'outside-to-line',
  17532. 'target-endpoint': 'outside-to-line'
  17533. }).selector(':selected').css({
  17534. 'background-color': '#0169D9',
  17535. 'line-color': '#0169D9',
  17536. 'source-arrow-color': '#0169D9',
  17537. 'target-arrow-color': '#0169D9',
  17538. 'mid-source-arrow-color': '#0169D9',
  17539. 'mid-target-arrow-color': '#0169D9'
  17540. }).selector(':parent:selected').css({
  17541. 'background-color': '#CCE1F9',
  17542. 'border-color': '#aec8e5'
  17543. }).selector(':active').css({
  17544. 'overlay-color': 'black',
  17545. 'overlay-padding': 10,
  17546. 'overlay-opacity': 0.25
  17547. });
  17548. this.defaultLength = this.length;
  17549. };
  17550. var styfn$1 = {};
  17551. // a caching layer for property parsing
  17552. styfn$1.parse = function (name, value, propIsBypass, propIsFlat) {
  17553. var self = this;
  17554. // function values can't be cached in all cases, and there isn't much benefit of caching them anyway
  17555. if (fn$6(value)) {
  17556. return self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  17557. }
  17558. var flatKey = propIsFlat === 'mapping' || propIsFlat === true || propIsFlat === false || propIsFlat == null ? 'dontcare' : propIsFlat;
  17559. var bypassKey = propIsBypass ? 't' : 'f';
  17560. var valueKey = '' + value;
  17561. var argHash = hashStrings(name, valueKey, bypassKey, flatKey);
  17562. var propCache = self.propCache = self.propCache || [];
  17563. var ret;
  17564. if (!(ret = propCache[argHash])) {
  17565. ret = propCache[argHash] = self.parseImplWarn(name, value, propIsBypass, propIsFlat);
  17566. }
  17567. // - bypasses can't be shared b/c the value can be changed by animations or otherwise overridden
  17568. // - mappings can't be shared b/c mappings are per-element
  17569. if (propIsBypass || propIsFlat === 'mapping') {
  17570. // need a copy since props are mutated later in their lifecycles
  17571. ret = copy(ret);
  17572. if (ret) {
  17573. ret.value = copy(ret.value); // because it could be an array, e.g. colour
  17574. }
  17575. }
  17576. return ret;
  17577. };
  17578. styfn$1.parseImplWarn = function (name, value, propIsBypass, propIsFlat) {
  17579. var prop = this.parseImpl(name, value, propIsBypass, propIsFlat);
  17580. if (!prop && value != null) {
  17581. warn("The style property `".concat(name, ": ").concat(value, "` is invalid"));
  17582. }
  17583. if (prop && (prop.name === 'width' || prop.name === 'height') && value === 'label') {
  17584. warn('The style value of `label` is deprecated for `' + prop.name + '`');
  17585. }
  17586. return prop;
  17587. };
  17588. // parse a property; return null on invalid; return parsed property otherwise
  17589. // fields :
  17590. // - name : the name of the property
  17591. // - value : the parsed, native-typed value of the property
  17592. // - strValue : a string value that represents the property value in valid css
  17593. // - bypass : true iff the property is a bypass property
  17594. styfn$1.parseImpl = function (name, value, propIsBypass, propIsFlat) {
  17595. var self = this;
  17596. name = camel2dash(name); // make sure the property name is in dash form (e.g. 'property-name' not 'propertyName')
  17597. var property = self.properties[name];
  17598. var passedValue = value;
  17599. var types = self.types;
  17600. if (!property) {
  17601. return null;
  17602. } // return null on property of unknown name
  17603. if (value === undefined) {
  17604. return null;
  17605. } // can't assign undefined
  17606. // the property may be an alias
  17607. if (property.alias) {
  17608. property = property.pointsTo;
  17609. name = property.name;
  17610. }
  17611. var valueIsString = string(value);
  17612. if (valueIsString) {
  17613. // trim the value to make parsing easier
  17614. value = value.trim();
  17615. }
  17616. var type = property.type;
  17617. if (!type) {
  17618. return null;
  17619. } // no type, no luck
  17620. // check if bypass is null or empty string (i.e. indication to delete bypass property)
  17621. if (propIsBypass && (value === '' || value === null)) {
  17622. return {
  17623. name: name,
  17624. value: value,
  17625. bypass: true,
  17626. deleteBypass: true
  17627. };
  17628. }
  17629. // check if value is a function used as a mapper
  17630. if (fn$6(value)) {
  17631. return {
  17632. name: name,
  17633. value: value,
  17634. strValue: 'fn',
  17635. mapped: types.fn,
  17636. bypass: propIsBypass
  17637. };
  17638. }
  17639. // check if value is mapped
  17640. var data, mapData;
  17641. 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))) {
  17642. if (propIsBypass) {
  17643. return false;
  17644. } // mappers not allowed in bypass
  17645. var mapped = types.data;
  17646. return {
  17647. name: name,
  17648. value: data,
  17649. strValue: '' + value,
  17650. mapped: mapped,
  17651. field: data[1],
  17652. bypass: propIsBypass
  17653. };
  17654. } else if (value.length >= 10 && value[0] === 'm' && (mapData = new RegExp(types.mapData.regex).exec(value))) {
  17655. if (propIsBypass) {
  17656. return false;
  17657. } // mappers not allowed in bypass
  17658. if (type.multiple) {
  17659. return false;
  17660. } // impossible to map to num
  17661. var _mapped = types.mapData;
  17662. // we can map only if the type is a colour or a number
  17663. if (!(type.color || type.number)) {
  17664. return false;
  17665. }
  17666. var valueMin = this.parse(name, mapData[4]); // parse to validate
  17667. if (!valueMin || valueMin.mapped) {
  17668. return false;
  17669. } // can't be invalid or mapped
  17670. var valueMax = this.parse(name, mapData[5]); // parse to validate
  17671. if (!valueMax || valueMax.mapped) {
  17672. return false;
  17673. } // can't be invalid or mapped
  17674. // check if valueMin and valueMax are the same
  17675. if (valueMin.pfValue === valueMax.pfValue || valueMin.strValue === valueMax.strValue) {
  17676. warn('`' + name + ': ' + value + '` is not a valid mapper because the output range is zero; converting to `' + name + ': ' + valueMin.strValue + '`');
  17677. return this.parse(name, valueMin.strValue); // can't make much of a mapper without a range
  17678. } else if (type.color) {
  17679. var c1 = valueMin.value;
  17680. var c2 = valueMax.value;
  17681. var same = c1[0] === c2[0] // red
  17682. && c1[1] === c2[1] // green
  17683. && c1[2] === c2[2] // blue
  17684. && (
  17685. // optional alpha
  17686. c1[3] === c2[3] // same alpha outright
  17687. || (c1[3] == null || c1[3] === 1 // full opacity for colour 1?
  17688. ) && (c2[3] == null || c2[3] === 1) // full opacity for colour 2?
  17689. );
  17690. if (same) {
  17691. return false;
  17692. } // can't make a mapper without a range
  17693. }
  17694. return {
  17695. name: name,
  17696. value: mapData,
  17697. strValue: '' + value,
  17698. mapped: _mapped,
  17699. field: mapData[1],
  17700. fieldMin: parseFloat(mapData[2]),
  17701. // min & max are numeric
  17702. fieldMax: parseFloat(mapData[3]),
  17703. valueMin: valueMin.value,
  17704. valueMax: valueMax.value,
  17705. bypass: propIsBypass
  17706. };
  17707. }
  17708. if (type.multiple && propIsFlat !== 'multiple') {
  17709. var vals;
  17710. if (valueIsString) {
  17711. vals = value.split(/\s+/);
  17712. } else if (array(value)) {
  17713. vals = value;
  17714. } else {
  17715. vals = [value];
  17716. }
  17717. if (type.evenMultiple && vals.length % 2 !== 0) {
  17718. return null;
  17719. }
  17720. var valArr = [];
  17721. var unitsArr = [];
  17722. var pfValArr = [];
  17723. var strVal = '';
  17724. var hasEnum = false;
  17725. for (var i = 0; i < vals.length; i++) {
  17726. var p = self.parse(name, vals[i], propIsBypass, 'multiple');
  17727. hasEnum = hasEnum || string(p.value);
  17728. valArr.push(p.value);
  17729. pfValArr.push(p.pfValue != null ? p.pfValue : p.value);
  17730. unitsArr.push(p.units);
  17731. strVal += (i > 0 ? ' ' : '') + p.strValue;
  17732. }
  17733. if (type.validate && !type.validate(valArr, unitsArr)) {
  17734. return null;
  17735. }
  17736. if (type.singleEnum && hasEnum) {
  17737. if (valArr.length === 1 && string(valArr[0])) {
  17738. return {
  17739. name: name,
  17740. value: valArr[0],
  17741. strValue: valArr[0],
  17742. bypass: propIsBypass
  17743. };
  17744. } else {
  17745. return null;
  17746. }
  17747. }
  17748. return {
  17749. name: name,
  17750. value: valArr,
  17751. pfValue: pfValArr,
  17752. strValue: strVal,
  17753. bypass: propIsBypass,
  17754. units: unitsArr
  17755. };
  17756. }
  17757. // several types also allow enums
  17758. var checkEnums = function checkEnums() {
  17759. for (var _i = 0; _i < type.enums.length; _i++) {
  17760. var en = type.enums[_i];
  17761. if (en === value) {
  17762. return {
  17763. name: name,
  17764. value: value,
  17765. strValue: '' + value,
  17766. bypass: propIsBypass
  17767. };
  17768. }
  17769. }
  17770. return null;
  17771. };
  17772. // check the type and return the appropriate object
  17773. if (type.number) {
  17774. var units;
  17775. var implicitUnits = 'px'; // not set => px
  17776. if (type.units) {
  17777. // use specified units if set
  17778. units = type.units;
  17779. }
  17780. if (type.implicitUnits) {
  17781. implicitUnits = type.implicitUnits;
  17782. }
  17783. if (!type.unitless) {
  17784. if (valueIsString) {
  17785. var unitsRegex = 'px|em' + (type.allowPercent ? '|\\%' : '');
  17786. if (units) {
  17787. unitsRegex = units;
  17788. } // only allow explicit units if so set
  17789. var match = value.match('^(' + number + ')(' + unitsRegex + ')?' + '$');
  17790. if (match) {
  17791. value = match[1];
  17792. units = match[2] || implicitUnits;
  17793. }
  17794. } else if (!units || type.implicitUnits) {
  17795. units = implicitUnits; // implicitly px if unspecified
  17796. }
  17797. }
  17798. value = parseFloat(value);
  17799. // if not a number and enums not allowed, then the value is invalid
  17800. if (isNaN(value) && type.enums === undefined) {
  17801. return null;
  17802. }
  17803. // check if this number type also accepts special keywords in place of numbers
  17804. // (i.e. `left`, `auto`, etc)
  17805. if (isNaN(value) && type.enums !== undefined) {
  17806. value = passedValue;
  17807. return checkEnums();
  17808. }
  17809. // check if value must be an integer
  17810. if (type.integer && !integer(value)) {
  17811. return null;
  17812. }
  17813. // check value is within range
  17814. if (type.min !== undefined && (value < type.min || type.strictMin && value === type.min) || type.max !== undefined && (value > type.max || type.strictMax && value === type.max)) {
  17815. return null;
  17816. }
  17817. var ret = {
  17818. name: name,
  17819. value: value,
  17820. strValue: '' + value + (units ? units : ''),
  17821. units: units,
  17822. bypass: propIsBypass
  17823. };
  17824. // normalise value in pixels
  17825. if (type.unitless || units !== 'px' && units !== 'em') {
  17826. ret.pfValue = value;
  17827. } else {
  17828. ret.pfValue = units === 'px' || !units ? value : this.getEmSizeInPixels() * value;
  17829. }
  17830. // normalise value in ms
  17831. if (units === 'ms' || units === 's') {
  17832. ret.pfValue = units === 'ms' ? value : 1000 * value;
  17833. }
  17834. // normalise value in rad
  17835. if (units === 'deg' || units === 'rad') {
  17836. ret.pfValue = units === 'rad' ? value : deg2rad(value);
  17837. }
  17838. // normalize value in %
  17839. if (units === '%') {
  17840. ret.pfValue = value / 100;
  17841. }
  17842. return ret;
  17843. } else if (type.propList) {
  17844. var props = [];
  17845. var propsStr = '' + value;
  17846. if (propsStr === 'none') ; else {
  17847. // go over each prop
  17848. var propsSplit = propsStr.split(/\s*,\s*|\s+/);
  17849. for (var _i2 = 0; _i2 < propsSplit.length; _i2++) {
  17850. var propName = propsSplit[_i2].trim();
  17851. if (self.properties[propName]) {
  17852. props.push(propName);
  17853. } else {
  17854. warn('`' + propName + '` is not a valid property name');
  17855. }
  17856. }
  17857. if (props.length === 0) {
  17858. return null;
  17859. }
  17860. }
  17861. return {
  17862. name: name,
  17863. value: props,
  17864. strValue: props.length === 0 ? 'none' : props.join(' '),
  17865. bypass: propIsBypass
  17866. };
  17867. } else if (type.color) {
  17868. var tuple = color2tuple(value);
  17869. if (!tuple) {
  17870. return null;
  17871. }
  17872. return {
  17873. name: name,
  17874. value: tuple,
  17875. pfValue: tuple,
  17876. strValue: 'rgb(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')',
  17877. // n.b. no spaces b/c of multiple support
  17878. bypass: propIsBypass
  17879. };
  17880. } else if (type.regex || type.regexes) {
  17881. // first check enums
  17882. if (type.enums) {
  17883. var enumProp = checkEnums();
  17884. if (enumProp) {
  17885. return enumProp;
  17886. }
  17887. }
  17888. var regexes = type.regexes ? type.regexes : [type.regex];
  17889. for (var _i3 = 0; _i3 < regexes.length; _i3++) {
  17890. var regex = new RegExp(regexes[_i3]); // make a regex from the type string
  17891. var m = regex.exec(value);
  17892. if (m) {
  17893. // regex matches
  17894. return {
  17895. name: name,
  17896. value: type.singleRegexMatchValue ? m[1] : m,
  17897. strValue: '' + value,
  17898. bypass: propIsBypass
  17899. };
  17900. }
  17901. }
  17902. return null; // didn't match any
  17903. } else if (type.string) {
  17904. // just return
  17905. return {
  17906. name: name,
  17907. value: '' + value,
  17908. strValue: '' + value,
  17909. bypass: propIsBypass
  17910. };
  17911. } else if (type.enums) {
  17912. // check enums last because it's a combo type in others
  17913. return checkEnums();
  17914. } else {
  17915. return null; // not a type we can handle
  17916. }
  17917. };
  17918. var _Style = function Style(cy) {
  17919. if (!(this instanceof _Style)) {
  17920. return new _Style(cy);
  17921. }
  17922. if (!core(cy)) {
  17923. error('A style must have a core reference');
  17924. return;
  17925. }
  17926. this._private = {
  17927. cy: cy,
  17928. coreStyle: {}
  17929. };
  17930. this.length = 0;
  17931. this.resetToDefault();
  17932. };
  17933. var styfn = _Style.prototype;
  17934. styfn.instanceString = function () {
  17935. return 'style';
  17936. };
  17937. // remove all contexts
  17938. styfn.clear = function () {
  17939. var _p = this._private;
  17940. var cy = _p.cy;
  17941. var eles = cy.elements();
  17942. for (var i = 0; i < this.length; i++) {
  17943. this[i] = undefined;
  17944. }
  17945. this.length = 0;
  17946. _p.contextStyles = {};
  17947. _p.propDiffs = {};
  17948. this.cleanElements(eles, true);
  17949. eles.forEach(function (ele) {
  17950. var ele_p = ele[0]._private;
  17951. ele_p.styleDirty = true;
  17952. ele_p.appliedInitStyle = false;
  17953. });
  17954. return this; // chaining
  17955. };
  17956. styfn.resetToDefault = function () {
  17957. this.clear();
  17958. this.addDefaultStylesheet();
  17959. return this;
  17960. };
  17961. // builds a style object for the 'core' selector
  17962. styfn.core = function (propName) {
  17963. return this._private.coreStyle[propName] || this.getDefaultProperty(propName);
  17964. };
  17965. // create a new context from the specified selector string and switch to that context
  17966. styfn.selector = function (selectorStr) {
  17967. // 'core' is a special case and does not need a selector
  17968. var selector = selectorStr === 'core' ? null : new Selector(selectorStr);
  17969. var i = this.length++; // new context means new index
  17970. this[i] = {
  17971. selector: selector,
  17972. properties: [],
  17973. mappedProperties: [],
  17974. index: i
  17975. };
  17976. return this; // chaining
  17977. };
  17978. // add one or many css rules to the current context
  17979. styfn.css = function () {
  17980. var self = this;
  17981. var args = arguments;
  17982. if (args.length === 1) {
  17983. var map = args[0];
  17984. for (var i = 0; i < self.properties.length; i++) {
  17985. var prop = self.properties[i];
  17986. var mapVal = map[prop.name];
  17987. if (mapVal === undefined) {
  17988. mapVal = map[dash2camel(prop.name)];
  17989. }
  17990. if (mapVal !== undefined) {
  17991. this.cssRule(prop.name, mapVal);
  17992. }
  17993. }
  17994. } else if (args.length === 2) {
  17995. this.cssRule(args[0], args[1]);
  17996. }
  17997. // do nothing if args are invalid
  17998. return this; // chaining
  17999. };
  18000. styfn.style = styfn.css;
  18001. // add a single css rule to the current context
  18002. styfn.cssRule = function (name, value) {
  18003. // name-value pair
  18004. var property = this.parse(name, value);
  18005. // add property to current context if valid
  18006. if (property) {
  18007. var i = this.length - 1;
  18008. this[i].properties.push(property);
  18009. this[i].properties[property.name] = property; // allow access by name as well
  18010. if (property.name.match(/pie-(\d+)-background-size/) && property.value) {
  18011. this._private.hasPie = true;
  18012. }
  18013. if (property.name.match(/stripe-(\d+)-background-size/) && property.value) {
  18014. this._private.hasStripe = true;
  18015. }
  18016. if (property.mapped) {
  18017. this[i].mappedProperties.push(property);
  18018. }
  18019. // add to core style if necessary
  18020. var currentSelectorIsCore = !this[i].selector;
  18021. if (currentSelectorIsCore) {
  18022. this._private.coreStyle[property.name] = property;
  18023. }
  18024. }
  18025. return this; // chaining
  18026. };
  18027. styfn.append = function (style) {
  18028. if (stylesheet(style)) {
  18029. style.appendToStyle(this);
  18030. } else if (array(style)) {
  18031. this.appendFromJson(style);
  18032. } else if (string(style)) {
  18033. this.appendFromString(style);
  18034. } // you probably wouldn't want to append a Style, since you'd duplicate the default parts
  18035. return this;
  18036. };
  18037. // static function
  18038. _Style.fromJson = function (cy, json) {
  18039. var style = new _Style(cy);
  18040. style.fromJson(json);
  18041. return style;
  18042. };
  18043. _Style.fromString = function (cy, string) {
  18044. return new _Style(cy).fromString(string);
  18045. };
  18046. [styfn$8, styfn$7, styfn$6, styfn$5, styfn$4, styfn$3, styfn$2, styfn$1].forEach(function (props) {
  18047. extend(styfn, props);
  18048. });
  18049. _Style.types = styfn.types;
  18050. _Style.properties = styfn.properties;
  18051. _Style.propertyGroups = styfn.propertyGroups;
  18052. _Style.propertyGroupNames = styfn.propertyGroupNames;
  18053. _Style.propertyGroupKeys = styfn.propertyGroupKeys;
  18054. var corefn$2 = {
  18055. style: function style(newStyle) {
  18056. if (newStyle) {
  18057. var s = this.setStyle(newStyle);
  18058. s.update();
  18059. }
  18060. return this._private.style;
  18061. },
  18062. setStyle: function setStyle(style) {
  18063. var _p = this._private;
  18064. if (stylesheet(style)) {
  18065. _p.style = style.generateStyle(this);
  18066. } else if (array(style)) {
  18067. _p.style = _Style.fromJson(this, style);
  18068. } else if (string(style)) {
  18069. _p.style = _Style.fromString(this, style);
  18070. } else {
  18071. _p.style = _Style(this);
  18072. }
  18073. return _p.style;
  18074. },
  18075. // e.g. cy.data() changed => recalc ele mappers
  18076. updateStyle: function updateStyle() {
  18077. this.mutableElements().updateStyle(); // just send to all eles
  18078. }
  18079. };
  18080. var defaultSelectionType = 'single';
  18081. var corefn$1 = {
  18082. autolock: function autolock(bool) {
  18083. if (bool !== undefined) {
  18084. this._private.autolock = bool ? true : false;
  18085. } else {
  18086. return this._private.autolock;
  18087. }
  18088. return this; // chaining
  18089. },
  18090. autoungrabify: function autoungrabify(bool) {
  18091. if (bool !== undefined) {
  18092. this._private.autoungrabify = bool ? true : false;
  18093. } else {
  18094. return this._private.autoungrabify;
  18095. }
  18096. return this; // chaining
  18097. },
  18098. autounselectify: function autounselectify(bool) {
  18099. if (bool !== undefined) {
  18100. this._private.autounselectify = bool ? true : false;
  18101. } else {
  18102. return this._private.autounselectify;
  18103. }
  18104. return this; // chaining
  18105. },
  18106. selectionType: function selectionType(selType) {
  18107. var _p = this._private;
  18108. if (_p.selectionType == null) {
  18109. _p.selectionType = defaultSelectionType;
  18110. }
  18111. if (selType !== undefined) {
  18112. if (selType === 'additive' || selType === 'single') {
  18113. _p.selectionType = selType;
  18114. }
  18115. } else {
  18116. return _p.selectionType;
  18117. }
  18118. return this;
  18119. },
  18120. panningEnabled: function panningEnabled(bool) {
  18121. if (bool !== undefined) {
  18122. this._private.panningEnabled = bool ? true : false;
  18123. } else {
  18124. return this._private.panningEnabled;
  18125. }
  18126. return this; // chaining
  18127. },
  18128. userPanningEnabled: function userPanningEnabled(bool) {
  18129. if (bool !== undefined) {
  18130. this._private.userPanningEnabled = bool ? true : false;
  18131. } else {
  18132. return this._private.userPanningEnabled;
  18133. }
  18134. return this; // chaining
  18135. },
  18136. zoomingEnabled: function zoomingEnabled(bool) {
  18137. if (bool !== undefined) {
  18138. this._private.zoomingEnabled = bool ? true : false;
  18139. } else {
  18140. return this._private.zoomingEnabled;
  18141. }
  18142. return this; // chaining
  18143. },
  18144. userZoomingEnabled: function userZoomingEnabled(bool) {
  18145. if (bool !== undefined) {
  18146. this._private.userZoomingEnabled = bool ? true : false;
  18147. } else {
  18148. return this._private.userZoomingEnabled;
  18149. }
  18150. return this; // chaining
  18151. },
  18152. boxSelectionEnabled: function boxSelectionEnabled(bool) {
  18153. if (bool !== undefined) {
  18154. this._private.boxSelectionEnabled = bool ? true : false;
  18155. } else {
  18156. return this._private.boxSelectionEnabled;
  18157. }
  18158. return this; // chaining
  18159. },
  18160. pan: function pan() {
  18161. var args = arguments;
  18162. var pan = this._private.pan;
  18163. var dim, val, dims, x, y;
  18164. switch (args.length) {
  18165. case 0:
  18166. // .pan()
  18167. return pan;
  18168. case 1:
  18169. if (string(args[0])) {
  18170. // .pan('x')
  18171. dim = args[0];
  18172. return pan[dim];
  18173. } else if (plainObject(args[0])) {
  18174. // .pan({ x: 0, y: 100 })
  18175. if (!this._private.panningEnabled) {
  18176. return this;
  18177. }
  18178. dims = args[0];
  18179. x = dims.x;
  18180. y = dims.y;
  18181. if (number$1(x)) {
  18182. pan.x = x;
  18183. }
  18184. if (number$1(y)) {
  18185. pan.y = y;
  18186. }
  18187. this.emit('pan viewport');
  18188. }
  18189. break;
  18190. case 2:
  18191. // .pan('x', 100)
  18192. if (!this._private.panningEnabled) {
  18193. return this;
  18194. }
  18195. dim = args[0];
  18196. val = args[1];
  18197. if ((dim === 'x' || dim === 'y') && number$1(val)) {
  18198. pan[dim] = val;
  18199. }
  18200. this.emit('pan viewport');
  18201. break;
  18202. // invalid
  18203. }
  18204. this.notify('viewport');
  18205. return this; // chaining
  18206. },
  18207. panBy: function panBy(arg0, arg1) {
  18208. var args = arguments;
  18209. var pan = this._private.pan;
  18210. var dim, val, dims, x, y;
  18211. if (!this._private.panningEnabled) {
  18212. return this;
  18213. }
  18214. switch (args.length) {
  18215. case 1:
  18216. if (plainObject(arg0)) {
  18217. // .panBy({ x: 0, y: 100 })
  18218. dims = args[0];
  18219. x = dims.x;
  18220. y = dims.y;
  18221. if (number$1(x)) {
  18222. pan.x += x;
  18223. }
  18224. if (number$1(y)) {
  18225. pan.y += y;
  18226. }
  18227. this.emit('pan viewport');
  18228. }
  18229. break;
  18230. case 2:
  18231. // .panBy('x', 100)
  18232. dim = arg0;
  18233. val = arg1;
  18234. if ((dim === 'x' || dim === 'y') && number$1(val)) {
  18235. pan[dim] += val;
  18236. }
  18237. this.emit('pan viewport');
  18238. break;
  18239. // invalid
  18240. }
  18241. this.notify('viewport');
  18242. return this; // chaining
  18243. },
  18244. gc: function gc() {
  18245. this.notify('gc');
  18246. },
  18247. fit: function fit(elements, padding) {
  18248. var viewportState = this.getFitViewport(elements, padding);
  18249. if (viewportState) {
  18250. var _p = this._private;
  18251. _p.zoom = viewportState.zoom;
  18252. _p.pan = viewportState.pan;
  18253. this.emit('pan zoom viewport');
  18254. this.notify('viewport');
  18255. }
  18256. return this; // chaining
  18257. },
  18258. getFitViewport: function getFitViewport(elements, padding) {
  18259. if (number$1(elements) && padding === undefined) {
  18260. // elements is optional
  18261. padding = elements;
  18262. elements = undefined;
  18263. }
  18264. if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
  18265. return;
  18266. }
  18267. var bb;
  18268. if (string(elements)) {
  18269. var sel = elements;
  18270. elements = this.$(sel);
  18271. } else if (boundingBox(elements)) {
  18272. // assume bb
  18273. var bbe = elements;
  18274. bb = {
  18275. x1: bbe.x1,
  18276. y1: bbe.y1,
  18277. x2: bbe.x2,
  18278. y2: bbe.y2
  18279. };
  18280. bb.w = bb.x2 - bb.x1;
  18281. bb.h = bb.y2 - bb.y1;
  18282. } else if (!elementOrCollection(elements)) {
  18283. elements = this.mutableElements();
  18284. }
  18285. if (elementOrCollection(elements) && elements.empty()) {
  18286. return;
  18287. } // can't fit to nothing
  18288. bb = bb || elements.boundingBox();
  18289. var w = this.width();
  18290. var h = this.height();
  18291. var zoom;
  18292. padding = number$1(padding) ? padding : 0;
  18293. if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0 && !isNaN(bb.w) && !isNaN(bb.h) && bb.w > 0 && bb.h > 0) {
  18294. zoom = Math.min((w - 2 * padding) / bb.w, (h - 2 * padding) / bb.h);
  18295. // crop zoom
  18296. zoom = zoom > this._private.maxZoom ? this._private.maxZoom : zoom;
  18297. zoom = zoom < this._private.minZoom ? this._private.minZoom : zoom;
  18298. var pan = {
  18299. // now pan to middle
  18300. x: (w - zoom * (bb.x1 + bb.x2)) / 2,
  18301. y: (h - zoom * (bb.y1 + bb.y2)) / 2
  18302. };
  18303. return {
  18304. zoom: zoom,
  18305. pan: pan
  18306. };
  18307. }
  18308. return;
  18309. },
  18310. zoomRange: function zoomRange(min, max) {
  18311. var _p = this._private;
  18312. if (max == null) {
  18313. var opts = min;
  18314. min = opts.min;
  18315. max = opts.max;
  18316. }
  18317. if (number$1(min) && number$1(max) && min <= max) {
  18318. _p.minZoom = min;
  18319. _p.maxZoom = max;
  18320. } else if (number$1(min) && max === undefined && min <= _p.maxZoom) {
  18321. _p.minZoom = min;
  18322. } else if (number$1(max) && min === undefined && max >= _p.minZoom) {
  18323. _p.maxZoom = max;
  18324. }
  18325. return this;
  18326. },
  18327. minZoom: function minZoom(zoom) {
  18328. if (zoom === undefined) {
  18329. return this._private.minZoom;
  18330. } else {
  18331. return this.zoomRange({
  18332. min: zoom
  18333. });
  18334. }
  18335. },
  18336. maxZoom: function maxZoom(zoom) {
  18337. if (zoom === undefined) {
  18338. return this._private.maxZoom;
  18339. } else {
  18340. return this.zoomRange({
  18341. max: zoom
  18342. });
  18343. }
  18344. },
  18345. getZoomedViewport: function getZoomedViewport(params) {
  18346. var _p = this._private;
  18347. var currentPan = _p.pan;
  18348. var currentZoom = _p.zoom;
  18349. var pos; // in rendered px
  18350. var zoom;
  18351. var bail = false;
  18352. if (!_p.zoomingEnabled) {
  18353. // zooming disabled
  18354. bail = true;
  18355. }
  18356. if (number$1(params)) {
  18357. // then set the zoom
  18358. zoom = params;
  18359. } else if (plainObject(params)) {
  18360. // then zoom about a point
  18361. zoom = params.level;
  18362. if (params.position != null) {
  18363. pos = modelToRenderedPosition$1(params.position, currentZoom, currentPan);
  18364. } else if (params.renderedPosition != null) {
  18365. pos = params.renderedPosition;
  18366. }
  18367. if (pos != null && !_p.panningEnabled) {
  18368. // panning disabled
  18369. bail = true;
  18370. }
  18371. }
  18372. // crop zoom
  18373. zoom = zoom > _p.maxZoom ? _p.maxZoom : zoom;
  18374. zoom = zoom < _p.minZoom ? _p.minZoom : zoom;
  18375. // can't zoom with invalid params
  18376. if (bail || !number$1(zoom) || zoom === currentZoom || pos != null && (!number$1(pos.x) || !number$1(pos.y))) {
  18377. return null;
  18378. }
  18379. if (pos != null) {
  18380. // set zoom about position
  18381. var pan1 = currentPan;
  18382. var zoom1 = currentZoom;
  18383. var zoom2 = zoom;
  18384. var pan2 = {
  18385. x: -zoom2 / zoom1 * (pos.x - pan1.x) + pos.x,
  18386. y: -zoom2 / zoom1 * (pos.y - pan1.y) + pos.y
  18387. };
  18388. return {
  18389. zoomed: true,
  18390. panned: true,
  18391. zoom: zoom2,
  18392. pan: pan2
  18393. };
  18394. } else {
  18395. // just set the zoom
  18396. return {
  18397. zoomed: true,
  18398. panned: false,
  18399. zoom: zoom,
  18400. pan: currentPan
  18401. };
  18402. }
  18403. },
  18404. zoom: function zoom(params) {
  18405. if (params === undefined) {
  18406. // get
  18407. return this._private.zoom;
  18408. } else {
  18409. // set
  18410. var vp = this.getZoomedViewport(params);
  18411. var _p = this._private;
  18412. if (vp == null || !vp.zoomed) {
  18413. return this;
  18414. }
  18415. _p.zoom = vp.zoom;
  18416. if (vp.panned) {
  18417. _p.pan.x = vp.pan.x;
  18418. _p.pan.y = vp.pan.y;
  18419. }
  18420. this.emit('zoom' + (vp.panned ? ' pan' : '') + ' viewport');
  18421. this.notify('viewport');
  18422. return this; // chaining
  18423. }
  18424. },
  18425. viewport: function viewport(opts) {
  18426. var _p = this._private;
  18427. var zoomDefd = true;
  18428. var panDefd = true;
  18429. var events = []; // to trigger
  18430. var zoomFailed = false;
  18431. var panFailed = false;
  18432. if (!opts) {
  18433. return this;
  18434. }
  18435. if (!number$1(opts.zoom)) {
  18436. zoomDefd = false;
  18437. }
  18438. if (!plainObject(opts.pan)) {
  18439. panDefd = false;
  18440. }
  18441. if (!zoomDefd && !panDefd) {
  18442. return this;
  18443. }
  18444. if (zoomDefd) {
  18445. var z = opts.zoom;
  18446. if (z < _p.minZoom || z > _p.maxZoom || !_p.zoomingEnabled) {
  18447. zoomFailed = true;
  18448. } else {
  18449. _p.zoom = z;
  18450. events.push('zoom');
  18451. }
  18452. }
  18453. if (panDefd && (!zoomFailed || !opts.cancelOnFailedZoom) && _p.panningEnabled) {
  18454. var p = opts.pan;
  18455. if (number$1(p.x)) {
  18456. _p.pan.x = p.x;
  18457. panFailed = false;
  18458. }
  18459. if (number$1(p.y)) {
  18460. _p.pan.y = p.y;
  18461. panFailed = false;
  18462. }
  18463. if (!panFailed) {
  18464. events.push('pan');
  18465. }
  18466. }
  18467. if (events.length > 0) {
  18468. events.push('viewport');
  18469. this.emit(events.join(' '));
  18470. this.notify('viewport');
  18471. }
  18472. return this; // chaining
  18473. },
  18474. center: function center(elements) {
  18475. var pan = this.getCenterPan(elements);
  18476. if (pan) {
  18477. this._private.pan = pan;
  18478. this.emit('pan viewport');
  18479. this.notify('viewport');
  18480. }
  18481. return this; // chaining
  18482. },
  18483. getCenterPan: function getCenterPan(elements, zoom) {
  18484. if (!this._private.panningEnabled) {
  18485. return;
  18486. }
  18487. if (string(elements)) {
  18488. var selector = elements;
  18489. elements = this.mutableElements().filter(selector);
  18490. } else if (!elementOrCollection(elements)) {
  18491. elements = this.mutableElements();
  18492. }
  18493. if (elements.length === 0) {
  18494. return;
  18495. } // can't centre pan to nothing
  18496. var bb = elements.boundingBox();
  18497. var w = this.width();
  18498. var h = this.height();
  18499. zoom = zoom === undefined ? this._private.zoom : zoom;
  18500. var pan = {
  18501. // middle
  18502. x: (w - zoom * (bb.x1 + bb.x2)) / 2,
  18503. y: (h - zoom * (bb.y1 + bb.y2)) / 2
  18504. };
  18505. return pan;
  18506. },
  18507. reset: function reset() {
  18508. if (!this._private.panningEnabled || !this._private.zoomingEnabled) {
  18509. return this;
  18510. }
  18511. this.viewport({
  18512. pan: {
  18513. x: 0,
  18514. y: 0
  18515. },
  18516. zoom: 1
  18517. });
  18518. return this; // chaining
  18519. },
  18520. invalidateSize: function invalidateSize() {
  18521. this._private.sizeCache = null;
  18522. },
  18523. size: function size() {
  18524. var _p = this._private;
  18525. var container = _p.container;
  18526. var cy = this;
  18527. return _p.sizeCache = _p.sizeCache || (container ? function () {
  18528. var style = cy.window().getComputedStyle(container);
  18529. var val = function val(name) {
  18530. return parseFloat(style.getPropertyValue(name));
  18531. };
  18532. return {
  18533. width: container.clientWidth - val('padding-left') - val('padding-right'),
  18534. height: container.clientHeight - val('padding-top') - val('padding-bottom')
  18535. };
  18536. }() : {
  18537. // fallback if no container (not 0 b/c can be used for dividing etc)
  18538. width: 1,
  18539. height: 1
  18540. });
  18541. },
  18542. width: function width() {
  18543. return this.size().width;
  18544. },
  18545. height: function height() {
  18546. return this.size().height;
  18547. },
  18548. extent: function extent() {
  18549. var pan = this._private.pan;
  18550. var zoom = this._private.zoom;
  18551. var rb = this.renderedExtent();
  18552. var b = {
  18553. x1: (rb.x1 - pan.x) / zoom,
  18554. x2: (rb.x2 - pan.x) / zoom,
  18555. y1: (rb.y1 - pan.y) / zoom,
  18556. y2: (rb.y2 - pan.y) / zoom
  18557. };
  18558. b.w = b.x2 - b.x1;
  18559. b.h = b.y2 - b.y1;
  18560. return b;
  18561. },
  18562. renderedExtent: function renderedExtent() {
  18563. var width = this.width();
  18564. var height = this.height();
  18565. return {
  18566. x1: 0,
  18567. y1: 0,
  18568. x2: width,
  18569. y2: height,
  18570. w: width,
  18571. h: height
  18572. };
  18573. },
  18574. multiClickDebounceTime: function multiClickDebounceTime(_int) {
  18575. if (_int) this._private.multiClickDebounceTime = _int;else return this._private.multiClickDebounceTime;
  18576. return this; // chaining
  18577. }
  18578. };
  18579. // aliases
  18580. corefn$1.centre = corefn$1.center;
  18581. // backwards compatibility
  18582. corefn$1.autolockNodes = corefn$1.autolock;
  18583. corefn$1.autoungrabifyNodes = corefn$1.autoungrabify;
  18584. var fn = {
  18585. data: define.data({
  18586. field: 'data',
  18587. bindingEvent: 'data',
  18588. allowBinding: true,
  18589. allowSetting: true,
  18590. settingEvent: 'data',
  18591. settingTriggersEvent: true,
  18592. triggerFnName: 'trigger',
  18593. allowGetting: true,
  18594. updateStyle: true
  18595. }),
  18596. removeData: define.removeData({
  18597. field: 'data',
  18598. event: 'data',
  18599. triggerFnName: 'trigger',
  18600. triggerEvent: true,
  18601. updateStyle: true
  18602. }),
  18603. scratch: define.data({
  18604. field: 'scratch',
  18605. bindingEvent: 'scratch',
  18606. allowBinding: true,
  18607. allowSetting: true,
  18608. settingEvent: 'scratch',
  18609. settingTriggersEvent: true,
  18610. triggerFnName: 'trigger',
  18611. allowGetting: true,
  18612. updateStyle: true
  18613. }),
  18614. removeScratch: define.removeData({
  18615. field: 'scratch',
  18616. event: 'scratch',
  18617. triggerFnName: 'trigger',
  18618. triggerEvent: true,
  18619. updateStyle: true
  18620. })
  18621. };
  18622. // aliases
  18623. fn.attr = fn.data;
  18624. fn.removeAttr = fn.removeData;
  18625. var Core = function Core(opts) {
  18626. var cy = this;
  18627. opts = extend({}, opts);
  18628. var container = opts.container;
  18629. // allow for passing a wrapped jquery object
  18630. // e.g. cytoscape({ container: $('#cy') })
  18631. if (container && !htmlElement(container) && htmlElement(container[0])) {
  18632. container = container[0];
  18633. }
  18634. var reg = container ? container._cyreg : null; // e.g. already registered some info (e.g. readies) via jquery
  18635. reg = reg || {};
  18636. if (reg && reg.cy) {
  18637. reg.cy.destroy();
  18638. reg = {}; // old instance => replace reg completely
  18639. }
  18640. var readies = reg.readies = reg.readies || [];
  18641. if (container) {
  18642. container._cyreg = reg;
  18643. } // make sure container assoc'd reg points to this cy
  18644. reg.cy = cy;
  18645. var head = _window !== undefined && container !== undefined && !opts.headless;
  18646. var options = opts;
  18647. options.layout = extend({
  18648. name: head ? 'grid' : 'null'
  18649. }, options.layout);
  18650. options.renderer = extend({
  18651. name: head ? 'canvas' : 'null'
  18652. }, options.renderer);
  18653. var defVal = function defVal(def, val, altVal) {
  18654. if (val !== undefined) {
  18655. return val;
  18656. } else if (altVal !== undefined) {
  18657. return altVal;
  18658. } else {
  18659. return def;
  18660. }
  18661. };
  18662. var _p = this._private = {
  18663. container: container,
  18664. // html dom ele container
  18665. ready: false,
  18666. // whether ready has been triggered
  18667. options: options,
  18668. // cached options
  18669. elements: new Collection(this),
  18670. // elements in the graph
  18671. listeners: [],
  18672. // list of listeners
  18673. aniEles: new Collection(this),
  18674. // elements being animated
  18675. data: options.data || {},
  18676. // data for the core
  18677. scratch: {},
  18678. // scratch object for core
  18679. layout: null,
  18680. renderer: null,
  18681. destroyed: false,
  18682. // whether destroy was called
  18683. notificationsEnabled: true,
  18684. // whether notifications are sent to the renderer
  18685. minZoom: 1e-50,
  18686. maxZoom: 1e50,
  18687. zoomingEnabled: defVal(true, options.zoomingEnabled),
  18688. userZoomingEnabled: defVal(true, options.userZoomingEnabled),
  18689. panningEnabled: defVal(true, options.panningEnabled),
  18690. userPanningEnabled: defVal(true, options.userPanningEnabled),
  18691. boxSelectionEnabled: defVal(true, options.boxSelectionEnabled),
  18692. autolock: defVal(false, options.autolock, options.autolockNodes),
  18693. autoungrabify: defVal(false, options.autoungrabify, options.autoungrabifyNodes),
  18694. autounselectify: defVal(false, options.autounselectify),
  18695. styleEnabled: options.styleEnabled === undefined ? head : options.styleEnabled,
  18696. zoom: number$1(options.zoom) ? options.zoom : 1,
  18697. pan: {
  18698. x: plainObject(options.pan) && number$1(options.pan.x) ? options.pan.x : 0,
  18699. y: plainObject(options.pan) && number$1(options.pan.y) ? options.pan.y : 0
  18700. },
  18701. animation: {
  18702. // object for currently-running animations
  18703. current: [],
  18704. queue: []
  18705. },
  18706. hasCompoundNodes: false,
  18707. multiClickDebounceTime: defVal(250, options.multiClickDebounceTime)
  18708. };
  18709. this.createEmitter();
  18710. // set selection type
  18711. this.selectionType(options.selectionType);
  18712. // init zoom bounds
  18713. this.zoomRange({
  18714. min: options.minZoom,
  18715. max: options.maxZoom
  18716. });
  18717. var loadExtData = function loadExtData(extData, next) {
  18718. var anyIsPromise = extData.some(promise);
  18719. if (anyIsPromise) {
  18720. return Promise$1.all(extData).then(next); // load all data asynchronously, then exec rest of init
  18721. } else {
  18722. next(extData); // exec synchronously for convenience
  18723. }
  18724. };
  18725. // start with the default stylesheet so we have something before loading an external stylesheet
  18726. if (_p.styleEnabled) {
  18727. cy.setStyle([]);
  18728. }
  18729. // create the renderer
  18730. var rendererOptions = extend({}, options, options.renderer); // allow rendering hints in top level options
  18731. cy.initRenderer(rendererOptions);
  18732. var setElesAndLayout = function setElesAndLayout(elements, onload, ondone) {
  18733. cy.notifications(false);
  18734. // remove old elements
  18735. var oldEles = cy.mutableElements();
  18736. if (oldEles.length > 0) {
  18737. oldEles.remove();
  18738. }
  18739. if (elements != null) {
  18740. if (plainObject(elements) || array(elements)) {
  18741. cy.add(elements);
  18742. }
  18743. }
  18744. cy.one('layoutready', function (e) {
  18745. cy.notifications(true);
  18746. cy.emit(e); // we missed this event by turning notifications off, so pass it on
  18747. cy.one('load', onload);
  18748. cy.emitAndNotify('load');
  18749. }).one('layoutstop', function () {
  18750. cy.one('done', ondone);
  18751. cy.emit('done');
  18752. });
  18753. var layoutOpts = extend({}, cy._private.options.layout);
  18754. layoutOpts.eles = cy.elements();
  18755. cy.layout(layoutOpts).run();
  18756. };
  18757. loadExtData([options.style, options.elements], function (thens) {
  18758. var initStyle = thens[0];
  18759. var initEles = thens[1];
  18760. // init style
  18761. if (_p.styleEnabled) {
  18762. cy.style().append(initStyle);
  18763. }
  18764. // initial load
  18765. setElesAndLayout(initEles, function () {
  18766. // onready
  18767. cy.startAnimationLoop();
  18768. _p.ready = true;
  18769. // if a ready callback is specified as an option, the bind it
  18770. if (fn$6(options.ready)) {
  18771. cy.on('ready', options.ready);
  18772. }
  18773. // bind all the ready handlers registered before creating this instance
  18774. for (var i = 0; i < readies.length; i++) {
  18775. var fn = readies[i];
  18776. cy.on('ready', fn);
  18777. }
  18778. if (reg) {
  18779. reg.readies = [];
  18780. } // 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
  18781. cy.emit('ready');
  18782. }, options.done);
  18783. });
  18784. };
  18785. var corefn = Core.prototype; // short alias
  18786. extend(corefn, {
  18787. instanceString: function instanceString() {
  18788. return 'core';
  18789. },
  18790. isReady: function isReady() {
  18791. return this._private.ready;
  18792. },
  18793. destroyed: function destroyed() {
  18794. return this._private.destroyed;
  18795. },
  18796. ready: function ready(fn) {
  18797. if (this.isReady()) {
  18798. this.emitter().emit('ready', [], fn); // just calls fn as though triggered via ready event
  18799. } else {
  18800. this.on('ready', fn);
  18801. }
  18802. return this;
  18803. },
  18804. destroy: function destroy() {
  18805. var cy = this;
  18806. if (cy.destroyed()) return;
  18807. cy.stopAnimationLoop();
  18808. cy.destroyRenderer();
  18809. this.emit('destroy');
  18810. cy._private.destroyed = true;
  18811. return cy;
  18812. },
  18813. hasElementWithId: function hasElementWithId(id) {
  18814. return this._private.elements.hasElementWithId(id);
  18815. },
  18816. getElementById: function getElementById(id) {
  18817. return this._private.elements.getElementById(id);
  18818. },
  18819. hasCompoundNodes: function hasCompoundNodes() {
  18820. return this._private.hasCompoundNodes;
  18821. },
  18822. headless: function headless() {
  18823. return this._private.renderer.isHeadless();
  18824. },
  18825. styleEnabled: function styleEnabled() {
  18826. return this._private.styleEnabled;
  18827. },
  18828. addToPool: function addToPool(eles) {
  18829. this._private.elements.merge(eles);
  18830. return this; // chaining
  18831. },
  18832. removeFromPool: function removeFromPool(eles) {
  18833. this._private.elements.unmerge(eles);
  18834. return this;
  18835. },
  18836. container: function container() {
  18837. return this._private.container || null;
  18838. },
  18839. window: function window() {
  18840. var container = this._private.container;
  18841. if (container == null) return _window;
  18842. var ownerDocument = this._private.container.ownerDocument;
  18843. if (ownerDocument === undefined || ownerDocument == null) {
  18844. return _window;
  18845. }
  18846. return ownerDocument.defaultView || _window;
  18847. },
  18848. mount: function mount(container) {
  18849. if (container == null) {
  18850. return;
  18851. }
  18852. var cy = this;
  18853. var _p = cy._private;
  18854. var options = _p.options;
  18855. if (!htmlElement(container) && htmlElement(container[0])) {
  18856. container = container[0];
  18857. }
  18858. cy.stopAnimationLoop();
  18859. cy.destroyRenderer();
  18860. _p.container = container;
  18861. _p.styleEnabled = true;
  18862. cy.invalidateSize();
  18863. cy.initRenderer(extend({}, options, options.renderer, {
  18864. // allow custom renderer name to be re-used, otherwise use canvas
  18865. name: options.renderer.name === 'null' ? 'canvas' : options.renderer.name
  18866. }));
  18867. cy.startAnimationLoop();
  18868. cy.style(options.style);
  18869. cy.emit('mount');
  18870. return cy;
  18871. },
  18872. unmount: function unmount() {
  18873. var cy = this;
  18874. cy.stopAnimationLoop();
  18875. cy.destroyRenderer();
  18876. cy.initRenderer({
  18877. name: 'null'
  18878. });
  18879. cy.emit('unmount');
  18880. return cy;
  18881. },
  18882. options: function options() {
  18883. return copy(this._private.options);
  18884. },
  18885. json: function json(obj) {
  18886. var cy = this;
  18887. var _p = cy._private;
  18888. var eles = cy.mutableElements();
  18889. var getFreshRef = function getFreshRef(ele) {
  18890. return cy.getElementById(ele.id());
  18891. };
  18892. if (plainObject(obj)) {
  18893. // set
  18894. cy.startBatch();
  18895. if (obj.elements) {
  18896. var idInJson = {};
  18897. var updateEles = function updateEles(jsons, gr) {
  18898. var toAdd = [];
  18899. var toMod = [];
  18900. for (var i = 0; i < jsons.length; i++) {
  18901. var json = jsons[i];
  18902. if (!json.data.id) {
  18903. warn('cy.json() cannot handle elements without an ID attribute');
  18904. continue;
  18905. }
  18906. var id = '' + json.data.id; // id must be string
  18907. var ele = cy.getElementById(id);
  18908. idInJson[id] = true;
  18909. if (ele.length !== 0) {
  18910. // existing element should be updated
  18911. toMod.push({
  18912. ele: ele,
  18913. json: json
  18914. });
  18915. } else {
  18916. // otherwise should be added
  18917. if (gr) {
  18918. json.group = gr;
  18919. toAdd.push(json);
  18920. } else {
  18921. toAdd.push(json);
  18922. }
  18923. }
  18924. }
  18925. cy.add(toAdd);
  18926. for (var _i = 0; _i < toMod.length; _i++) {
  18927. var _toMod$_i = toMod[_i],
  18928. _ele = _toMod$_i.ele,
  18929. _json = _toMod$_i.json;
  18930. _ele.json(_json);
  18931. }
  18932. };
  18933. if (array(obj.elements)) {
  18934. // elements: []
  18935. updateEles(obj.elements);
  18936. } else {
  18937. // elements: { nodes: [], edges: [] }
  18938. var grs = ['nodes', 'edges'];
  18939. for (var i = 0; i < grs.length; i++) {
  18940. var gr = grs[i];
  18941. var elements = obj.elements[gr];
  18942. if (array(elements)) {
  18943. updateEles(elements, gr);
  18944. }
  18945. }
  18946. }
  18947. var parentsToRemove = cy.collection();
  18948. eles.filter(function (ele) {
  18949. return !idInJson[ele.id()];
  18950. }).forEach(function (ele) {
  18951. if (ele.isParent()) {
  18952. parentsToRemove.merge(ele);
  18953. } else {
  18954. ele.remove();
  18955. }
  18956. });
  18957. // so that children are not removed w/parent
  18958. parentsToRemove.forEach(function (ele) {
  18959. return ele.children().move({
  18960. parent: null
  18961. });
  18962. });
  18963. // intermediate parents may be moved by prior line, so make sure we remove by fresh refs
  18964. parentsToRemove.forEach(function (ele) {
  18965. return getFreshRef(ele).remove();
  18966. });
  18967. }
  18968. if (obj.style) {
  18969. cy.style(obj.style);
  18970. }
  18971. if (obj.zoom != null && obj.zoom !== _p.zoom) {
  18972. cy.zoom(obj.zoom);
  18973. }
  18974. if (obj.pan) {
  18975. if (obj.pan.x !== _p.pan.x || obj.pan.y !== _p.pan.y) {
  18976. cy.pan(obj.pan);
  18977. }
  18978. }
  18979. if (obj.data) {
  18980. cy.data(obj.data);
  18981. }
  18982. var fields = ['minZoom', 'maxZoom', 'zoomingEnabled', 'userZoomingEnabled', 'panningEnabled', 'userPanningEnabled', 'boxSelectionEnabled', 'autolock', 'autoungrabify', 'autounselectify', 'multiClickDebounceTime'];
  18983. for (var _i2 = 0; _i2 < fields.length; _i2++) {
  18984. var f = fields[_i2];
  18985. if (obj[f] != null) {
  18986. cy[f](obj[f]);
  18987. }
  18988. }
  18989. cy.endBatch();
  18990. return this; // chaining
  18991. } else {
  18992. // get
  18993. var flat = !!obj;
  18994. var json = {};
  18995. if (flat) {
  18996. json.elements = this.elements().map(function (ele) {
  18997. return ele.json();
  18998. });
  18999. } else {
  19000. json.elements = {};
  19001. eles.forEach(function (ele) {
  19002. var group = ele.group();
  19003. if (!json.elements[group]) {
  19004. json.elements[group] = [];
  19005. }
  19006. json.elements[group].push(ele.json());
  19007. });
  19008. }
  19009. if (this._private.styleEnabled) {
  19010. json.style = cy.style().json();
  19011. }
  19012. json.data = copy(cy.data());
  19013. var options = _p.options;
  19014. json.zoomingEnabled = _p.zoomingEnabled;
  19015. json.userZoomingEnabled = _p.userZoomingEnabled;
  19016. json.zoom = _p.zoom;
  19017. json.minZoom = _p.minZoom;
  19018. json.maxZoom = _p.maxZoom;
  19019. json.panningEnabled = _p.panningEnabled;
  19020. json.userPanningEnabled = _p.userPanningEnabled;
  19021. json.pan = copy(_p.pan);
  19022. json.boxSelectionEnabled = _p.boxSelectionEnabled;
  19023. json.renderer = copy(options.renderer);
  19024. json.hideEdgesOnViewport = options.hideEdgesOnViewport;
  19025. json.textureOnViewport = options.textureOnViewport;
  19026. json.wheelSensitivity = options.wheelSensitivity;
  19027. json.motionBlur = options.motionBlur;
  19028. json.multiClickDebounceTime = options.multiClickDebounceTime;
  19029. return json;
  19030. }
  19031. }
  19032. });
  19033. corefn.$id = corefn.getElementById;
  19034. [corefn$9, corefn$8, elesfn, corefn$7, corefn$6, corefn$5, corefn$4, corefn$3, corefn$2, corefn$1, fn].forEach(function (props) {
  19035. extend(corefn, props);
  19036. });
  19037. /* eslint-disable no-unused-vars */
  19038. var defaults$7 = {
  19039. fit: true,
  19040. // whether to fit the viewport to the graph
  19041. directed: false,
  19042. // whether the tree is directed downwards (or edges can point in any direction if false)
  19043. direction: 'downward',
  19044. // determines the direction in which the tree structure is drawn. The possible values are 'downward', 'upward', 'rightward', or 'leftward'.
  19045. padding: 30,
  19046. // padding on fit
  19047. circle: false,
  19048. // put depths in concentric circles if true, put depths top down if false
  19049. grid: false,
  19050. // whether to create an even grid into which the DAG is placed (circle:false only)
  19051. spacingFactor: 1.75,
  19052. // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)
  19053. boundingBox: undefined,
  19054. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19055. avoidOverlap: true,
  19056. // prevents node overlap, may overflow boundingBox if not enough space
  19057. nodeDimensionsIncludeLabels: false,
  19058. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19059. roots: undefined,
  19060. // the roots of the trees
  19061. depthSort: undefined,
  19062. // a sorting function to order nodes at equal depth. e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  19063. animate: false,
  19064. // whether to transition the node positions
  19065. animationDuration: 500,
  19066. // duration of animation in ms if enabled
  19067. animationEasing: undefined,
  19068. // easing of animation if enabled,
  19069. animateFilter: function animateFilter(node, i) {
  19070. return true;
  19071. },
  19072. // 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
  19073. ready: undefined,
  19074. // callback on layoutready
  19075. stop: undefined,
  19076. // callback on layoutstop
  19077. transform: function transform(node, position) {
  19078. return position;
  19079. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19080. };
  19081. var deprecatedOptionDefaults = {
  19082. maximal: false,
  19083. // 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
  19084. 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
  19085. };
  19086. /* eslint-enable */
  19087. var getInfo = function getInfo(ele) {
  19088. return ele.scratch('breadthfirst');
  19089. };
  19090. var setInfo = function setInfo(ele, obj) {
  19091. return ele.scratch('breadthfirst', obj);
  19092. };
  19093. function BreadthFirstLayout(options) {
  19094. this.options = extend({}, defaults$7, deprecatedOptionDefaults, options);
  19095. }
  19096. BreadthFirstLayout.prototype.run = function () {
  19097. var options = this.options;
  19098. var cy = options.cy;
  19099. var eles = options.eles;
  19100. var nodes = eles.nodes().filter(function (n) {
  19101. return n.isChildless();
  19102. });
  19103. var graph = eles;
  19104. var directed = options.directed;
  19105. var maximal = options.acyclic || options.maximal || options.maximalAdjustments > 0; // maximalAdjustments for compat. w/ old code; also, setting acyclic to true sets maximal to true
  19106. var hasBoundingBox = !!options.boundingBox;
  19107. var bb = makeBoundingBox(hasBoundingBox ? options.boundingBox : structuredClone(cy.extent()));
  19108. var roots;
  19109. if (elementOrCollection(options.roots)) {
  19110. roots = options.roots;
  19111. } else if (array(options.roots)) {
  19112. var rootsArray = [];
  19113. for (var i = 0; i < options.roots.length; i++) {
  19114. var id = options.roots[i];
  19115. var ele = cy.getElementById(id);
  19116. rootsArray.push(ele);
  19117. }
  19118. roots = cy.collection(rootsArray);
  19119. } else if (string(options.roots)) {
  19120. roots = cy.$(options.roots);
  19121. } else {
  19122. if (directed) {
  19123. roots = nodes.roots();
  19124. } else {
  19125. var components = eles.components();
  19126. roots = cy.collection();
  19127. var _loop = function _loop() {
  19128. var comp = components[_i];
  19129. var maxDegree = comp.maxDegree(false);
  19130. var compRoots = comp.filter(function (ele) {
  19131. return ele.degree(false) === maxDegree;
  19132. });
  19133. roots = roots.add(compRoots);
  19134. };
  19135. for (var _i = 0; _i < components.length; _i++) {
  19136. _loop();
  19137. }
  19138. }
  19139. }
  19140. var depths = [];
  19141. var foundByBfs = {};
  19142. var addToDepth = function addToDepth(ele, d) {
  19143. if (depths[d] == null) {
  19144. depths[d] = [];
  19145. }
  19146. var i = depths[d].length;
  19147. depths[d].push(ele);
  19148. setInfo(ele, {
  19149. index: i,
  19150. depth: d
  19151. });
  19152. };
  19153. var changeDepth = function changeDepth(ele, newDepth) {
  19154. var _getInfo = getInfo(ele),
  19155. depth = _getInfo.depth,
  19156. index = _getInfo.index;
  19157. depths[depth][index] = null;
  19158. // add only childless nodes
  19159. if (ele.isChildless()) addToDepth(ele, newDepth);
  19160. };
  19161. // find the depths of the nodes
  19162. graph.bfs({
  19163. roots: roots,
  19164. directed: options.directed,
  19165. visit: function visit(node, edge, pNode, i, depth) {
  19166. var ele = node[0];
  19167. var id = ele.id();
  19168. // add only childless nodes
  19169. if (ele.isChildless()) addToDepth(ele, depth);
  19170. foundByBfs[id] = true;
  19171. }
  19172. });
  19173. // check for nodes not found by bfs
  19174. var orphanNodes = [];
  19175. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  19176. var _ele = nodes[_i2];
  19177. if (foundByBfs[_ele.id()]) {
  19178. continue;
  19179. } else {
  19180. orphanNodes.push(_ele);
  19181. }
  19182. }
  19183. // assign the nodes a depth and index
  19184. var assignDepthsAt = function assignDepthsAt(i) {
  19185. var eles = depths[i];
  19186. for (var j = 0; j < eles.length; j++) {
  19187. var _ele2 = eles[j];
  19188. if (_ele2 == null) {
  19189. eles.splice(j, 1);
  19190. j--;
  19191. continue;
  19192. }
  19193. setInfo(_ele2, {
  19194. depth: i,
  19195. index: j
  19196. });
  19197. }
  19198. };
  19199. var adjustMaximally = function adjustMaximally(ele, shifted) {
  19200. var eInfo = getInfo(ele);
  19201. var incomers = ele.incomers().filter(function (el) {
  19202. return el.isNode() && eles.has(el);
  19203. });
  19204. var maxDepth = -1;
  19205. var id = ele.id();
  19206. for (var k = 0; k < incomers.length; k++) {
  19207. var incmr = incomers[k];
  19208. var iInfo = getInfo(incmr);
  19209. maxDepth = Math.max(maxDepth, iInfo.depth);
  19210. }
  19211. if (eInfo.depth <= maxDepth) {
  19212. if (!options.acyclic && shifted[id]) {
  19213. return null;
  19214. }
  19215. var newDepth = maxDepth + 1;
  19216. changeDepth(ele, newDepth);
  19217. shifted[id] = newDepth;
  19218. return true;
  19219. }
  19220. return false;
  19221. };
  19222. // for the directed case, try to make the edges all go down (i.e. depth i => depth i + 1)
  19223. if (directed && maximal) {
  19224. var Q = [];
  19225. var shifted = {};
  19226. var enqueue = function enqueue(n) {
  19227. return Q.push(n);
  19228. };
  19229. var dequeue = function dequeue() {
  19230. return Q.shift();
  19231. };
  19232. nodes.forEach(function (n) {
  19233. return Q.push(n);
  19234. });
  19235. while (Q.length > 0) {
  19236. var _ele3 = dequeue();
  19237. var didShift = adjustMaximally(_ele3, shifted);
  19238. if (didShift) {
  19239. _ele3.outgoers().filter(function (el) {
  19240. return el.isNode() && eles.has(el);
  19241. }).forEach(enqueue);
  19242. } else if (didShift === null) {
  19243. warn('Detected double maximal shift for node `' + _ele3.id() + '`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.');
  19244. break; // exit on failure
  19245. }
  19246. }
  19247. }
  19248. // find min distance we need to leave between nodes
  19249. var minDistance = 0;
  19250. if (options.avoidOverlap) {
  19251. for (var _i3 = 0; _i3 < nodes.length; _i3++) {
  19252. var n = nodes[_i3];
  19253. var nbb = n.layoutDimensions(options);
  19254. var w = nbb.w;
  19255. var h = nbb.h;
  19256. minDistance = Math.max(minDistance, w, h);
  19257. }
  19258. }
  19259. // get the weighted percent for an element based on its connectivity to other levels
  19260. var cachedWeightedPercent = {};
  19261. var getWeightedPercent = function getWeightedPercent(ele) {
  19262. if (cachedWeightedPercent[ele.id()]) {
  19263. return cachedWeightedPercent[ele.id()];
  19264. }
  19265. var eleDepth = getInfo(ele).depth;
  19266. var neighbors = ele.neighborhood();
  19267. var percent = 0;
  19268. var samples = 0;
  19269. for (var _i4 = 0; _i4 < neighbors.length; _i4++) {
  19270. var neighbor = neighbors[_i4];
  19271. if (neighbor.isEdge() || neighbor.isParent() || !nodes.has(neighbor)) {
  19272. continue;
  19273. }
  19274. var bf = getInfo(neighbor);
  19275. if (bf == null) {
  19276. continue;
  19277. }
  19278. var index = bf.index;
  19279. var depth = bf.depth;
  19280. // unassigned neighbours shouldn't affect the ordering
  19281. if (index == null || depth == null) {
  19282. continue;
  19283. }
  19284. var nDepth = depths[depth].length;
  19285. if (depth < eleDepth) {
  19286. // only get influenced by elements above
  19287. percent += index / nDepth;
  19288. samples++;
  19289. }
  19290. }
  19291. samples = Math.max(1, samples);
  19292. percent = percent / samples;
  19293. if (samples === 0) {
  19294. // put lone nodes at the start
  19295. percent = 0;
  19296. }
  19297. cachedWeightedPercent[ele.id()] = percent;
  19298. return percent;
  19299. };
  19300. // rearrange the indices in each depth level based on connectivity
  19301. var sortFn = function sortFn(a, b) {
  19302. var apct = getWeightedPercent(a);
  19303. var bpct = getWeightedPercent(b);
  19304. var diff = apct - bpct;
  19305. if (diff === 0) {
  19306. return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons
  19307. } else {
  19308. return diff;
  19309. }
  19310. };
  19311. if (options.depthSort !== undefined) {
  19312. sortFn = options.depthSort;
  19313. }
  19314. var depthsLen = depths.length;
  19315. // sort each level to make connected nodes closer
  19316. for (var _i5 = 0; _i5 < depthsLen; _i5++) {
  19317. depths[_i5].sort(sortFn);
  19318. assignDepthsAt(_i5);
  19319. }
  19320. // assign orphan nodes to a new top-level depth
  19321. var orphanDepth = [];
  19322. for (var _i6 = 0; _i6 < orphanNodes.length; _i6++) {
  19323. orphanDepth.push(orphanNodes[_i6]);
  19324. }
  19325. var assignDepths = function assignDepths() {
  19326. for (var _i7 = 0; _i7 < depthsLen; _i7++) {
  19327. assignDepthsAt(_i7);
  19328. }
  19329. };
  19330. // add a new top-level depth only when there are orphan nodes
  19331. if (orphanDepth.length) {
  19332. depths.unshift(orphanDepth);
  19333. depthsLen = depths.length;
  19334. assignDepths();
  19335. }
  19336. var biggestDepthSize = 0;
  19337. for (var _i8 = 0; _i8 < depthsLen; _i8++) {
  19338. biggestDepthSize = Math.max(depths[_i8].length, biggestDepthSize);
  19339. }
  19340. var center = {
  19341. x: bb.x1 + bb.w / 2,
  19342. y: bb.y1 + bb.h / 2
  19343. };
  19344. // average node size
  19345. var aveNodeSize = nodes.reduce(function (acc, node) {
  19346. return function (box) {
  19347. return {
  19348. w: acc.w === -1 ? box.w : (acc.w + box.w) / 2,
  19349. h: acc.h === -1 ? box.h : (acc.h + box.h) / 2
  19350. };
  19351. }(node.boundingBox({
  19352. includeLabels: options.nodeDimensionsIncludeLabels
  19353. }));
  19354. }, {
  19355. w: -1,
  19356. h: -1
  19357. });
  19358. var distanceY = Math.max(
  19359. // only one depth
  19360. depthsLen === 1 ? 0 :
  19361. // inside a bounding box, no need for top & bottom padding
  19362. hasBoundingBox ? (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen - 1) : (bb.h - options.padding * 2 - aveNodeSize.h) / (depthsLen + 1), minDistance);
  19363. var maxDepthSize = depths.reduce(function (max, eles) {
  19364. return Math.max(max, eles.length);
  19365. }, 0);
  19366. var getPositionTopBottom = function getPositionTopBottom(ele) {
  19367. var _getInfo2 = getInfo(ele),
  19368. depth = _getInfo2.depth,
  19369. index = _getInfo2.index;
  19370. if (options.circle) {
  19371. var radiusStepSize = Math.min(bb.w / 2 / depthsLen, bb.h / 2 / depthsLen);
  19372. radiusStepSize = Math.max(radiusStepSize, minDistance);
  19373. var radius = radiusStepSize * depth + radiusStepSize - (depthsLen > 0 && depths[0].length <= 3 ? radiusStepSize / 2 : 0);
  19374. var theta = 2 * Math.PI / depths[depth].length * index;
  19375. if (depth === 0 && depths[0].length === 1) {
  19376. radius = 1;
  19377. }
  19378. return {
  19379. x: center.x + radius * Math.cos(theta),
  19380. y: center.y + radius * Math.sin(theta)
  19381. };
  19382. } else {
  19383. var depthSize = depths[depth].length;
  19384. var distanceX = Math.max(
  19385. // only one depth
  19386. depthSize === 1 ? 0 :
  19387. // inside a bounding box, no need for left & right padding
  19388. 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);
  19389. var epos = {
  19390. x: center.x + (index + 1 - (depthSize + 1) / 2) * distanceX,
  19391. y: center.y + (depth + 1 - (depthsLen + 1) / 2) * distanceY
  19392. };
  19393. return epos;
  19394. }
  19395. };
  19396. var rotateDegrees = {
  19397. 'downward': 0,
  19398. 'leftward': 90,
  19399. 'upward': 180,
  19400. 'rightward': -90
  19401. };
  19402. if (Object.keys(rotateDegrees).indexOf(options.direction) === -1) {
  19403. error("Invalid direction '".concat(options.direction, "' specified for breadthfirst layout. Valid values are: ").concat(Object.keys(rotateDegrees).join(', ')));
  19404. }
  19405. var getPosition = function getPosition(ele) {
  19406. return rotatePosAndSkewByBox(getPositionTopBottom(ele), bb, rotateDegrees[options.direction]);
  19407. };
  19408. eles.nodes().layoutPositions(this, options, getPosition);
  19409. return this; // chaining
  19410. };
  19411. var defaults$6 = {
  19412. fit: true,
  19413. // whether to fit the viewport to the graph
  19414. padding: 30,
  19415. // the padding on fit
  19416. boundingBox: undefined,
  19417. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19418. avoidOverlap: true,
  19419. // prevents node overlap, may overflow boundingBox and radius if not enough space
  19420. nodeDimensionsIncludeLabels: false,
  19421. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19422. spacingFactor: undefined,
  19423. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  19424. radius: undefined,
  19425. // the radius of the circle
  19426. startAngle: 3 / 2 * Math.PI,
  19427. // where nodes start in radians
  19428. sweep: undefined,
  19429. // how many radians should be between the first and last node (defaults to full circle)
  19430. clockwise: true,
  19431. // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  19432. sort: undefined,
  19433. // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  19434. animate: false,
  19435. // whether to transition the node positions
  19436. animationDuration: 500,
  19437. // duration of animation in ms if enabled
  19438. animationEasing: undefined,
  19439. // easing of animation if enabled
  19440. animateFilter: function animateFilter(node, i) {
  19441. return true;
  19442. },
  19443. // 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
  19444. ready: undefined,
  19445. // callback on layoutready
  19446. stop: undefined,
  19447. // callback on layoutstop
  19448. transform: function transform(node, position) {
  19449. return position;
  19450. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19451. };
  19452. function CircleLayout(options) {
  19453. this.options = extend({}, defaults$6, options);
  19454. }
  19455. CircleLayout.prototype.run = function () {
  19456. var params = this.options;
  19457. var options = params;
  19458. var cy = params.cy;
  19459. var eles = options.eles;
  19460. var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  19461. var nodes = eles.nodes().not(':parent');
  19462. if (options.sort) {
  19463. nodes = nodes.sort(options.sort);
  19464. }
  19465. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19466. x1: 0,
  19467. y1: 0,
  19468. w: cy.width(),
  19469. h: cy.height()
  19470. });
  19471. var center = {
  19472. x: bb.x1 + bb.w / 2,
  19473. y: bb.y1 + bb.h / 2
  19474. };
  19475. var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / nodes.length : options.sweep;
  19476. var dTheta = sweep / Math.max(1, nodes.length - 1);
  19477. var r;
  19478. var minDistance = 0;
  19479. for (var i = 0; i < nodes.length; i++) {
  19480. var n = nodes[i];
  19481. var nbb = n.layoutDimensions(options);
  19482. var w = nbb.w;
  19483. var h = nbb.h;
  19484. minDistance = Math.max(minDistance, w, h);
  19485. }
  19486. if (number$1(options.radius)) {
  19487. r = options.radius;
  19488. } else if (nodes.length <= 1) {
  19489. r = 0;
  19490. } else {
  19491. r = Math.min(bb.h, bb.w) / 2 - minDistance;
  19492. }
  19493. // calculate the radius
  19494. if (nodes.length > 1 && options.avoidOverlap) {
  19495. // but only if more than one node (can't overlap)
  19496. minDistance *= 1.75; // just to have some nice spacing
  19497. var dcos = Math.cos(dTheta) - Math.cos(0);
  19498. var dsin = Math.sin(dTheta) - Math.sin(0);
  19499. var rMin = Math.sqrt(minDistance * minDistance / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
  19500. r = Math.max(rMin, r);
  19501. }
  19502. var getPos = function getPos(ele, i) {
  19503. var theta = options.startAngle + i * dTheta * (clockwise ? 1 : -1);
  19504. var rx = r * Math.cos(theta);
  19505. var ry = r * Math.sin(theta);
  19506. var pos = {
  19507. x: center.x + rx,
  19508. y: center.y + ry
  19509. };
  19510. return pos;
  19511. };
  19512. eles.nodes().layoutPositions(this, options, getPos);
  19513. return this; // chaining
  19514. };
  19515. var defaults$5 = {
  19516. fit: true,
  19517. // whether to fit the viewport to the graph
  19518. padding: 30,
  19519. // the padding on fit
  19520. startAngle: 3 / 2 * Math.PI,
  19521. // where nodes start in radians
  19522. sweep: undefined,
  19523. // how many radians should be between the first and last node (defaults to full circle)
  19524. clockwise: true,
  19525. // whether the layout should go clockwise (true) or counterclockwise/anticlockwise (false)
  19526. equidistant: false,
  19527. // whether levels have an equal radial distance betwen them, may cause bounding box overflow
  19528. minNodeSpacing: 10,
  19529. // min spacing between outside of nodes (used for radius adjustment)
  19530. boundingBox: undefined,
  19531. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19532. avoidOverlap: true,
  19533. // prevents node overlap, may overflow boundingBox if not enough space
  19534. nodeDimensionsIncludeLabels: false,
  19535. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19536. height: undefined,
  19537. // height of layout area (overrides container height)
  19538. width: undefined,
  19539. // width of layout area (overrides container width)
  19540. spacingFactor: undefined,
  19541. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  19542. concentric: function concentric(node) {
  19543. // returns numeric value for each node, placing higher nodes in levels towards the centre
  19544. return node.degree();
  19545. },
  19546. levelWidth: function levelWidth(nodes) {
  19547. // the variation of concentric values in each level
  19548. return nodes.maxDegree() / 4;
  19549. },
  19550. animate: false,
  19551. // whether to transition the node positions
  19552. animationDuration: 500,
  19553. // duration of animation in ms if enabled
  19554. animationEasing: undefined,
  19555. // easing of animation if enabled
  19556. animateFilter: function animateFilter(node, i) {
  19557. return true;
  19558. },
  19559. // 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
  19560. ready: undefined,
  19561. // callback on layoutready
  19562. stop: undefined,
  19563. // callback on layoutstop
  19564. transform: function transform(node, position) {
  19565. return position;
  19566. } // transform a given node position. Useful for changing flow direction in discrete layouts
  19567. };
  19568. function ConcentricLayout(options) {
  19569. this.options = extend({}, defaults$5, options);
  19570. }
  19571. ConcentricLayout.prototype.run = function () {
  19572. var params = this.options;
  19573. var options = params;
  19574. var clockwise = options.counterclockwise !== undefined ? !options.counterclockwise : options.clockwise;
  19575. var cy = params.cy;
  19576. var eles = options.eles;
  19577. var nodes = eles.nodes().not(':parent');
  19578. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19579. x1: 0,
  19580. y1: 0,
  19581. w: cy.width(),
  19582. h: cy.height()
  19583. });
  19584. var center = {
  19585. x: bb.x1 + bb.w / 2,
  19586. y: bb.y1 + bb.h / 2
  19587. };
  19588. var nodeValues = []; // { node, value }
  19589. var maxNodeSize = 0;
  19590. for (var i = 0; i < nodes.length; i++) {
  19591. var node = nodes[i];
  19592. var value = undefined;
  19593. // calculate the node value
  19594. value = options.concentric(node);
  19595. nodeValues.push({
  19596. value: value,
  19597. node: node
  19598. });
  19599. // for style mapping
  19600. node._private.scratch.concentric = value;
  19601. }
  19602. // in case we used the `concentric` in style
  19603. nodes.updateStyle();
  19604. // calculate max size now based on potentially updated mappers
  19605. for (var _i = 0; _i < nodes.length; _i++) {
  19606. var _node = nodes[_i];
  19607. var nbb = _node.layoutDimensions(options);
  19608. maxNodeSize = Math.max(maxNodeSize, nbb.w, nbb.h);
  19609. }
  19610. // sort node values in descreasing order
  19611. nodeValues.sort(function (a, b) {
  19612. return b.value - a.value;
  19613. });
  19614. var levelWidth = options.levelWidth(nodes);
  19615. // put the values into levels
  19616. var levels = [[]];
  19617. var currentLevel = levels[0];
  19618. for (var _i2 = 0; _i2 < nodeValues.length; _i2++) {
  19619. var val = nodeValues[_i2];
  19620. if (currentLevel.length > 0) {
  19621. var diff = Math.abs(currentLevel[0].value - val.value);
  19622. if (diff >= levelWidth) {
  19623. currentLevel = [];
  19624. levels.push(currentLevel);
  19625. }
  19626. }
  19627. currentLevel.push(val);
  19628. }
  19629. // create positions from levels
  19630. var minDist = maxNodeSize + options.minNodeSpacing; // min dist between nodes
  19631. if (!options.avoidOverlap) {
  19632. // then strictly constrain to bb
  19633. var firstLvlHasMulti = levels.length > 0 && levels[0].length > 1;
  19634. var maxR = Math.min(bb.w, bb.h) / 2 - minDist;
  19635. var rStep = maxR / (levels.length + firstLvlHasMulti ? 1 : 0);
  19636. minDist = Math.min(minDist, rStep);
  19637. }
  19638. // find the metrics for each level
  19639. var r = 0;
  19640. for (var _i3 = 0; _i3 < levels.length; _i3++) {
  19641. var level = levels[_i3];
  19642. var sweep = options.sweep === undefined ? 2 * Math.PI - 2 * Math.PI / level.length : options.sweep;
  19643. var dTheta = level.dTheta = sweep / Math.max(1, level.length - 1);
  19644. // calculate the radius
  19645. if (level.length > 1 && options.avoidOverlap) {
  19646. // but only if more than one node (can't overlap)
  19647. var dcos = Math.cos(dTheta) - Math.cos(0);
  19648. var dsin = Math.sin(dTheta) - Math.sin(0);
  19649. var rMin = Math.sqrt(minDist * minDist / (dcos * dcos + dsin * dsin)); // s.t. no nodes overlapping
  19650. r = Math.max(rMin, r);
  19651. }
  19652. level.r = r;
  19653. r += minDist;
  19654. }
  19655. if (options.equidistant) {
  19656. var rDeltaMax = 0;
  19657. var _r = 0;
  19658. for (var _i4 = 0; _i4 < levels.length; _i4++) {
  19659. var _level = levels[_i4];
  19660. var rDelta = _level.r - _r;
  19661. rDeltaMax = Math.max(rDeltaMax, rDelta);
  19662. }
  19663. _r = 0;
  19664. for (var _i5 = 0; _i5 < levels.length; _i5++) {
  19665. var _level2 = levels[_i5];
  19666. if (_i5 === 0) {
  19667. _r = _level2.r;
  19668. }
  19669. _level2.r = _r;
  19670. _r += rDeltaMax;
  19671. }
  19672. }
  19673. // calculate the node positions
  19674. var pos = {}; // id => position
  19675. for (var _i6 = 0; _i6 < levels.length; _i6++) {
  19676. var _level3 = levels[_i6];
  19677. var _dTheta = _level3.dTheta;
  19678. var _r2 = _level3.r;
  19679. for (var j = 0; j < _level3.length; j++) {
  19680. var _val = _level3[j];
  19681. var theta = options.startAngle + (clockwise ? 1 : -1) * _dTheta * j;
  19682. var p = {
  19683. x: center.x + _r2 * Math.cos(theta),
  19684. y: center.y + _r2 * Math.sin(theta)
  19685. };
  19686. pos[_val.node.id()] = p;
  19687. }
  19688. }
  19689. // position the nodes
  19690. eles.nodes().layoutPositions(this, options, function (ele) {
  19691. var id = ele.id();
  19692. return pos[id];
  19693. });
  19694. return this; // chaining
  19695. };
  19696. /*
  19697. The CoSE layout was written by Gerardo Huck.
  19698. https://www.linkedin.com/in/gerardohuck/
  19699. Based on the following article:
  19700. http://dl.acm.org/citation.cfm?id=1498047
  19701. Modifications tracked on Github.
  19702. */
  19703. var DEBUG;
  19704. /**
  19705. * @brief : default layout options
  19706. */
  19707. var defaults$4 = {
  19708. // Called on `layoutready`
  19709. ready: function ready() {},
  19710. // Called on `layoutstop`
  19711. stop: function stop() {},
  19712. // Whether to animate while running the layout
  19713. // true : Animate continuously as the layout is running
  19714. // false : Just show the end result
  19715. // 'end' : Animate with the end result, from the initial positions to the end positions
  19716. animate: true,
  19717. // Easing of the animation for animate:'end'
  19718. animationEasing: undefined,
  19719. // The duration of the animation for animate:'end'
  19720. animationDuration: undefined,
  19721. // A function that determines whether the node should be animated
  19722. // All nodes animated by default on animate enabled
  19723. // Non-animated nodes are positioned immediately when the layout starts
  19724. animateFilter: function animateFilter(node, i) {
  19725. return true;
  19726. },
  19727. // The layout animates only after this many milliseconds for animate:true
  19728. // (prevents flashing on fast runs)
  19729. animationThreshold: 250,
  19730. // Number of iterations between consecutive screen positions update
  19731. refresh: 20,
  19732. // Whether to fit the network view after when done
  19733. fit: true,
  19734. // Padding on fit
  19735. padding: 30,
  19736. // Constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  19737. boundingBox: undefined,
  19738. // Excludes the label when calculating node bounding boxes for the layout algorithm
  19739. nodeDimensionsIncludeLabels: false,
  19740. // Randomize the initial positions of the nodes (true) or use existing positions (false)
  19741. randomize: false,
  19742. // Extra spacing between components in non-compound graphs
  19743. componentSpacing: 40,
  19744. // Node repulsion (non overlapping) multiplier
  19745. nodeRepulsion: function nodeRepulsion(node) {
  19746. return 2048;
  19747. },
  19748. // Node repulsion (overlapping) multiplier
  19749. nodeOverlap: 4,
  19750. // Ideal edge (non nested) length
  19751. idealEdgeLength: function idealEdgeLength(edge) {
  19752. return 32;
  19753. },
  19754. // Divisor to compute edge forces
  19755. edgeElasticity: function edgeElasticity(edge) {
  19756. return 32;
  19757. },
  19758. // Nesting factor (multiplier) to compute ideal edge length for nested edges
  19759. nestingFactor: 1.2,
  19760. // Gravity force (constant)
  19761. gravity: 1,
  19762. // Maximum number of iterations to perform
  19763. numIter: 1000,
  19764. // Initial temperature (maximum node displacement)
  19765. initialTemp: 1000,
  19766. // Cooling factor (how the temperature is reduced between consecutive iterations
  19767. coolingFactor: 0.99,
  19768. // Lower temperature threshold (below this point the layout will end)
  19769. minTemp: 1.0
  19770. };
  19771. /**
  19772. * @brief : constructor
  19773. * @arg options : object containing layout options
  19774. */
  19775. function CoseLayout(options) {
  19776. this.options = extend({}, defaults$4, options);
  19777. this.options.layout = this;
  19778. // Exclude any edge that has a source or target node that is not in the set of passed-in nodes
  19779. var nodes = this.options.eles.nodes();
  19780. var edges = this.options.eles.edges();
  19781. var notEdges = edges.filter(function (e) {
  19782. var sourceId = e.source().data('id');
  19783. var targetId = e.target().data('id');
  19784. var hasSource = nodes.some(function (n) {
  19785. return n.data('id') === sourceId;
  19786. });
  19787. var hasTarget = nodes.some(function (n) {
  19788. return n.data('id') === targetId;
  19789. });
  19790. return !hasSource || !hasTarget;
  19791. });
  19792. this.options.eles = this.options.eles.not(notEdges);
  19793. }
  19794. /**
  19795. * @brief : runs the layout
  19796. */
  19797. CoseLayout.prototype.run = function () {
  19798. var options = this.options;
  19799. var cy = options.cy;
  19800. var layout = this;
  19801. layout.stopped = false;
  19802. if (options.animate === true || options.animate === false) {
  19803. layout.emit({
  19804. type: 'layoutstart',
  19805. layout: layout
  19806. });
  19807. }
  19808. // Set DEBUG - Global variable
  19809. if (true === options.debug) {
  19810. DEBUG = true;
  19811. } else {
  19812. DEBUG = false;
  19813. }
  19814. // Initialize layout info
  19815. var layoutInfo = createLayoutInfo(cy, layout, options);
  19816. // Show LayoutInfo contents if debugging
  19817. if (DEBUG) {
  19818. printLayoutInfo(layoutInfo);
  19819. }
  19820. // If required, randomize node positions
  19821. if (options.randomize) {
  19822. randomizePositions(layoutInfo);
  19823. }
  19824. var startTime = performanceNow();
  19825. var refresh = function refresh() {
  19826. refreshPositions(layoutInfo, cy, options);
  19827. // Fit the graph if necessary
  19828. if (true === options.fit) {
  19829. cy.fit(options.padding);
  19830. }
  19831. };
  19832. var mainLoop = function mainLoop(i) {
  19833. if (layout.stopped || i >= options.numIter) {
  19834. // logDebug("Layout manually stopped. Stopping computation in step " + i);
  19835. return false;
  19836. }
  19837. // Do one step in the phisical simulation
  19838. step(layoutInfo, options);
  19839. // Update temperature
  19840. layoutInfo.temperature = layoutInfo.temperature * options.coolingFactor;
  19841. // logDebug("New temperature: " + layoutInfo.temperature);
  19842. if (layoutInfo.temperature < options.minTemp) {
  19843. // logDebug("Temperature drop below minimum threshold. Stopping computation in step " + i);
  19844. return false;
  19845. }
  19846. return true;
  19847. };
  19848. var done = function done() {
  19849. if (options.animate === true || options.animate === false) {
  19850. refresh();
  19851. // Layout has finished
  19852. layout.one('layoutstop', options.stop);
  19853. layout.emit({
  19854. type: 'layoutstop',
  19855. layout: layout
  19856. });
  19857. } else {
  19858. var nodes = options.eles.nodes();
  19859. var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  19860. nodes.layoutPositions(layout, options, getScaledPos);
  19861. }
  19862. };
  19863. var i = 0;
  19864. var loopRet = true;
  19865. if (options.animate === true) {
  19866. var _frame = function frame() {
  19867. var f = 0;
  19868. while (loopRet && f < options.refresh) {
  19869. loopRet = mainLoop(i);
  19870. i++;
  19871. f++;
  19872. }
  19873. if (!loopRet) {
  19874. // it's done
  19875. separateComponents(layoutInfo, options);
  19876. done();
  19877. } else {
  19878. var now = performanceNow();
  19879. if (now - startTime >= options.animationThreshold) {
  19880. refresh();
  19881. }
  19882. requestAnimationFrame(_frame);
  19883. }
  19884. };
  19885. _frame();
  19886. } else {
  19887. while (loopRet) {
  19888. loopRet = mainLoop(i);
  19889. i++;
  19890. }
  19891. separateComponents(layoutInfo, options);
  19892. done();
  19893. }
  19894. return this; // chaining
  19895. };
  19896. /**
  19897. * @brief : called on continuous layouts to stop them before they finish
  19898. */
  19899. CoseLayout.prototype.stop = function () {
  19900. this.stopped = true;
  19901. if (this.thread) {
  19902. this.thread.stop();
  19903. }
  19904. this.emit('layoutstop');
  19905. return this; // chaining
  19906. };
  19907. CoseLayout.prototype.destroy = function () {
  19908. if (this.thread) {
  19909. this.thread.stop();
  19910. }
  19911. return this; // chaining
  19912. };
  19913. /**
  19914. * @brief : Creates an object which is contains all the data
  19915. * used in the layout process
  19916. * @arg cy : cytoscape.js object
  19917. * @return : layoutInfo object initialized
  19918. */
  19919. var createLayoutInfo = function createLayoutInfo(cy, layout, options) {
  19920. // Shortcut
  19921. var edges = options.eles.edges();
  19922. var nodes = options.eles.nodes();
  19923. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  19924. x1: 0,
  19925. y1: 0,
  19926. w: cy.width(),
  19927. h: cy.height()
  19928. });
  19929. var layoutInfo = {
  19930. isCompound: cy.hasCompoundNodes(),
  19931. layoutNodes: [],
  19932. idToIndex: {},
  19933. nodeSize: nodes.size(),
  19934. graphSet: [],
  19935. indexToGraph: [],
  19936. layoutEdges: [],
  19937. edgeSize: edges.size(),
  19938. temperature: options.initialTemp,
  19939. clientWidth: bb.w,
  19940. clientHeight: bb.h,
  19941. boundingBox: bb
  19942. };
  19943. var components = options.eles.components();
  19944. var id2cmptId = {};
  19945. for (var i = 0; i < components.length; i++) {
  19946. var component = components[i];
  19947. for (var j = 0; j < component.length; j++) {
  19948. var node = component[j];
  19949. id2cmptId[node.id()] = i;
  19950. }
  19951. }
  19952. // Iterate over all nodes, creating layout nodes
  19953. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  19954. var n = nodes[i];
  19955. var nbb = n.layoutDimensions(options);
  19956. var tempNode = {};
  19957. tempNode.isLocked = n.locked();
  19958. tempNode.id = n.data('id');
  19959. tempNode.parentId = n.data('parent');
  19960. tempNode.cmptId = id2cmptId[n.id()];
  19961. tempNode.children = [];
  19962. tempNode.positionX = n.position('x');
  19963. tempNode.positionY = n.position('y');
  19964. tempNode.offsetX = 0;
  19965. tempNode.offsetY = 0;
  19966. tempNode.height = nbb.w;
  19967. tempNode.width = nbb.h;
  19968. tempNode.maxX = tempNode.positionX + tempNode.width / 2;
  19969. tempNode.minX = tempNode.positionX - tempNode.width / 2;
  19970. tempNode.maxY = tempNode.positionY + tempNode.height / 2;
  19971. tempNode.minY = tempNode.positionY - tempNode.height / 2;
  19972. tempNode.padLeft = parseFloat(n.style('padding'));
  19973. tempNode.padRight = parseFloat(n.style('padding'));
  19974. tempNode.padTop = parseFloat(n.style('padding'));
  19975. tempNode.padBottom = parseFloat(n.style('padding'));
  19976. // forces
  19977. tempNode.nodeRepulsion = fn$6(options.nodeRepulsion) ? options.nodeRepulsion(n) : options.nodeRepulsion;
  19978. // Add new node
  19979. layoutInfo.layoutNodes.push(tempNode);
  19980. // Add entry to id-index map
  19981. layoutInfo.idToIndex[tempNode.id] = i;
  19982. }
  19983. // Inline implementation of a queue, used for traversing the graph in BFS order
  19984. var queue = [];
  19985. var start = 0; // Points to the start the queue
  19986. var end = -1; // Points to the end of the queue
  19987. var tempGraph = [];
  19988. // Second pass to add child information and
  19989. // initialize queue for hierarchical traversal
  19990. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  19991. var n = layoutInfo.layoutNodes[i];
  19992. var p_id = n.parentId;
  19993. // Check if node n has a parent node
  19994. if (null != p_id) {
  19995. // Add node Id to parent's list of children
  19996. layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);
  19997. } else {
  19998. // If a node doesn't have a parent, then it's in the root graph
  19999. queue[++end] = n.id;
  20000. tempGraph.push(n.id);
  20001. }
  20002. }
  20003. // Add root graph to graphSet
  20004. layoutInfo.graphSet.push(tempGraph);
  20005. // Traverse the graph, level by level,
  20006. while (start <= end) {
  20007. // Get the node to visit and remove it from queue
  20008. var node_id = queue[start++];
  20009. var node_ix = layoutInfo.idToIndex[node_id];
  20010. var node = layoutInfo.layoutNodes[node_ix];
  20011. var children = node.children;
  20012. if (children.length > 0) {
  20013. // Add children nodes as a new graph to graph set
  20014. layoutInfo.graphSet.push(children);
  20015. // Add children to que queue to be visited
  20016. for (var i = 0; i < children.length; i++) {
  20017. queue[++end] = children[i];
  20018. }
  20019. }
  20020. }
  20021. // Create indexToGraph map
  20022. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20023. var graph = layoutInfo.graphSet[i];
  20024. for (var j = 0; j < graph.length; j++) {
  20025. var index = layoutInfo.idToIndex[graph[j]];
  20026. layoutInfo.indexToGraph[index] = i;
  20027. }
  20028. }
  20029. // Iterate over all edges, creating Layout Edges
  20030. for (var i = 0; i < layoutInfo.edgeSize; i++) {
  20031. var e = edges[i];
  20032. var tempEdge = {};
  20033. tempEdge.id = e.data('id');
  20034. tempEdge.sourceId = e.data('source');
  20035. tempEdge.targetId = e.data('target');
  20036. // Compute ideal length
  20037. var idealLength = fn$6(options.idealEdgeLength) ? options.idealEdgeLength(e) : options.idealEdgeLength;
  20038. var elasticity = fn$6(options.edgeElasticity) ? options.edgeElasticity(e) : options.edgeElasticity;
  20039. // Check if it's an inter graph edge
  20040. var sourceIx = layoutInfo.idToIndex[tempEdge.sourceId];
  20041. var targetIx = layoutInfo.idToIndex[tempEdge.targetId];
  20042. var sourceGraph = layoutInfo.indexToGraph[sourceIx];
  20043. var targetGraph = layoutInfo.indexToGraph[targetIx];
  20044. if (sourceGraph != targetGraph) {
  20045. // Find lowest common graph ancestor
  20046. var lca = findLCA(tempEdge.sourceId, tempEdge.targetId, layoutInfo);
  20047. // Compute sum of node depths, relative to lca graph
  20048. var lcaGraph = layoutInfo.graphSet[lca];
  20049. var depth = 0;
  20050. // Source depth
  20051. var tempNode = layoutInfo.layoutNodes[sourceIx];
  20052. while (-1 === lcaGraph.indexOf(tempNode.id)) {
  20053. tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
  20054. depth++;
  20055. }
  20056. // Target depth
  20057. tempNode = layoutInfo.layoutNodes[targetIx];
  20058. while (-1 === lcaGraph.indexOf(tempNode.id)) {
  20059. tempNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[tempNode.parentId]];
  20060. depth++;
  20061. }
  20062. // logDebug('LCA of nodes ' + tempEdge.sourceId + ' and ' + tempEdge.targetId +
  20063. // ". Index: " + lca + " Contents: " + lcaGraph.toString() +
  20064. // ". Depth: " + depth);
  20065. // Update idealLength
  20066. idealLength *= depth * options.nestingFactor;
  20067. }
  20068. tempEdge.idealLength = idealLength;
  20069. tempEdge.elasticity = elasticity;
  20070. layoutInfo.layoutEdges.push(tempEdge);
  20071. }
  20072. // Finally, return layoutInfo object
  20073. return layoutInfo;
  20074. };
  20075. /**
  20076. * @brief : This function finds the index of the lowest common
  20077. * graph ancestor between 2 nodes in the subtree
  20078. * (from the graph hierarchy induced tree) whose
  20079. * root is graphIx
  20080. *
  20081. * @arg node1: node1's ID
  20082. * @arg node2: node2's ID
  20083. * @arg layoutInfo: layoutInfo object
  20084. *
  20085. */
  20086. var findLCA = function findLCA(node1, node2, layoutInfo) {
  20087. // Find their common ancester, starting from the root graph
  20088. var res = _findLCA_aux(node1, node2, 0, layoutInfo);
  20089. if (2 > res.count) {
  20090. // If aux function couldn't find the common ancester,
  20091. // then it is the root graph
  20092. return 0;
  20093. } else {
  20094. return res.graph;
  20095. }
  20096. };
  20097. /**
  20098. * @brief : Auxiliary function used for LCA computation
  20099. *
  20100. * @arg node1 : node1's ID
  20101. * @arg node2 : node2's ID
  20102. * @arg graphIx : subgraph index
  20103. * @arg layoutInfo : layoutInfo object
  20104. *
  20105. * @return : object of the form {count: X, graph: Y}, where:
  20106. * X is the number of ancestors (max: 2) found in
  20107. * graphIx (and it's subgraphs),
  20108. * Y is the graph index of the lowest graph containing
  20109. * all X nodes
  20110. */
  20111. var _findLCA_aux = function findLCA_aux(node1, node2, graphIx, layoutInfo) {
  20112. var graph = layoutInfo.graphSet[graphIx];
  20113. // If both nodes belongs to graphIx
  20114. if (-1 < graph.indexOf(node1) && -1 < graph.indexOf(node2)) {
  20115. return {
  20116. count: 2,
  20117. graph: graphIx
  20118. };
  20119. }
  20120. // Make recursive calls for all subgraphs
  20121. var c = 0;
  20122. for (var i = 0; i < graph.length; i++) {
  20123. var nodeId = graph[i];
  20124. var nodeIx = layoutInfo.idToIndex[nodeId];
  20125. var children = layoutInfo.layoutNodes[nodeIx].children;
  20126. // If the node has no child, skip it
  20127. if (0 === children.length) {
  20128. continue;
  20129. }
  20130. var childGraphIx = layoutInfo.indexToGraph[layoutInfo.idToIndex[children[0]]];
  20131. var result = _findLCA_aux(node1, node2, childGraphIx, layoutInfo);
  20132. if (0 === result.count) {
  20133. // Neither node1 nor node2 are present in this subgraph
  20134. continue;
  20135. } else if (1 === result.count) {
  20136. // One of (node1, node2) is present in this subgraph
  20137. c++;
  20138. if (2 === c) {
  20139. // We've already found both nodes, no need to keep searching
  20140. break;
  20141. }
  20142. } else {
  20143. // Both nodes are present in this subgraph
  20144. return result;
  20145. }
  20146. }
  20147. return {
  20148. count: c,
  20149. graph: graphIx
  20150. };
  20151. };
  20152. /**
  20153. * @brief: printsLayoutInfo into js console
  20154. * Only used for debbuging
  20155. */
  20156. var printLayoutInfo;
  20157. /**
  20158. * @brief : Randomizes the position of all nodes
  20159. */
  20160. var randomizePositions = function randomizePositions(layoutInfo, cy) {
  20161. var width = layoutInfo.clientWidth;
  20162. var height = layoutInfo.clientHeight;
  20163. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20164. var n = layoutInfo.layoutNodes[i];
  20165. // No need to randomize compound nodes or locked nodes
  20166. if (0 === n.children.length && !n.isLocked) {
  20167. n.positionX = Math.random() * width;
  20168. n.positionY = Math.random() * height;
  20169. }
  20170. }
  20171. };
  20172. var getScaleInBoundsFn = function getScaleInBoundsFn(layoutInfo, options, nodes) {
  20173. var bb = layoutInfo.boundingBox;
  20174. var coseBB = {
  20175. x1: Infinity,
  20176. x2: -Infinity,
  20177. y1: Infinity,
  20178. y2: -Infinity
  20179. };
  20180. if (options.boundingBox) {
  20181. nodes.forEach(function (node) {
  20182. var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[node.data('id')]];
  20183. coseBB.x1 = Math.min(coseBB.x1, lnode.positionX);
  20184. coseBB.x2 = Math.max(coseBB.x2, lnode.positionX);
  20185. coseBB.y1 = Math.min(coseBB.y1, lnode.positionY);
  20186. coseBB.y2 = Math.max(coseBB.y2, lnode.positionY);
  20187. });
  20188. coseBB.w = coseBB.x2 - coseBB.x1;
  20189. coseBB.h = coseBB.y2 - coseBB.y1;
  20190. }
  20191. return function (ele, i) {
  20192. var lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];
  20193. if (options.boundingBox) {
  20194. // then add extra bounding box constraint
  20195. // Handle single node case where coseBB.w or coseBB.h is 0
  20196. var pctX = coseBB.w === 0 ? 0.5 : (lnode.positionX - coseBB.x1) / coseBB.w;
  20197. var pctY = coseBB.h === 0 ? 0.5 : (lnode.positionY - coseBB.y1) / coseBB.h;
  20198. return {
  20199. x: bb.x1 + pctX * bb.w,
  20200. y: bb.y1 + pctY * bb.h
  20201. };
  20202. } else {
  20203. return {
  20204. x: lnode.positionX,
  20205. y: lnode.positionY
  20206. };
  20207. }
  20208. };
  20209. };
  20210. /**
  20211. * @brief : Updates the positions of nodes in the network
  20212. * @arg layoutInfo : LayoutInfo object
  20213. * @arg cy : Cytoscape object
  20214. * @arg options : Layout options
  20215. */
  20216. var refreshPositions = function refreshPositions(layoutInfo, cy, options) {
  20217. // var s = 'Refreshing positions';
  20218. // logDebug(s);
  20219. var layout = options.layout;
  20220. var nodes = options.eles.nodes();
  20221. var getScaledPos = getScaleInBoundsFn(layoutInfo, options, nodes);
  20222. nodes.positions(getScaledPos);
  20223. // Trigger layoutReady only on first call
  20224. if (true !== layoutInfo.ready) {
  20225. // s = 'Triggering layoutready';
  20226. // logDebug(s);
  20227. layoutInfo.ready = true;
  20228. layout.one('layoutready', options.ready);
  20229. layout.emit({
  20230. type: 'layoutready',
  20231. layout: this
  20232. });
  20233. }
  20234. };
  20235. /**
  20236. * @brief : Logs a debug message in JS console, if DEBUG is ON
  20237. */
  20238. // var logDebug = function(text) {
  20239. // if (DEBUG) {
  20240. // console.debug(text);
  20241. // }
  20242. // };
  20243. /**
  20244. * @brief : Performs one iteration of the physical simulation
  20245. * @arg layoutInfo : LayoutInfo object already initialized
  20246. * @arg cy : Cytoscape object
  20247. * @arg options : Layout options
  20248. */
  20249. var step = function step(layoutInfo, options, _step) {
  20250. // var s = "\n\n###############################";
  20251. // s += "\nSTEP: " + step;
  20252. // s += "\n###############################\n";
  20253. // logDebug(s);
  20254. // Calculate node repulsions
  20255. calculateNodeForces(layoutInfo, options);
  20256. // Calculate edge forces
  20257. calculateEdgeForces(layoutInfo);
  20258. // Calculate gravity forces
  20259. calculateGravityForces(layoutInfo, options);
  20260. // Propagate forces from parent to child
  20261. propagateForces(layoutInfo);
  20262. // Update positions based on calculated forces
  20263. updatePositions(layoutInfo);
  20264. };
  20265. /**
  20266. * @brief : Computes the node repulsion forces
  20267. */
  20268. var calculateNodeForces = function calculateNodeForces(layoutInfo, options) {
  20269. // Go through each of the graphs in graphSet
  20270. // Nodes only repel each other if they belong to the same graph
  20271. // var s = 'calculateNodeForces';
  20272. // logDebug(s);
  20273. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20274. var graph = layoutInfo.graphSet[i];
  20275. var numNodes = graph.length;
  20276. // s = "Set: " + graph.toString();
  20277. // logDebug(s);
  20278. // Now get all the pairs of nodes
  20279. // Only get each pair once, (A, B) = (B, A)
  20280. for (var j = 0; j < numNodes; j++) {
  20281. var node1 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
  20282. for (var k = j + 1; k < numNodes; k++) {
  20283. var node2 = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[k]]];
  20284. nodeRepulsion(node1, node2, layoutInfo, options);
  20285. }
  20286. }
  20287. }
  20288. };
  20289. var randomDistance = function randomDistance(max) {
  20290. return -1 + 2 * max * Math.random();
  20291. };
  20292. /**
  20293. * @brief : Compute the node repulsion forces between a pair of nodes
  20294. */
  20295. var nodeRepulsion = function nodeRepulsion(node1, node2, layoutInfo, options) {
  20296. // var s = "Node repulsion. Node1: " + node1.id + " Node2: " + node2.id;
  20297. var cmptId1 = node1.cmptId;
  20298. var cmptId2 = node2.cmptId;
  20299. if (cmptId1 !== cmptId2 && !layoutInfo.isCompound) {
  20300. return;
  20301. }
  20302. // Get direction of line connecting both node centers
  20303. var directionX = node2.positionX - node1.positionX;
  20304. var directionY = node2.positionY - node1.positionY;
  20305. var maxRandDist = 1;
  20306. // s += "\ndirectionX: " + directionX + ", directionY: " + directionY;
  20307. // If both centers are the same, apply a random force
  20308. if (0 === directionX && 0 === directionY) {
  20309. directionX = randomDistance(maxRandDist);
  20310. directionY = randomDistance(maxRandDist);
  20311. }
  20312. var overlap = nodesOverlap(node1, node2, directionX, directionY);
  20313. if (overlap > 0) {
  20314. // s += "\nNodes DO overlap.";
  20315. // s += "\nOverlap: " + overlap;
  20316. // If nodes overlap, repulsion force is proportional
  20317. // to the overlap
  20318. var force = options.nodeOverlap * overlap;
  20319. // Compute the module and components of the force vector
  20320. var distance = Math.sqrt(directionX * directionX + directionY * directionY);
  20321. // s += "\nDistance: " + distance;
  20322. var forceX = force * directionX / distance;
  20323. var forceY = force * directionY / distance;
  20324. } else {
  20325. // s += "\nNodes do NOT overlap.";
  20326. // If there's no overlap, force is inversely proportional
  20327. // to squared distance
  20328. // Get clipping points for both nodes
  20329. var point1 = findClippingPoint(node1, directionX, directionY);
  20330. var point2 = findClippingPoint(node2, -1 * directionX, -1 * directionY);
  20331. // Use clipping points to compute distance
  20332. var distanceX = point2.x - point1.x;
  20333. var distanceY = point2.y - point1.y;
  20334. var distanceSqr = distanceX * distanceX + distanceY * distanceY;
  20335. var distance = Math.sqrt(distanceSqr);
  20336. // s += "\nDistance: " + distance;
  20337. // Compute the module and components of the force vector
  20338. var force = (node1.nodeRepulsion + node2.nodeRepulsion) / distanceSqr;
  20339. var forceX = force * distanceX / distance;
  20340. var forceY = force * distanceY / distance;
  20341. }
  20342. // Apply force
  20343. if (!node1.isLocked) {
  20344. node1.offsetX -= forceX;
  20345. node1.offsetY -= forceY;
  20346. }
  20347. if (!node2.isLocked) {
  20348. node2.offsetX += forceX;
  20349. node2.offsetY += forceY;
  20350. }
  20351. // s += "\nForceX: " + forceX + " ForceY: " + forceY;
  20352. // logDebug(s);
  20353. return;
  20354. };
  20355. /**
  20356. * @brief : Determines whether two nodes overlap or not
  20357. * @return : Amount of overlapping (0 => no overlap)
  20358. */
  20359. var nodesOverlap = function nodesOverlap(node1, node2, dX, dY) {
  20360. if (dX > 0) {
  20361. var overlapX = node1.maxX - node2.minX;
  20362. } else {
  20363. var overlapX = node2.maxX - node1.minX;
  20364. }
  20365. if (dY > 0) {
  20366. var overlapY = node1.maxY - node2.minY;
  20367. } else {
  20368. var overlapY = node2.maxY - node1.minY;
  20369. }
  20370. if (overlapX >= 0 && overlapY >= 0) {
  20371. return Math.sqrt(overlapX * overlapX + overlapY * overlapY);
  20372. } else {
  20373. return 0;
  20374. }
  20375. };
  20376. /**
  20377. * @brief : Finds the point in which an edge (direction dX, dY) intersects
  20378. * the rectangular bounding box of it's source/target node
  20379. */
  20380. var findClippingPoint = function findClippingPoint(node, dX, dY) {
  20381. // Shorcuts
  20382. var X = node.positionX;
  20383. var Y = node.positionY;
  20384. var H = node.height || 1;
  20385. var W = node.width || 1;
  20386. var dirSlope = dY / dX;
  20387. var nodeSlope = H / W;
  20388. // var s = 'Computing clipping point of node ' + node.id +
  20389. // " . Height: " + H + ", Width: " + W +
  20390. // "\nDirection " + dX + ", " + dY;
  20391. //
  20392. // Compute intersection
  20393. var res = {};
  20394. // Case: Vertical direction (up)
  20395. if (0 === dX && 0 < dY) {
  20396. res.x = X;
  20397. // s += "\nUp direction";
  20398. res.y = Y + H / 2;
  20399. return res;
  20400. }
  20401. // Case: Vertical direction (down)
  20402. if (0 === dX && 0 > dY) {
  20403. res.x = X;
  20404. res.y = Y + H / 2;
  20405. // s += "\nDown direction";
  20406. return res;
  20407. }
  20408. // Case: Intersects the right border
  20409. if (0 < dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
  20410. res.x = X + W / 2;
  20411. res.y = Y + W * dY / 2 / dX;
  20412. // s += "\nRightborder";
  20413. return res;
  20414. }
  20415. // Case: Intersects the left border
  20416. if (0 > dX && -1 * nodeSlope <= dirSlope && dirSlope <= nodeSlope) {
  20417. res.x = X - W / 2;
  20418. res.y = Y - W * dY / 2 / dX;
  20419. // s += "\nLeftborder";
  20420. return res;
  20421. }
  20422. // Case: Intersects the top border
  20423. if (0 < dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
  20424. res.x = X + H * dX / 2 / dY;
  20425. res.y = Y + H / 2;
  20426. // s += "\nTop border";
  20427. return res;
  20428. }
  20429. // Case: Intersects the bottom border
  20430. if (0 > dY && (dirSlope <= -1 * nodeSlope || dirSlope >= nodeSlope)) {
  20431. res.x = X - H * dX / 2 / dY;
  20432. res.y = Y - H / 2;
  20433. // s += "\nBottom border";
  20434. return res;
  20435. }
  20436. // s += "\nClipping point found at " + res.x + ", " + res.y;
  20437. // logDebug(s);
  20438. return res;
  20439. };
  20440. /**
  20441. * @brief : Calculates all edge forces
  20442. */
  20443. var calculateEdgeForces = function calculateEdgeForces(layoutInfo, options) {
  20444. // Iterate over all edges
  20445. for (var i = 0; i < layoutInfo.edgeSize; i++) {
  20446. // Get edge, source & target nodes
  20447. var edge = layoutInfo.layoutEdges[i];
  20448. var sourceIx = layoutInfo.idToIndex[edge.sourceId];
  20449. var source = layoutInfo.layoutNodes[sourceIx];
  20450. var targetIx = layoutInfo.idToIndex[edge.targetId];
  20451. var target = layoutInfo.layoutNodes[targetIx];
  20452. // Get direction of line connecting both node centers
  20453. var directionX = target.positionX - source.positionX;
  20454. var directionY = target.positionY - source.positionY;
  20455. // If both centers are the same, do nothing.
  20456. // A random force has already been applied as node repulsion
  20457. if (0 === directionX && 0 === directionY) {
  20458. continue;
  20459. }
  20460. // Get clipping points for both nodes
  20461. var point1 = findClippingPoint(source, directionX, directionY);
  20462. var point2 = findClippingPoint(target, -1 * directionX, -1 * directionY);
  20463. var lx = point2.x - point1.x;
  20464. var ly = point2.y - point1.y;
  20465. var l = Math.sqrt(lx * lx + ly * ly);
  20466. var force = Math.pow(edge.idealLength - l, 2) / edge.elasticity;
  20467. if (0 !== l) {
  20468. var forceX = force * lx / l;
  20469. var forceY = force * ly / l;
  20470. } else {
  20471. var forceX = 0;
  20472. var forceY = 0;
  20473. }
  20474. // Add this force to target and source nodes
  20475. if (!source.isLocked) {
  20476. source.offsetX += forceX;
  20477. source.offsetY += forceY;
  20478. }
  20479. if (!target.isLocked) {
  20480. target.offsetX -= forceX;
  20481. target.offsetY -= forceY;
  20482. }
  20483. // var s = 'Edge force between nodes ' + source.id + ' and ' + target.id;
  20484. // s += "\nDistance: " + l + " Force: (" + forceX + ", " + forceY + ")";
  20485. // logDebug(s);
  20486. }
  20487. };
  20488. /**
  20489. * @brief : Computes gravity forces for all nodes
  20490. */
  20491. var calculateGravityForces = function calculateGravityForces(layoutInfo, options) {
  20492. if (options.gravity === 0) {
  20493. return;
  20494. }
  20495. var distThreshold = 1;
  20496. // var s = 'calculateGravityForces';
  20497. // logDebug(s);
  20498. for (var i = 0; i < layoutInfo.graphSet.length; i++) {
  20499. var graph = layoutInfo.graphSet[i];
  20500. var numNodes = graph.length;
  20501. // s = "Set: " + graph.toString();
  20502. // logDebug(s);
  20503. // Compute graph center
  20504. if (0 === i) {
  20505. var centerX = layoutInfo.clientHeight / 2;
  20506. var centerY = layoutInfo.clientWidth / 2;
  20507. } else {
  20508. // Get Parent node for this graph, and use its position as center
  20509. var temp = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[0]]];
  20510. var parent = layoutInfo.layoutNodes[layoutInfo.idToIndex[temp.parentId]];
  20511. var centerX = parent.positionX;
  20512. var centerY = parent.positionY;
  20513. }
  20514. // s = "Center found at: " + centerX + ", " + centerY;
  20515. // logDebug(s);
  20516. // Apply force to all nodes in graph
  20517. for (var j = 0; j < numNodes; j++) {
  20518. var node = layoutInfo.layoutNodes[layoutInfo.idToIndex[graph[j]]];
  20519. // s = "Node: " + node.id;
  20520. if (node.isLocked) {
  20521. continue;
  20522. }
  20523. var dx = centerX - node.positionX;
  20524. var dy = centerY - node.positionY;
  20525. var d = Math.sqrt(dx * dx + dy * dy);
  20526. if (d > distThreshold) {
  20527. var fx = options.gravity * dx / d;
  20528. var fy = options.gravity * dy / d;
  20529. node.offsetX += fx;
  20530. node.offsetY += fy;
  20531. // s += ": Applied force: " + fx + ", " + fy;
  20532. }
  20533. // logDebug(s);
  20534. }
  20535. }
  20536. };
  20537. /**
  20538. * @brief : This function propagates the existing offsets from
  20539. * parent nodes to its descendents.
  20540. * @arg layoutInfo : layoutInfo Object
  20541. * @arg cy : cytoscape Object
  20542. * @arg options : Layout options
  20543. */
  20544. var propagateForces = function propagateForces(layoutInfo, options) {
  20545. // Inline implementation of a queue, used for traversing the graph in BFS order
  20546. var queue = [];
  20547. var start = 0; // Points to the start the queue
  20548. var end = -1; // Points to the end of the queue
  20549. // logDebug('propagateForces');
  20550. // Start by visiting the nodes in the root graph
  20551. queue.push.apply(queue, layoutInfo.graphSet[0]);
  20552. end += layoutInfo.graphSet[0].length;
  20553. // Traverse the graph, level by level,
  20554. while (start <= end) {
  20555. // Get the node to visit and remove it from queue
  20556. var nodeId = queue[start++];
  20557. var nodeIndex = layoutInfo.idToIndex[nodeId];
  20558. var node = layoutInfo.layoutNodes[nodeIndex];
  20559. var children = node.children;
  20560. // We only need to process the node if it's compound
  20561. if (0 < children.length && !node.isLocked) {
  20562. var offX = node.offsetX;
  20563. var offY = node.offsetY;
  20564. // var s = "Propagating offset from parent node : " + node.id +
  20565. // ". OffsetX: " + offX + ". OffsetY: " + offY;
  20566. // s += "\n Children: " + children.toString();
  20567. // logDebug(s);
  20568. for (var i = 0; i < children.length; i++) {
  20569. var childNode = layoutInfo.layoutNodes[layoutInfo.idToIndex[children[i]]];
  20570. // Propagate offset
  20571. childNode.offsetX += offX;
  20572. childNode.offsetY += offY;
  20573. // Add children to queue to be visited
  20574. queue[++end] = children[i];
  20575. }
  20576. // Reset parent offsets
  20577. node.offsetX = 0;
  20578. node.offsetY = 0;
  20579. }
  20580. }
  20581. };
  20582. /**
  20583. * @brief : Updates the layout model positions, based on
  20584. * the accumulated forces
  20585. */
  20586. var updatePositions = function updatePositions(layoutInfo, options) {
  20587. // var s = 'Updating positions';
  20588. // logDebug(s);
  20589. // Reset boundaries for compound nodes
  20590. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20591. var n = layoutInfo.layoutNodes[i];
  20592. if (0 < n.children.length) {
  20593. // logDebug("Resetting boundaries of compound node: " + n.id);
  20594. n.maxX = undefined;
  20595. n.minX = undefined;
  20596. n.maxY = undefined;
  20597. n.minY = undefined;
  20598. }
  20599. }
  20600. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20601. var n = layoutInfo.layoutNodes[i];
  20602. if (0 < n.children.length || n.isLocked) {
  20603. // No need to set compound or locked node position
  20604. // logDebug("Skipping position update of node: " + n.id);
  20605. continue;
  20606. }
  20607. // s = "Node: " + n.id + " Previous position: (" +
  20608. // n.positionX + ", " + n.positionY + ").";
  20609. // Limit displacement in order to improve stability
  20610. var tempForce = limitForce(n.offsetX, n.offsetY, layoutInfo.temperature);
  20611. n.positionX += tempForce.x;
  20612. n.positionY += tempForce.y;
  20613. n.offsetX = 0;
  20614. n.offsetY = 0;
  20615. n.minX = n.positionX - n.width;
  20616. n.maxX = n.positionX + n.width;
  20617. n.minY = n.positionY - n.height;
  20618. n.maxY = n.positionY + n.height;
  20619. // s += " New Position: (" + n.positionX + ", " + n.positionY + ").";
  20620. // logDebug(s);
  20621. // Update ancestry boudaries
  20622. _updateAncestryBoundaries(n, layoutInfo);
  20623. }
  20624. // Update size, position of compund nodes
  20625. for (var i = 0; i < layoutInfo.nodeSize; i++) {
  20626. var n = layoutInfo.layoutNodes[i];
  20627. if (0 < n.children.length && !n.isLocked) {
  20628. n.positionX = (n.maxX + n.minX) / 2;
  20629. n.positionY = (n.maxY + n.minY) / 2;
  20630. n.width = n.maxX - n.minX;
  20631. n.height = n.maxY - n.minY;
  20632. // s = "Updating position, size of compound node " + n.id;
  20633. // s += "\nPositionX: " + n.positionX + ", PositionY: " + n.positionY;
  20634. // s += "\nWidth: " + n.width + ", Height: " + n.height;
  20635. // logDebug(s);
  20636. }
  20637. }
  20638. };
  20639. /**
  20640. * @brief : Limits a force (forceX, forceY) to be not
  20641. * greater (in modulo) than max.
  20642. 8 Preserves force direction.
  20643. */
  20644. var limitForce = function limitForce(forceX, forceY, max) {
  20645. // var s = "Limiting force: (" + forceX + ", " + forceY + "). Max: " + max;
  20646. var force = Math.sqrt(forceX * forceX + forceY * forceY);
  20647. if (force > max) {
  20648. var res = {
  20649. x: max * forceX / force,
  20650. y: max * forceY / force
  20651. };
  20652. } else {
  20653. var res = {
  20654. x: forceX,
  20655. y: forceY
  20656. };
  20657. }
  20658. // s += ".\nResult: (" + res.x + ", " + res.y + ")";
  20659. // logDebug(s);
  20660. return res;
  20661. };
  20662. /**
  20663. * @brief : Function used for keeping track of compound node
  20664. * sizes, since they should bound all their subnodes.
  20665. */
  20666. var _updateAncestryBoundaries = function updateAncestryBoundaries(node, layoutInfo) {
  20667. // var s = "Propagating new position/size of node " + node.id;
  20668. var parentId = node.parentId;
  20669. if (null == parentId) {
  20670. // If there's no parent, we are done
  20671. // s += ". No parent node.";
  20672. // logDebug(s);
  20673. return;
  20674. }
  20675. // Get Parent Node
  20676. var p = layoutInfo.layoutNodes[layoutInfo.idToIndex[parentId]];
  20677. var flag = false;
  20678. // MaxX
  20679. if (null == p.maxX || node.maxX + p.padRight > p.maxX) {
  20680. p.maxX = node.maxX + p.padRight;
  20681. flag = true;
  20682. // s += "\nNew maxX for parent node " + p.id + ": " + p.maxX;
  20683. }
  20684. // MinX
  20685. if (null == p.minX || node.minX - p.padLeft < p.minX) {
  20686. p.minX = node.minX - p.padLeft;
  20687. flag = true;
  20688. // s += "\nNew minX for parent node " + p.id + ": " + p.minX;
  20689. }
  20690. // MaxY
  20691. if (null == p.maxY || node.maxY + p.padBottom > p.maxY) {
  20692. p.maxY = node.maxY + p.padBottom;
  20693. flag = true;
  20694. // s += "\nNew maxY for parent node " + p.id + ": " + p.maxY;
  20695. }
  20696. // MinY
  20697. if (null == p.minY || node.minY - p.padTop < p.minY) {
  20698. p.minY = node.minY - p.padTop;
  20699. flag = true;
  20700. // s += "\nNew minY for parent node " + p.id + ": " + p.minY;
  20701. }
  20702. // If updated boundaries, propagate changes upward
  20703. if (flag) {
  20704. // logDebug(s);
  20705. return _updateAncestryBoundaries(p, layoutInfo);
  20706. }
  20707. // s += ". No changes in boundaries/position of parent node " + p.id;
  20708. // logDebug(s);
  20709. return;
  20710. };
  20711. var separateComponents = function separateComponents(layoutInfo, options) {
  20712. var nodes = layoutInfo.layoutNodes;
  20713. var components = [];
  20714. for (var i = 0; i < nodes.length; i++) {
  20715. var node = nodes[i];
  20716. var cid = node.cmptId;
  20717. var component = components[cid] = components[cid] || [];
  20718. component.push(node);
  20719. }
  20720. var totalA = 0;
  20721. for (var i = 0; i < components.length; i++) {
  20722. var c = components[i];
  20723. if (!c) {
  20724. continue;
  20725. }
  20726. c.x1 = Infinity;
  20727. c.x2 = -Infinity;
  20728. c.y1 = Infinity;
  20729. c.y2 = -Infinity;
  20730. for (var j = 0; j < c.length; j++) {
  20731. var n = c[j];
  20732. c.x1 = Math.min(c.x1, n.positionX - n.width / 2);
  20733. c.x2 = Math.max(c.x2, n.positionX + n.width / 2);
  20734. c.y1 = Math.min(c.y1, n.positionY - n.height / 2);
  20735. c.y2 = Math.max(c.y2, n.positionY + n.height / 2);
  20736. }
  20737. c.w = c.x2 - c.x1;
  20738. c.h = c.y2 - c.y1;
  20739. totalA += c.w * c.h;
  20740. }
  20741. components.sort(function (c1, c2) {
  20742. return c2.w * c2.h - c1.w * c1.h;
  20743. });
  20744. var x = 0;
  20745. var y = 0;
  20746. var usedW = 0;
  20747. var rowH = 0;
  20748. var maxRowW = Math.sqrt(totalA) * layoutInfo.clientWidth / layoutInfo.clientHeight;
  20749. for (var i = 0; i < components.length; i++) {
  20750. var c = components[i];
  20751. if (!c) {
  20752. continue;
  20753. }
  20754. for (var j = 0; j < c.length; j++) {
  20755. var n = c[j];
  20756. if (!n.isLocked) {
  20757. n.positionX += x - c.x1;
  20758. n.positionY += y - c.y1;
  20759. }
  20760. }
  20761. x += c.w + options.componentSpacing;
  20762. usedW += c.w + options.componentSpacing;
  20763. rowH = Math.max(rowH, c.h);
  20764. if (usedW > maxRowW) {
  20765. y += rowH + options.componentSpacing;
  20766. x = 0;
  20767. usedW = 0;
  20768. rowH = 0;
  20769. }
  20770. }
  20771. };
  20772. var defaults$3 = {
  20773. fit: true,
  20774. // whether to fit the viewport to the graph
  20775. padding: 30,
  20776. // padding used on fit
  20777. boundingBox: undefined,
  20778. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  20779. avoidOverlap: true,
  20780. // prevents node overlap, may overflow boundingBox if not enough space
  20781. avoidOverlapPadding: 10,
  20782. // extra spacing around nodes when avoidOverlap: true
  20783. nodeDimensionsIncludeLabels: false,
  20784. // Excludes the label when calculating node bounding boxes for the layout algorithm
  20785. spacingFactor: undefined,
  20786. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  20787. condense: false,
  20788. // uses all available space on false, uses minimal space on true
  20789. rows: undefined,
  20790. // force num of rows in the grid
  20791. cols: undefined,
  20792. // force num of columns in the grid
  20793. position: function position(node) {},
  20794. // returns { row, col } for element
  20795. sort: undefined,
  20796. // a sorting function to order the nodes; e.g. function(a, b){ return a.data('weight') - b.data('weight') }
  20797. animate: false,
  20798. // whether to transition the node positions
  20799. animationDuration: 500,
  20800. // duration of animation in ms if enabled
  20801. animationEasing: undefined,
  20802. // easing of animation if enabled
  20803. animateFilter: function animateFilter(node, i) {
  20804. return true;
  20805. },
  20806. // 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
  20807. ready: undefined,
  20808. // callback on layoutready
  20809. stop: undefined,
  20810. // callback on layoutstop
  20811. transform: function transform(node, position) {
  20812. return position;
  20813. } // transform a given node position. Useful for changing flow direction in discrete layouts
  20814. };
  20815. function GridLayout(options) {
  20816. this.options = extend({}, defaults$3, options);
  20817. }
  20818. GridLayout.prototype.run = function () {
  20819. var params = this.options;
  20820. var options = params;
  20821. var cy = params.cy;
  20822. var eles = options.eles;
  20823. var nodes = eles.nodes().not(':parent');
  20824. if (options.sort) {
  20825. nodes = nodes.sort(options.sort);
  20826. }
  20827. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  20828. x1: 0,
  20829. y1: 0,
  20830. w: cy.width(),
  20831. h: cy.height()
  20832. });
  20833. if (bb.h === 0 || bb.w === 0) {
  20834. eles.nodes().layoutPositions(this, options, function (ele) {
  20835. return {
  20836. x: bb.x1,
  20837. y: bb.y1
  20838. };
  20839. });
  20840. } else {
  20841. // width/height * splits^2 = cells where splits is number of times to split width
  20842. var cells = nodes.size();
  20843. var splits = Math.sqrt(cells * bb.h / bb.w);
  20844. var rows = Math.round(splits);
  20845. var cols = Math.round(bb.w / bb.h * splits);
  20846. var small = function small(val) {
  20847. if (val == null) {
  20848. return Math.min(rows, cols);
  20849. } else {
  20850. var min = Math.min(rows, cols);
  20851. if (min == rows) {
  20852. rows = val;
  20853. } else {
  20854. cols = val;
  20855. }
  20856. }
  20857. };
  20858. var large = function large(val) {
  20859. if (val == null) {
  20860. return Math.max(rows, cols);
  20861. } else {
  20862. var max = Math.max(rows, cols);
  20863. if (max == rows) {
  20864. rows = val;
  20865. } else {
  20866. cols = val;
  20867. }
  20868. }
  20869. };
  20870. var oRows = options.rows;
  20871. var oCols = options.cols != null ? options.cols : options.columns;
  20872. // if rows or columns were set in options, use those values
  20873. if (oRows != null && oCols != null) {
  20874. rows = oRows;
  20875. cols = oCols;
  20876. } else if (oRows != null && oCols == null) {
  20877. rows = oRows;
  20878. cols = Math.ceil(cells / rows);
  20879. } else if (oRows == null && oCols != null) {
  20880. cols = oCols;
  20881. rows = Math.ceil(cells / cols);
  20882. }
  20883. // otherwise use the automatic values and adjust accordingly
  20884. // if rounding was up, see if we can reduce rows or columns
  20885. else if (cols * rows > cells) {
  20886. var sm = small();
  20887. var lg = large();
  20888. // reducing the small side takes away the most cells, so try it first
  20889. if ((sm - 1) * lg >= cells) {
  20890. small(sm - 1);
  20891. } else if ((lg - 1) * sm >= cells) {
  20892. large(lg - 1);
  20893. }
  20894. } else {
  20895. // if rounding was too low, add rows or columns
  20896. while (cols * rows < cells) {
  20897. var _sm = small();
  20898. var _lg = large();
  20899. // try to add to larger side first (adds less in multiplication)
  20900. if ((_lg + 1) * _sm >= cells) {
  20901. large(_lg + 1);
  20902. } else {
  20903. small(_sm + 1);
  20904. }
  20905. }
  20906. }
  20907. var cellWidth = bb.w / cols;
  20908. var cellHeight = bb.h / rows;
  20909. if (options.condense) {
  20910. cellWidth = 0;
  20911. cellHeight = 0;
  20912. }
  20913. if (options.avoidOverlap) {
  20914. for (var i = 0; i < nodes.length; i++) {
  20915. var node = nodes[i];
  20916. var pos = node._private.position;
  20917. if (pos.x == null || pos.y == null) {
  20918. // for bb
  20919. pos.x = 0;
  20920. pos.y = 0;
  20921. }
  20922. var nbb = node.layoutDimensions(options);
  20923. var p = options.avoidOverlapPadding;
  20924. var w = nbb.w + p;
  20925. var h = nbb.h + p;
  20926. cellWidth = Math.max(cellWidth, w);
  20927. cellHeight = Math.max(cellHeight, h);
  20928. }
  20929. }
  20930. var cellUsed = {}; // e.g. 'c-0-2' => true
  20931. var used = function used(row, col) {
  20932. return cellUsed['c-' + row + '-' + col] ? true : false;
  20933. };
  20934. var use = function use(row, col) {
  20935. cellUsed['c-' + row + '-' + col] = true;
  20936. };
  20937. // to keep track of current cell position
  20938. var row = 0;
  20939. var col = 0;
  20940. var moveToNextCell = function moveToNextCell() {
  20941. col++;
  20942. if (col >= cols) {
  20943. col = 0;
  20944. row++;
  20945. }
  20946. };
  20947. // get a cache of all the manual positions
  20948. var id2manPos = {};
  20949. for (var _i = 0; _i < nodes.length; _i++) {
  20950. var _node = nodes[_i];
  20951. var rcPos = options.position(_node);
  20952. if (rcPos && (rcPos.row !== undefined || rcPos.col !== undefined)) {
  20953. // must have at least row or col def'd
  20954. var _pos = {
  20955. row: rcPos.row,
  20956. col: rcPos.col
  20957. };
  20958. if (_pos.col === undefined) {
  20959. // find unused col
  20960. _pos.col = 0;
  20961. while (used(_pos.row, _pos.col)) {
  20962. _pos.col++;
  20963. }
  20964. } else if (_pos.row === undefined) {
  20965. // find unused row
  20966. _pos.row = 0;
  20967. while (used(_pos.row, _pos.col)) {
  20968. _pos.row++;
  20969. }
  20970. }
  20971. id2manPos[_node.id()] = _pos;
  20972. use(_pos.row, _pos.col);
  20973. }
  20974. }
  20975. var getPos = function getPos(element, i) {
  20976. var x, y;
  20977. if (element.locked() || element.isParent()) {
  20978. return false;
  20979. }
  20980. // see if we have a manual position set
  20981. var rcPos = id2manPos[element.id()];
  20982. if (rcPos) {
  20983. x = rcPos.col * cellWidth + cellWidth / 2 + bb.x1;
  20984. y = rcPos.row * cellHeight + cellHeight / 2 + bb.y1;
  20985. } else {
  20986. // otherwise set automatically
  20987. while (used(row, col)) {
  20988. moveToNextCell();
  20989. }
  20990. x = col * cellWidth + cellWidth / 2 + bb.x1;
  20991. y = row * cellHeight + cellHeight / 2 + bb.y1;
  20992. use(row, col);
  20993. moveToNextCell();
  20994. }
  20995. return {
  20996. x: x,
  20997. y: y
  20998. };
  20999. };
  21000. nodes.layoutPositions(this, options, getPos);
  21001. }
  21002. return this; // chaining
  21003. };
  21004. // default layout options
  21005. var defaults$2 = {
  21006. ready: function ready() {},
  21007. // on layoutready
  21008. stop: function stop() {} // on layoutstop
  21009. };
  21010. // constructor
  21011. // options : object containing layout options
  21012. function NullLayout(options) {
  21013. this.options = extend({}, defaults$2, options);
  21014. }
  21015. // runs the layout
  21016. NullLayout.prototype.run = function () {
  21017. var options = this.options;
  21018. var eles = options.eles; // elements to consider in the layout
  21019. var layout = this;
  21020. // cy is automatically populated for us in the constructor
  21021. // (disable eslint for next line as this serves as example layout code to external developers)
  21022. // eslint-disable-next-line no-unused-vars
  21023. options.cy;
  21024. layout.emit('layoutstart');
  21025. // puts all nodes at (0, 0)
  21026. // n.b. most layouts would use layoutPositions(), instead of positions() and manual events
  21027. eles.nodes().positions(function () {
  21028. return {
  21029. x: 0,
  21030. y: 0
  21031. };
  21032. });
  21033. // trigger layoutready when each node has had its position set at least once
  21034. layout.one('layoutready', options.ready);
  21035. layout.emit('layoutready');
  21036. // trigger layoutstop when the layout stops (e.g. finishes)
  21037. layout.one('layoutstop', options.stop);
  21038. layout.emit('layoutstop');
  21039. return this; // chaining
  21040. };
  21041. // called on continuous layouts to stop them before they finish
  21042. NullLayout.prototype.stop = function () {
  21043. return this; // chaining
  21044. };
  21045. var defaults$1 = {
  21046. positions: undefined,
  21047. // map of (node id) => (position obj); or function(node){ return somPos; }
  21048. zoom: undefined,
  21049. // the zoom level to set (prob want fit = false if set)
  21050. pan: undefined,
  21051. // the pan level to set (prob want fit = false if set)
  21052. fit: true,
  21053. // whether to fit to viewport
  21054. padding: 30,
  21055. // padding on fit
  21056. spacingFactor: undefined,
  21057. // Applies a multiplicative factor (>0) to expand or compress the overall area that the nodes take up
  21058. animate: false,
  21059. // whether to transition the node positions
  21060. animationDuration: 500,
  21061. // duration of animation in ms if enabled
  21062. animationEasing: undefined,
  21063. // easing of animation if enabled
  21064. animateFilter: function animateFilter(node, i) {
  21065. return true;
  21066. },
  21067. // 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
  21068. ready: undefined,
  21069. // callback on layoutready
  21070. stop: undefined,
  21071. // callback on layoutstop
  21072. transform: function transform(node, position) {
  21073. return position;
  21074. } // transform a given node position. Useful for changing flow direction in discrete layouts
  21075. };
  21076. function PresetLayout(options) {
  21077. this.options = extend({}, defaults$1, options);
  21078. }
  21079. PresetLayout.prototype.run = function () {
  21080. var options = this.options;
  21081. var eles = options.eles;
  21082. var nodes = eles.nodes();
  21083. var posIsFn = fn$6(options.positions);
  21084. function getPosition(node) {
  21085. if (options.positions == null) {
  21086. return copyPosition(node.position());
  21087. }
  21088. if (posIsFn) {
  21089. return options.positions(node);
  21090. }
  21091. var pos = options.positions[node._private.data.id];
  21092. if (pos == null) {
  21093. return null;
  21094. }
  21095. return pos;
  21096. }
  21097. nodes.layoutPositions(this, options, function (node, i) {
  21098. var position = getPosition(node);
  21099. if (node.locked() || position == null) {
  21100. return false;
  21101. }
  21102. return position;
  21103. });
  21104. return this; // chaining
  21105. };
  21106. var defaults = {
  21107. fit: true,
  21108. // whether to fit to viewport
  21109. padding: 30,
  21110. // fit padding
  21111. boundingBox: undefined,
  21112. // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
  21113. animate: false,
  21114. // whether to transition the node positions
  21115. animationDuration: 500,
  21116. // duration of animation in ms if enabled
  21117. animationEasing: undefined,
  21118. // easing of animation if enabled
  21119. animateFilter: function animateFilter(node, i) {
  21120. return true;
  21121. },
  21122. // 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
  21123. ready: undefined,
  21124. // callback on layoutready
  21125. stop: undefined,
  21126. // callback on layoutstop
  21127. transform: function transform(node, position) {
  21128. return position;
  21129. } // transform a given node position. Useful for changing flow direction in discrete layouts
  21130. };
  21131. function RandomLayout(options) {
  21132. this.options = extend({}, defaults, options);
  21133. }
  21134. RandomLayout.prototype.run = function () {
  21135. var options = this.options;
  21136. var cy = options.cy;
  21137. var eles = options.eles;
  21138. var bb = makeBoundingBox(options.boundingBox ? options.boundingBox : {
  21139. x1: 0,
  21140. y1: 0,
  21141. w: cy.width(),
  21142. h: cy.height()
  21143. });
  21144. var getPos = function getPos(node, i) {
  21145. return {
  21146. x: bb.x1 + Math.round(Math.random() * bb.w),
  21147. y: bb.y1 + Math.round(Math.random() * bb.h)
  21148. };
  21149. };
  21150. eles.nodes().layoutPositions(this, options, getPos);
  21151. return this; // chaining
  21152. };
  21153. var layout = [{
  21154. name: 'breadthfirst',
  21155. impl: BreadthFirstLayout
  21156. }, {
  21157. name: 'circle',
  21158. impl: CircleLayout
  21159. }, {
  21160. name: 'concentric',
  21161. impl: ConcentricLayout
  21162. }, {
  21163. name: 'cose',
  21164. impl: CoseLayout
  21165. }, {
  21166. name: 'grid',
  21167. impl: GridLayout
  21168. }, {
  21169. name: 'null',
  21170. impl: NullLayout
  21171. }, {
  21172. name: 'preset',
  21173. impl: PresetLayout
  21174. }, {
  21175. name: 'random',
  21176. impl: RandomLayout
  21177. }];
  21178. function NullRenderer(options) {
  21179. this.options = options;
  21180. this.notifications = 0; // for testing
  21181. }
  21182. var noop = function noop() {};
  21183. var throwImgErr = function throwImgErr() {
  21184. throw new Error('A headless instance can not render images');
  21185. };
  21186. NullRenderer.prototype = {
  21187. recalculateRenderedStyle: noop,
  21188. notify: function notify() {
  21189. this.notifications++;
  21190. },
  21191. init: noop,
  21192. isHeadless: function isHeadless() {
  21193. return true;
  21194. },
  21195. png: throwImgErr,
  21196. jpg: throwImgErr
  21197. };
  21198. var BRp$f = {};
  21199. BRp$f.arrowShapeWidth = 0.3;
  21200. BRp$f.registerArrowShapes = function () {
  21201. var arrowShapes = this.arrowShapes = {};
  21202. var renderer = this;
  21203. // Contract for arrow shapes:
  21204. // 0, 0 is arrow tip
  21205. // (0, 1) is direction towards node
  21206. // (1, 0) is right
  21207. //
  21208. // functional api:
  21209. // collide: check x, y in shape
  21210. // roughCollide: called before collide, no false negatives
  21211. // draw: draw
  21212. // spacing: dist(arrowTip, nodeBoundary)
  21213. // gap: dist(edgeTip, nodeBoundary), edgeTip may != arrowTip
  21214. var bbCollide = function bbCollide(x, y, size, angle, translation, edgeWidth, padding) {
  21215. var x1 = translation.x - size / 2 - padding;
  21216. var x2 = translation.x + size / 2 + padding;
  21217. var y1 = translation.y - size / 2 - padding;
  21218. var y2 = translation.y + size / 2 + padding;
  21219. var inside = x1 <= x && x <= x2 && y1 <= y && y <= y2;
  21220. return inside;
  21221. };
  21222. var transform = function transform(x, y, size, angle, translation) {
  21223. var xRotated = x * Math.cos(angle) - y * Math.sin(angle);
  21224. var yRotated = x * Math.sin(angle) + y * Math.cos(angle);
  21225. var xScaled = xRotated * size;
  21226. var yScaled = yRotated * size;
  21227. var xTranslated = xScaled + translation.x;
  21228. var yTranslated = yScaled + translation.y;
  21229. return {
  21230. x: xTranslated,
  21231. y: yTranslated
  21232. };
  21233. };
  21234. var transformPoints = function transformPoints(pts, size, angle, translation) {
  21235. var retPts = [];
  21236. for (var i = 0; i < pts.length; i += 2) {
  21237. var x = pts[i];
  21238. var y = pts[i + 1];
  21239. retPts.push(transform(x, y, size, angle, translation));
  21240. }
  21241. return retPts;
  21242. };
  21243. var pointsToArr = function pointsToArr(pts) {
  21244. var ret = [];
  21245. for (var i = 0; i < pts.length; i++) {
  21246. var p = pts[i];
  21247. ret.push(p.x, p.y);
  21248. }
  21249. return ret;
  21250. };
  21251. var standardGap = function standardGap(edge) {
  21252. return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').pfValue * 2;
  21253. };
  21254. var defineArrowShape = function defineArrowShape(name, defn) {
  21255. if (string(defn)) {
  21256. defn = arrowShapes[defn];
  21257. }
  21258. arrowShapes[name] = extend({
  21259. name: name,
  21260. points: [-0.15, -0.3, 0.15, -0.3, 0.15, 0.3, -0.15, 0.3],
  21261. collide: function collide(x, y, size, angle, translation, padding) {
  21262. var points = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21263. var inside = pointInsidePolygonPoints(x, y, points);
  21264. return inside;
  21265. },
  21266. roughCollide: bbCollide,
  21267. draw: function draw(context, size, angle, translation) {
  21268. var points = transformPoints(this.points, size, angle, translation);
  21269. renderer.arrowShapeImpl('polygon')(context, points);
  21270. },
  21271. spacing: function spacing(edge) {
  21272. return 0;
  21273. },
  21274. gap: standardGap
  21275. }, defn);
  21276. };
  21277. defineArrowShape('none', {
  21278. collide: falsify,
  21279. roughCollide: falsify,
  21280. draw: noop$1,
  21281. spacing: zeroify,
  21282. gap: zeroify
  21283. });
  21284. defineArrowShape('triangle', {
  21285. points: [-0.15, -0.3, 0, 0, 0.15, -0.3]
  21286. });
  21287. defineArrowShape('arrow', 'triangle');
  21288. defineArrowShape('triangle-backcurve', {
  21289. points: arrowShapes['triangle'].points,
  21290. controlPoint: [0, -0.15],
  21291. roughCollide: bbCollide,
  21292. draw: function draw(context, size, angle, translation, edgeWidth) {
  21293. var ptsTrans = transformPoints(this.points, size, angle, translation);
  21294. var ctrlPt = this.controlPoint;
  21295. var ctrlPtTrans = transform(ctrlPt[0], ctrlPt[1], size, angle, translation);
  21296. renderer.arrowShapeImpl(this.name)(context, ptsTrans, ctrlPtTrans);
  21297. },
  21298. gap: function gap(edge) {
  21299. return standardGap(edge) * 0.8;
  21300. }
  21301. });
  21302. defineArrowShape('triangle-tee', {
  21303. points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
  21304. pointsTee: [-0.15, -0.4, -0.15, -0.5, 0.15, -0.5, 0.15, -0.4],
  21305. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21306. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21307. var teePts = pointsToArr(transformPoints(this.pointsTee, size + 2 * padding, angle, translation));
  21308. var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
  21309. return inside;
  21310. },
  21311. draw: function draw(context, size, angle, translation, edgeWidth) {
  21312. var triPts = transformPoints(this.points, size, angle, translation);
  21313. var teePts = transformPoints(this.pointsTee, size, angle, translation);
  21314. renderer.arrowShapeImpl(this.name)(context, triPts, teePts);
  21315. }
  21316. });
  21317. defineArrowShape('circle-triangle', {
  21318. radius: 0.15,
  21319. pointsTr: [0, -0.15, 0.15, -0.45, -0.15, -0.45, 0, -0.15],
  21320. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21321. var t = translation;
  21322. var circleInside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
  21323. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21324. return pointInsidePolygonPoints(x, y, triPts) || circleInside;
  21325. },
  21326. draw: function draw(context, size, angle, translation, edgeWidth) {
  21327. var triPts = transformPoints(this.pointsTr, size, angle, translation);
  21328. renderer.arrowShapeImpl(this.name)(context, triPts, translation.x, translation.y, this.radius * size);
  21329. },
  21330. spacing: function spacing(edge) {
  21331. return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
  21332. }
  21333. });
  21334. defineArrowShape('triangle-cross', {
  21335. points: [0, 0, 0.15, -0.3, -0.15, -0.3, 0, 0],
  21336. baseCrossLinePts: [-0.15, -0.4,
  21337. // first half of the rectangle
  21338. -0.15, -0.4, 0.15, -0.4,
  21339. // second half of the rectangle
  21340. 0.15, -0.4],
  21341. crossLinePts: function crossLinePts(size, edgeWidth) {
  21342. // shift points so that the distance between the cross points matches edge width
  21343. var p = this.baseCrossLinePts.slice();
  21344. var shiftFactor = edgeWidth / size;
  21345. var y0 = 3;
  21346. var y1 = 5;
  21347. p[y0] = p[y0] - shiftFactor;
  21348. p[y1] = p[y1] - shiftFactor;
  21349. return p;
  21350. },
  21351. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21352. var triPts = pointsToArr(transformPoints(this.points, size + 2 * padding, angle, translation));
  21353. var teePts = pointsToArr(transformPoints(this.crossLinePts(size, edgeWidth), size + 2 * padding, angle, translation));
  21354. var inside = pointInsidePolygonPoints(x, y, triPts) || pointInsidePolygonPoints(x, y, teePts);
  21355. return inside;
  21356. },
  21357. draw: function draw(context, size, angle, translation, edgeWidth) {
  21358. var triPts = transformPoints(this.points, size, angle, translation);
  21359. var crossLinePts = transformPoints(this.crossLinePts(size, edgeWidth), size, angle, translation);
  21360. renderer.arrowShapeImpl(this.name)(context, triPts, crossLinePts);
  21361. }
  21362. });
  21363. defineArrowShape('vee', {
  21364. points: [-0.15, -0.3, 0, 0, 0.15, -0.3, 0, -0.15],
  21365. gap: function gap(edge) {
  21366. return standardGap(edge) * 0.525;
  21367. }
  21368. });
  21369. defineArrowShape('circle', {
  21370. radius: 0.15,
  21371. collide: function collide(x, y, size, angle, translation, edgeWidth, padding) {
  21372. var t = translation;
  21373. var inside = Math.pow(t.x - x, 2) + Math.pow(t.y - y, 2) <= Math.pow((size + 2 * padding) * this.radius, 2);
  21374. return inside;
  21375. },
  21376. draw: function draw(context, size, angle, translation, edgeWidth) {
  21377. renderer.arrowShapeImpl(this.name)(context, translation.x, translation.y, this.radius * size);
  21378. },
  21379. spacing: function spacing(edge) {
  21380. return renderer.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.radius;
  21381. }
  21382. });
  21383. defineArrowShape('tee', {
  21384. points: [-0.15, 0, -0.15, -0.1, 0.15, -0.1, 0.15, 0],
  21385. spacing: function spacing(edge) {
  21386. return 1;
  21387. },
  21388. gap: function gap(edge) {
  21389. return 1;
  21390. }
  21391. });
  21392. defineArrowShape('square', {
  21393. points: [-0.15, 0.00, 0.15, 0.00, 0.15, -0.3, -0.15, -0.3]
  21394. });
  21395. defineArrowShape('diamond', {
  21396. points: [-0.15, -0.15, 0, -0.3, 0.15, -0.15, 0, 0],
  21397. gap: function gap(edge) {
  21398. return edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
  21399. }
  21400. });
  21401. defineArrowShape('chevron', {
  21402. points: [0, 0, -0.15, -0.15, -0.1, -0.2, 0, -0.1, 0.1, -0.2, 0.15, -0.15],
  21403. gap: function gap(edge) {
  21404. return 0.95 * edge.pstyle('width').pfValue * edge.pstyle('arrow-scale').value;
  21405. }
  21406. });
  21407. };
  21408. var BRp$e = {};
  21409. // Project mouse
  21410. BRp$e.projectIntoViewport = function (clientX, clientY) {
  21411. var cy = this.cy;
  21412. var offsets = this.findContainerClientCoords();
  21413. var offsetLeft = offsets[0];
  21414. var offsetTop = offsets[1];
  21415. var scale = offsets[4];
  21416. var pan = cy.pan();
  21417. var zoom = cy.zoom();
  21418. var x = ((clientX - offsetLeft) / scale - pan.x) / zoom;
  21419. var y = ((clientY - offsetTop) / scale - pan.y) / zoom;
  21420. return [x, y];
  21421. };
  21422. BRp$e.findContainerClientCoords = function () {
  21423. if (this.containerBB) {
  21424. return this.containerBB;
  21425. }
  21426. var container = this.container;
  21427. var rect = container.getBoundingClientRect();
  21428. var style = this.cy.window().getComputedStyle(container);
  21429. var styleValue = function styleValue(name) {
  21430. return parseFloat(style.getPropertyValue(name));
  21431. };
  21432. var padding = {
  21433. left: styleValue('padding-left'),
  21434. right: styleValue('padding-right'),
  21435. top: styleValue('padding-top'),
  21436. bottom: styleValue('padding-bottom')
  21437. };
  21438. var border = {
  21439. left: styleValue('border-left-width'),
  21440. right: styleValue('border-right-width'),
  21441. top: styleValue('border-top-width'),
  21442. bottom: styleValue('border-bottom-width')
  21443. };
  21444. var clientWidth = container.clientWidth;
  21445. var clientHeight = container.clientHeight;
  21446. var paddingHor = padding.left + padding.right;
  21447. var paddingVer = padding.top + padding.bottom;
  21448. var borderHor = border.left + border.right;
  21449. var scale = rect.width / (clientWidth + borderHor);
  21450. var unscaledW = clientWidth - paddingHor;
  21451. var unscaledH = clientHeight - paddingVer;
  21452. var left = rect.left + padding.left + border.left;
  21453. var top = rect.top + padding.top + border.top;
  21454. return this.containerBB = [left, top, unscaledW, unscaledH, scale];
  21455. };
  21456. BRp$e.invalidateContainerClientCoordsCache = function () {
  21457. this.containerBB = null;
  21458. };
  21459. BRp$e.findNearestElement = function (x, y, interactiveElementsOnly, isTouch) {
  21460. return this.findNearestElements(x, y, interactiveElementsOnly, isTouch)[0];
  21461. };
  21462. BRp$e.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  21463. var self = this;
  21464. var r = this;
  21465. var eles = r.getCachedZSortedEles();
  21466. var near = []; // 1 node max, 1 edge max
  21467. var zoom = r.cy.zoom();
  21468. var hasCompounds = r.cy.hasCompoundNodes();
  21469. var edgeThreshold = (isTouch ? 24 : 8) / zoom;
  21470. var nodeThreshold = (isTouch ? 8 : 2) / zoom;
  21471. var labelThreshold = (isTouch ? 8 : 2) / zoom;
  21472. var minSqDist = Infinity;
  21473. var nearEdge;
  21474. var nearNode;
  21475. if (interactiveElementsOnly) {
  21476. eles = eles.interactive;
  21477. }
  21478. function addEle(ele, sqDist) {
  21479. if (ele.isNode()) {
  21480. if (nearNode) {
  21481. return; // can't replace node
  21482. } else {
  21483. nearNode = ele;
  21484. near.push(ele);
  21485. }
  21486. }
  21487. if (ele.isEdge() && (sqDist == null || sqDist < minSqDist)) {
  21488. if (nearEdge) {
  21489. // then replace existing edge
  21490. // can replace only if same z-index
  21491. 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) {
  21492. for (var i = 0; i < near.length; i++) {
  21493. if (near[i].isEdge()) {
  21494. near[i] = ele;
  21495. nearEdge = ele;
  21496. minSqDist = sqDist != null ? sqDist : minSqDist;
  21497. break;
  21498. }
  21499. }
  21500. }
  21501. } else {
  21502. near.push(ele);
  21503. nearEdge = ele;
  21504. minSqDist = sqDist != null ? sqDist : minSqDist;
  21505. }
  21506. }
  21507. }
  21508. function checkNode(node) {
  21509. var width = node.outerWidth() + 2 * nodeThreshold;
  21510. var height = node.outerHeight() + 2 * nodeThreshold;
  21511. var hw = width / 2;
  21512. var hh = height / 2;
  21513. var pos = node.position();
  21514. var cornerRadius = node.pstyle('corner-radius').value === 'auto' ? 'auto' : node.pstyle('corner-radius').pfValue;
  21515. var rs = node._private.rscratch;
  21516. if (pos.x - hw <= x && x <= pos.x + hw // bb check x
  21517. && pos.y - hh <= y && y <= pos.y + hh // bb check y
  21518. ) {
  21519. var shape = r.nodeShapes[self.getNodeShape(node)];
  21520. if (shape.checkPoint(x, y, 0, width, height, pos.x, pos.y, cornerRadius, rs)) {
  21521. addEle(node, 0);
  21522. return true;
  21523. }
  21524. }
  21525. }
  21526. function checkEdge(edge) {
  21527. var _p = edge._private;
  21528. var rs = _p.rscratch;
  21529. var styleWidth = edge.pstyle('width').pfValue;
  21530. var scale = edge.pstyle('arrow-scale').value;
  21531. var width = styleWidth / 2 + edgeThreshold; // more like a distance radius from centre
  21532. var widthSq = width * width;
  21533. var width2 = width * 2;
  21534. var src = _p.source;
  21535. var tgt = _p.target;
  21536. var sqDist;
  21537. if (rs.edgeType === 'segments' || rs.edgeType === 'straight' || rs.edgeType === 'haystack') {
  21538. var pts = rs.allpts;
  21539. for (var i = 0; i + 3 < pts.length; i += 2) {
  21540. 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]))) {
  21541. addEle(edge, sqDist);
  21542. return true;
  21543. }
  21544. }
  21545. } else if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
  21546. var pts = rs.allpts;
  21547. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  21548. 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]))) {
  21549. addEle(edge, sqDist);
  21550. return true;
  21551. }
  21552. }
  21553. }
  21554. // if we're close to the edge but didn't hit it, maybe we hit its arrows
  21555. var src = src || _p.source;
  21556. var tgt = tgt || _p.target;
  21557. var arSize = self.getArrowWidth(styleWidth, scale);
  21558. var arrows = [{
  21559. name: 'source',
  21560. x: rs.arrowStartX,
  21561. y: rs.arrowStartY,
  21562. angle: rs.srcArrowAngle
  21563. }, {
  21564. name: 'target',
  21565. x: rs.arrowEndX,
  21566. y: rs.arrowEndY,
  21567. angle: rs.tgtArrowAngle
  21568. }, {
  21569. name: 'mid-source',
  21570. x: rs.midX,
  21571. y: rs.midY,
  21572. angle: rs.midsrcArrowAngle
  21573. }, {
  21574. name: 'mid-target',
  21575. x: rs.midX,
  21576. y: rs.midY,
  21577. angle: rs.midtgtArrowAngle
  21578. }];
  21579. for (var i = 0; i < arrows.length; i++) {
  21580. var ar = arrows[i];
  21581. var shape = r.arrowShapes[edge.pstyle(ar.name + '-arrow-shape').value];
  21582. var edgeWidth = edge.pstyle('width').pfValue;
  21583. if (shape.roughCollide(x, y, arSize, ar.angle, {
  21584. x: ar.x,
  21585. y: ar.y
  21586. }, edgeWidth, edgeThreshold) && shape.collide(x, y, arSize, ar.angle, {
  21587. x: ar.x,
  21588. y: ar.y
  21589. }, edgeWidth, edgeThreshold)) {
  21590. addEle(edge);
  21591. return true;
  21592. }
  21593. }
  21594. // for compound graphs, hitting edge may actually want a connected node instead (b/c edge may have greater z-index precedence)
  21595. if (hasCompounds && near.length > 0) {
  21596. checkNode(src);
  21597. checkNode(tgt);
  21598. }
  21599. }
  21600. function preprop(obj, name, pre) {
  21601. return getPrefixedProperty(obj, name, pre);
  21602. }
  21603. function checkLabel(ele, prefix) {
  21604. var _p = ele._private;
  21605. var th = labelThreshold;
  21606. var prefixDash;
  21607. if (prefix) {
  21608. prefixDash = prefix + '-';
  21609. } else {
  21610. prefixDash = '';
  21611. }
  21612. ele.boundingBox();
  21613. var bb = _p.labelBounds[prefix || 'main'];
  21614. var text = ele.pstyle(prefixDash + 'label').value;
  21615. var eventsEnabled = ele.pstyle('text-events').strValue === 'yes';
  21616. if (!eventsEnabled || !text) {
  21617. return;
  21618. }
  21619. var lx = preprop(_p.rscratch, 'labelX', prefix);
  21620. var ly = preprop(_p.rscratch, 'labelY', prefix);
  21621. var theta = preprop(_p.rscratch, 'labelAngle', prefix);
  21622. var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  21623. var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  21624. var lx1 = bb.x1 - th - ox; // (-ox, -oy) as bb already includes margin
  21625. var lx2 = bb.x2 + th - ox; // and rotation is about (lx, ly)
  21626. var ly1 = bb.y1 - th - oy;
  21627. var ly2 = bb.y2 + th - oy;
  21628. if (theta) {
  21629. var cos = Math.cos(theta);
  21630. var sin = Math.sin(theta);
  21631. var rotate = function rotate(x, y) {
  21632. x = x - lx;
  21633. y = y - ly;
  21634. return {
  21635. x: x * cos - y * sin + lx,
  21636. y: x * sin + y * cos + ly
  21637. };
  21638. };
  21639. var px1y1 = rotate(lx1, ly1);
  21640. var px1y2 = rotate(lx1, ly2);
  21641. var px2y1 = rotate(lx2, ly1);
  21642. var px2y2 = rotate(lx2, ly2);
  21643. var points = [
  21644. // with the margin added after the rotation is applied
  21645. px1y1.x + ox, px1y1.y + oy, px2y1.x + ox, px2y1.y + oy, px2y2.x + ox, px2y2.y + oy, px1y2.x + ox, px1y2.y + oy];
  21646. if (pointInsidePolygonPoints(x, y, points)) {
  21647. addEle(ele);
  21648. return true;
  21649. }
  21650. } else {
  21651. // do a cheaper bb check
  21652. if (inBoundingBox(bb, x, y)) {
  21653. addEle(ele);
  21654. return true;
  21655. }
  21656. }
  21657. }
  21658. for (var i = eles.length - 1; i >= 0; i--) {
  21659. // reverse order for precedence
  21660. var ele = eles[i];
  21661. if (ele.isNode()) {
  21662. checkNode(ele) || checkLabel(ele);
  21663. } else {
  21664. // then edge
  21665. checkEdge(ele) || checkLabel(ele) || checkLabel(ele, 'source') || checkLabel(ele, 'target');
  21666. }
  21667. }
  21668. return near;
  21669. };
  21670. // 'Give me everything from this box'
  21671. BRp$e.getAllInBox = function (x1, y1, x2, y2) {
  21672. var eles = this.getCachedZSortedEles().interactive;
  21673. var zoom = this.cy.zoom();
  21674. var labelThreshold = 2 / zoom;
  21675. var box = [];
  21676. var x1c = Math.min(x1, x2);
  21677. var x2c = Math.max(x1, x2);
  21678. var y1c = Math.min(y1, y2);
  21679. var y2c = Math.max(y1, y2);
  21680. x1 = x1c;
  21681. x2 = x2c;
  21682. y1 = y1c;
  21683. y2 = y2c;
  21684. var boxBb = makeBoundingBox({
  21685. x1: x1,
  21686. y1: y1,
  21687. x2: x2,
  21688. y2: y2
  21689. });
  21690. var selectionBox = [{
  21691. x: boxBb.x1,
  21692. y: boxBb.y1
  21693. }, {
  21694. x: boxBb.x2,
  21695. y: boxBb.y1
  21696. }, {
  21697. x: boxBb.x2,
  21698. y: boxBb.y2
  21699. }, {
  21700. x: boxBb.x1,
  21701. y: boxBb.y2
  21702. }];
  21703. var boxEdges = [[selectionBox[0], selectionBox[1]], [selectionBox[1], selectionBox[2]], [selectionBox[2], selectionBox[3]], [selectionBox[3], selectionBox[0]]];
  21704. function preprop(obj, name, pre) {
  21705. return getPrefixedProperty(obj, name, pre);
  21706. }
  21707. function getRotatedLabelBox(ele, prefix) {
  21708. var _p = ele._private;
  21709. var th = labelThreshold;
  21710. var prefixDash = '';
  21711. ele.boundingBox();
  21712. var bb = _p.labelBounds['main'];
  21713. // If the bounding box is not available, return null.
  21714. // This indicates that the label box cannot be calculated, which is consistent
  21715. // with the expected behavior of this function. Returning null allows the caller
  21716. // to handle the absence of a bounding box explicitly.
  21717. if (!bb) {
  21718. return null;
  21719. }
  21720. var lx = preprop(_p.rscratch, 'labelX', prefix);
  21721. var ly = preprop(_p.rscratch, 'labelY', prefix);
  21722. var theta = preprop(_p.rscratch, 'labelAngle', prefix);
  21723. var ox = ele.pstyle(prefixDash + 'text-margin-x').pfValue;
  21724. var oy = ele.pstyle(prefixDash + 'text-margin-y').pfValue;
  21725. var lx1 = bb.x1 - th - ox;
  21726. var lx2 = bb.x2 + th - ox;
  21727. var ly1 = bb.y1 - th - oy;
  21728. var ly2 = bb.y2 + th - oy;
  21729. if (theta) {
  21730. var cos = Math.cos(theta);
  21731. var sin = Math.sin(theta);
  21732. var rotate = function rotate(x, y) {
  21733. x = x - lx;
  21734. y = y - ly;
  21735. return {
  21736. x: x * cos - y * sin + lx,
  21737. y: x * sin + y * cos + ly
  21738. };
  21739. };
  21740. return [rotate(lx1, ly1), rotate(lx2, ly1), rotate(lx2, ly2), rotate(lx1, ly2)];
  21741. } else {
  21742. return [{
  21743. x: lx1,
  21744. y: ly1
  21745. }, {
  21746. x: lx2,
  21747. y: ly1
  21748. }, {
  21749. x: lx2,
  21750. y: ly2
  21751. }, {
  21752. x: lx1,
  21753. y: ly2
  21754. }];
  21755. }
  21756. }
  21757. function doLinesIntersect(p1, p2, q1, q2) {
  21758. function ccw(a, b, c) {
  21759. return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
  21760. }
  21761. return ccw(p1, q1, q2) !== ccw(p2, q1, q2) && ccw(p1, p2, q1) !== ccw(p1, p2, q2);
  21762. }
  21763. for (var e = 0; e < eles.length; e++) {
  21764. var ele = eles[e];
  21765. if (ele.isNode()) {
  21766. var node = ele;
  21767. var textEvents = node.pstyle('text-events').strValue === 'yes';
  21768. var nodeBoxSelectMode = node.pstyle('box-selection').strValue;
  21769. var labelBoxSelectEnabled = node.pstyle('box-select-labels').strValue === 'yes';
  21770. if (nodeBoxSelectMode === 'none') {
  21771. continue;
  21772. }
  21773. var includeLabels = (nodeBoxSelectMode === 'overlap' || labelBoxSelectEnabled) && textEvents;
  21774. var nodeBb = node.boundingBox({
  21775. includeNodes: true,
  21776. includeEdges: false,
  21777. includeLabels: includeLabels
  21778. });
  21779. if (nodeBoxSelectMode === 'contain') {
  21780. var selected = false;
  21781. if (labelBoxSelectEnabled && textEvents) {
  21782. var rotatedLabelBox = getRotatedLabelBox(node);
  21783. if (rotatedLabelBox && satPolygonIntersection(rotatedLabelBox, selectionBox)) {
  21784. box.push(node);
  21785. selected = true;
  21786. }
  21787. }
  21788. if (!selected && boundingBoxInBoundingBox(boxBb, nodeBb)) {
  21789. box.push(node);
  21790. }
  21791. } else if (nodeBoxSelectMode === 'overlap') {
  21792. if (boundingBoxesIntersect(boxBb, nodeBb)) {
  21793. var nodeBodyBb = node.boundingBox({
  21794. includeNodes: true,
  21795. includeEdges: true,
  21796. includeLabels: false,
  21797. includeMainLabels: false,
  21798. includeSourceLabels: false,
  21799. includeTargetLabels: false
  21800. });
  21801. var nodeBodyCorners = [{
  21802. x: nodeBodyBb.x1,
  21803. y: nodeBodyBb.y1
  21804. }, {
  21805. x: nodeBodyBb.x2,
  21806. y: nodeBodyBb.y1
  21807. }, {
  21808. x: nodeBodyBb.x2,
  21809. y: nodeBodyBb.y2
  21810. }, {
  21811. x: nodeBodyBb.x1,
  21812. y: nodeBodyBb.y2
  21813. }];
  21814. // if node body intersects, no need to check label
  21815. if (satPolygonIntersection(nodeBodyCorners, selectionBox)) {
  21816. box.push(node);
  21817. } else {
  21818. // only check label if node body didn't intersect
  21819. var _rotatedLabelBox = getRotatedLabelBox(node);
  21820. if (_rotatedLabelBox && satPolygonIntersection(_rotatedLabelBox, selectionBox)) {
  21821. box.push(node);
  21822. }
  21823. }
  21824. }
  21825. }
  21826. } else {
  21827. var edge = ele;
  21828. var _p = edge._private;
  21829. var rs = _p.rscratch;
  21830. var edgeBoxSelectMode = edge.pstyle('box-selection').strValue;
  21831. if (edgeBoxSelectMode === 'none') {
  21832. continue;
  21833. }
  21834. if (edgeBoxSelectMode === 'contain') {
  21835. if (rs.startX != null && rs.startY != null && !inBoundingBox(boxBb, rs.startX, rs.startY)) {
  21836. continue;
  21837. }
  21838. if (rs.endX != null && rs.endY != null && !inBoundingBox(boxBb, rs.endX, rs.endY)) {
  21839. continue;
  21840. }
  21841. if (rs.edgeType === 'bezier' || rs.edgeType === 'multibezier' || rs.edgeType === 'self' || rs.edgeType === 'compound' || rs.edgeType === 'segments' || rs.edgeType === 'haystack') {
  21842. var pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
  21843. var allInside = true;
  21844. for (var i = 0; i < pts.length; i++) {
  21845. if (!pointInBoundingBox(boxBb, pts[i])) {
  21846. allInside = false;
  21847. break;
  21848. }
  21849. }
  21850. if (allInside) {
  21851. box.push(edge);
  21852. }
  21853. } else if (rs.edgeType === 'straight') {
  21854. box.push(edge);
  21855. }
  21856. } else if (edgeBoxSelectMode === 'overlap') {
  21857. var _selected = false;
  21858. // Check: either endpoint inside box
  21859. 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))) {
  21860. box.push(edge);
  21861. _selected = true;
  21862. }
  21863. // Haystack fallback (only check if not already selected)
  21864. else if (!_selected && rs.edgeType === 'haystack') {
  21865. var haystackPts = _p.rstyle.haystackPts;
  21866. for (var _i = 0; _i < haystackPts.length; _i++) {
  21867. if (pointInBoundingBox(boxBb, haystackPts[_i])) {
  21868. box.push(edge);
  21869. _selected = true;
  21870. break;
  21871. }
  21872. }
  21873. }
  21874. // Segment intersection check (only if not already selected)
  21875. if (!_selected) {
  21876. var _pts = _p.rstyle.bezierPts || _p.rstyle.linePts || _p.rstyle.haystackPts;
  21877. // straight edges
  21878. if ((!_pts || _pts.length < 2) && rs.edgeType === 'straight') {
  21879. if (rs.startX != null && rs.startY != null && rs.endX != null && rs.endY != null) {
  21880. _pts = [{
  21881. x: rs.startX,
  21882. y: rs.startY
  21883. }, {
  21884. x: rs.endX,
  21885. y: rs.endY
  21886. }];
  21887. }
  21888. }
  21889. if (!_pts || _pts.length < 2) continue;
  21890. for (var _i2 = 0; _i2 < _pts.length - 1; _i2++) {
  21891. var segStart = _pts[_i2];
  21892. var segEnd = _pts[_i2 + 1];
  21893. for (var b = 0; b < boxEdges.length; b++) {
  21894. var _boxEdges$b = _slicedToArray(boxEdges[b], 2),
  21895. boxStart = _boxEdges$b[0],
  21896. boxEnd = _boxEdges$b[1];
  21897. if (doLinesIntersect(segStart, segEnd, boxStart, boxEnd)) {
  21898. box.push(edge);
  21899. _selected = true;
  21900. break;
  21901. }
  21902. }
  21903. if (_selected) break;
  21904. }
  21905. }
  21906. }
  21907. }
  21908. }
  21909. return box;
  21910. };
  21911. var BRp$d = {};
  21912. BRp$d.calculateArrowAngles = function (edge) {
  21913. var rs = edge._private.rscratch;
  21914. var isHaystack = rs.edgeType === 'haystack';
  21915. var isBezier = rs.edgeType === 'bezier';
  21916. var isMultibezier = rs.edgeType === 'multibezier';
  21917. var isSegments = rs.edgeType === 'segments';
  21918. var isCompound = rs.edgeType === 'compound';
  21919. var isSelf = rs.edgeType === 'self';
  21920. // Displacement gives direction for arrowhead orientation
  21921. var dispX, dispY;
  21922. var startX, startY, endX, endY, midX, midY;
  21923. if (isHaystack) {
  21924. startX = rs.haystackPts[0];
  21925. startY = rs.haystackPts[1];
  21926. endX = rs.haystackPts[2];
  21927. endY = rs.haystackPts[3];
  21928. } else {
  21929. startX = rs.arrowStartX;
  21930. startY = rs.arrowStartY;
  21931. endX = rs.arrowEndX;
  21932. endY = rs.arrowEndY;
  21933. }
  21934. midX = rs.midX;
  21935. midY = rs.midY;
  21936. // source
  21937. //
  21938. if (isSegments) {
  21939. dispX = startX - rs.segpts[0];
  21940. dispY = startY - rs.segpts[1];
  21941. } else if (isMultibezier || isCompound || isSelf || isBezier) {
  21942. var pts = rs.allpts;
  21943. var bX = qbezierAt(pts[0], pts[2], pts[4], 0.1);
  21944. var bY = qbezierAt(pts[1], pts[3], pts[5], 0.1);
  21945. dispX = startX - bX;
  21946. dispY = startY - bY;
  21947. } else {
  21948. dispX = startX - midX;
  21949. dispY = startY - midY;
  21950. }
  21951. rs.srcArrowAngle = getAngleFromDisp(dispX, dispY);
  21952. // mid target
  21953. //
  21954. var midX = rs.midX;
  21955. var midY = rs.midY;
  21956. if (isHaystack) {
  21957. midX = (startX + endX) / 2;
  21958. midY = (startY + endY) / 2;
  21959. }
  21960. dispX = endX - startX;
  21961. dispY = endY - startY;
  21962. if (isSegments) {
  21963. var pts = rs.allpts;
  21964. if (pts.length / 2 % 2 === 0) {
  21965. var i2 = pts.length / 2;
  21966. var i1 = i2 - 2;
  21967. dispX = pts[i2] - pts[i1];
  21968. dispY = pts[i2 + 1] - pts[i1 + 1];
  21969. } else if (rs.isRound) {
  21970. dispX = rs.midVector[1];
  21971. dispY = -rs.midVector[0];
  21972. } else {
  21973. var i2 = pts.length / 2 - 1;
  21974. var i1 = i2 - 2;
  21975. dispX = pts[i2] - pts[i1];
  21976. dispY = pts[i2 + 1] - pts[i1 + 1];
  21977. }
  21978. } else if (isMultibezier || isCompound || isSelf) {
  21979. var pts = rs.allpts;
  21980. var cpts = rs.ctrlpts;
  21981. var bp0x, bp0y;
  21982. var bp1x, bp1y;
  21983. if (cpts.length / 2 % 2 === 0) {
  21984. var p0 = pts.length / 2 - 1; // startpt
  21985. var ic = p0 + 2;
  21986. var p1 = ic + 2;
  21987. bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0);
  21988. bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0);
  21989. bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.0001);
  21990. bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.0001);
  21991. } else {
  21992. var ic = pts.length / 2 - 1; // ctrpt
  21993. var p0 = ic - 2; // startpt
  21994. var p1 = ic + 2; // endpt
  21995. bp0x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.4999);
  21996. bp0y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.4999);
  21997. bp1x = qbezierAt(pts[p0], pts[ic], pts[p1], 0.5);
  21998. bp1y = qbezierAt(pts[p0 + 1], pts[ic + 1], pts[p1 + 1], 0.5);
  21999. }
  22000. dispX = bp1x - bp0x;
  22001. dispY = bp1y - bp0y;
  22002. }
  22003. rs.midtgtArrowAngle = getAngleFromDisp(dispX, dispY);
  22004. rs.midDispX = dispX;
  22005. rs.midDispY = dispY;
  22006. // mid source
  22007. //
  22008. dispX *= -1;
  22009. dispY *= -1;
  22010. if (isSegments) {
  22011. var pts = rs.allpts;
  22012. if (pts.length / 2 % 2 === 0) ; else if (!rs.isRound) {
  22013. var i2 = pts.length / 2 - 1;
  22014. var i3 = i2 + 2;
  22015. dispX = -(pts[i3] - pts[i2]);
  22016. dispY = -(pts[i3 + 1] - pts[i2 + 1]);
  22017. }
  22018. }
  22019. rs.midsrcArrowAngle = getAngleFromDisp(dispX, dispY);
  22020. // target
  22021. //
  22022. if (isSegments) {
  22023. dispX = endX - rs.segpts[rs.segpts.length - 2];
  22024. dispY = endY - rs.segpts[rs.segpts.length - 1];
  22025. } else if (isMultibezier || isCompound || isSelf || isBezier) {
  22026. var pts = rs.allpts;
  22027. var l = pts.length;
  22028. var bX = qbezierAt(pts[l - 6], pts[l - 4], pts[l - 2], 0.9);
  22029. var bY = qbezierAt(pts[l - 5], pts[l - 3], pts[l - 1], 0.9);
  22030. dispX = endX - bX;
  22031. dispY = endY - bY;
  22032. } else {
  22033. dispX = endX - midX;
  22034. dispY = endY - midY;
  22035. }
  22036. rs.tgtArrowAngle = getAngleFromDisp(dispX, dispY);
  22037. };
  22038. BRp$d.getArrowWidth = BRp$d.getArrowHeight = function (edgeWidth, scale) {
  22039. var cache = this.arrowWidthCache = this.arrowWidthCache || {};
  22040. var cachedVal = cache[edgeWidth + ', ' + scale];
  22041. if (cachedVal) {
  22042. return cachedVal;
  22043. }
  22044. cachedVal = Math.max(Math.pow(edgeWidth * 13.37, 0.9), 29) * scale;
  22045. cache[edgeWidth + ', ' + scale] = cachedVal;
  22046. return cachedVal;
  22047. };
  22048. /**
  22049. * Explained by Blindman67 at https://stackoverflow.com/a/44856925/11028828
  22050. */
  22051. // Declare reused variable to avoid reallocating variables every time the function is called
  22052. var x,
  22053. y,
  22054. v1 = {},
  22055. v2 = {},
  22056. sinA,
  22057. sinA90,
  22058. radDirection,
  22059. drawDirection,
  22060. angle,
  22061. halfAngle,
  22062. cRadius,
  22063. lenOut,
  22064. radius,
  22065. limit;
  22066. var startX, startY, stopX, stopY;
  22067. var lastPoint;
  22068. // convert 2 points into vector form, polar form, and normalised
  22069. var asVec = function asVec(p, pp, v) {
  22070. v.x = pp.x - p.x;
  22071. v.y = pp.y - p.y;
  22072. v.len = Math.sqrt(v.x * v.x + v.y * v.y);
  22073. v.nx = v.x / v.len;
  22074. v.ny = v.y / v.len;
  22075. v.ang = Math.atan2(v.ny, v.nx);
  22076. };
  22077. var invertVec = function invertVec(originalV, invertedV) {
  22078. invertedV.x = originalV.x * -1;
  22079. invertedV.y = originalV.y * -1;
  22080. invertedV.nx = originalV.nx * -1;
  22081. invertedV.ny = originalV.ny * -1;
  22082. invertedV.ang = originalV.ang > 0 ? -(Math.PI - originalV.ang) : Math.PI + originalV.ang;
  22083. };
  22084. var calcCornerArc = function calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius) {
  22085. //-----------------------------------------
  22086. // Part 1
  22087. previousPoint !== lastPoint ? asVec(currentPoint, previousPoint, v1) : invertVec(v2, v1); // Avoid recalculating vec if it is the invert of the last one calculated
  22088. asVec(currentPoint, nextPoint, v2);
  22089. sinA = v1.nx * v2.ny - v1.ny * v2.nx;
  22090. sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;
  22091. angle = Math.asin(Math.max(-1, Math.min(1, sinA)));
  22092. if (Math.abs(angle) < 1e-6) {
  22093. x = currentPoint.x;
  22094. y = currentPoint.y;
  22095. cRadius = radius = 0;
  22096. return;
  22097. }
  22098. //-----------------------------------------
  22099. radDirection = 1;
  22100. drawDirection = false;
  22101. if (sinA90 < 0) {
  22102. if (angle < 0) {
  22103. angle = Math.PI + angle;
  22104. } else {
  22105. angle = Math.PI - angle;
  22106. radDirection = -1;
  22107. drawDirection = true;
  22108. }
  22109. } else {
  22110. if (angle > 0) {
  22111. radDirection = -1;
  22112. drawDirection = true;
  22113. }
  22114. }
  22115. if (currentPoint.radius !== undefined) {
  22116. radius = currentPoint.radius;
  22117. } else {
  22118. radius = radiusMax;
  22119. }
  22120. //-----------------------------------------
  22121. // Part 2
  22122. halfAngle = angle / 2;
  22123. //-----------------------------------------
  22124. limit = Math.min(v1.len / 2, v2.len / 2);
  22125. if (isArcRadius) {
  22126. //-----------------------------------------
  22127. // Part 3
  22128. lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));
  22129. //-----------------------------------------
  22130. // Special part A
  22131. if (lenOut > limit) {
  22132. lenOut = limit;
  22133. cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  22134. } else {
  22135. cRadius = radius;
  22136. }
  22137. } else {
  22138. lenOut = Math.min(limit, radius);
  22139. cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
  22140. }
  22141. //-----------------------------------------
  22142. //-----------------------------------------
  22143. // Part 4
  22144. stopX = currentPoint.x + v2.nx * lenOut;
  22145. stopY = currentPoint.y + v2.ny * lenOut;
  22146. //-----------------------------------------
  22147. // Part 5
  22148. x = stopX - v2.ny * cRadius * radDirection;
  22149. y = stopY + v2.nx * cRadius * radDirection;
  22150. //-----------------------------------------
  22151. // Additional Part : calculate start point E
  22152. startX = currentPoint.x + v1.nx * lenOut;
  22153. startY = currentPoint.y + v1.ny * lenOut;
  22154. // Save last point to avoid recalculating vector when not needed
  22155. lastPoint = currentPoint;
  22156. };
  22157. /**
  22158. * Draw corner provided by {@link getRoundCorner}
  22159. *
  22160. * @param ctx :CanvasRenderingContext2D
  22161. * @param roundCorner {{cx:number, cy:number, radius:number, endAngle: number, startAngle: number, counterClockwise: boolean}}
  22162. */
  22163. function drawPreparedRoundCorner(ctx, roundCorner) {
  22164. 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);
  22165. }
  22166. /**
  22167. * Get round corner from a point and its previous and next neighbours in a path
  22168. *
  22169. * @param previousPoint {{x: number, y:number, radius: number?}}
  22170. * @param currentPoint {{x: number, y:number, radius: number?}}
  22171. * @param nextPoint {{x: number, y:number, radius: number?}}
  22172. * @param radiusMax :number
  22173. * @param isArcRadius :boolean
  22174. * @return {{
  22175. * cx:number, cy:number, radius:number,
  22176. * startX:number, startY:number,
  22177. * stopX:number, stopY: number,
  22178. * endAngle: number, startAngle: number, counterClockwise: boolean
  22179. * }}
  22180. */
  22181. function getRoundCorner(previousPoint, currentPoint, nextPoint, radiusMax) {
  22182. var isArcRadius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  22183. if (radiusMax === 0 || currentPoint.radius === 0) return {
  22184. cx: currentPoint.x,
  22185. cy: currentPoint.y,
  22186. radius: 0,
  22187. startX: currentPoint.x,
  22188. startY: currentPoint.y,
  22189. stopX: currentPoint.x,
  22190. stopY: currentPoint.y,
  22191. startAngle: undefined,
  22192. endAngle: undefined,
  22193. counterClockwise: undefined
  22194. };
  22195. calcCornerArc(previousPoint, currentPoint, nextPoint, radiusMax, isArcRadius);
  22196. return {
  22197. cx: x,
  22198. cy: y,
  22199. radius: cRadius,
  22200. startX: startX,
  22201. startY: startY,
  22202. stopX: stopX,
  22203. stopY: stopY,
  22204. startAngle: v1.ang + Math.PI / 2 * radDirection,
  22205. endAngle: v2.ang - Math.PI / 2 * radDirection,
  22206. counterClockwise: drawDirection
  22207. };
  22208. }
  22209. var AVOID_IMPOSSIBLE_BEZIER_CONSTANT = 0.01;
  22210. var AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L = Math.sqrt(2 * AVOID_IMPOSSIBLE_BEZIER_CONSTANT);
  22211. var BRp$c = {};
  22212. BRp$c.findMidptPtsEtc = function (edge, pairInfo) {
  22213. var posPts = pairInfo.posPts,
  22214. intersectionPts = pairInfo.intersectionPts,
  22215. vectorNormInverse = pairInfo.vectorNormInverse;
  22216. var midptPts;
  22217. // n.b. assumes all edges in bezier bundle have same endpoints specified
  22218. var srcManEndpt = edge.pstyle('source-endpoint');
  22219. var tgtManEndpt = edge.pstyle('target-endpoint');
  22220. var haveManualEndPts = srcManEndpt.units != null && tgtManEndpt.units != null;
  22221. var recalcVectorNormInverse = function recalcVectorNormInverse(x1, y1, x2, y2) {
  22222. var dy = y2 - y1;
  22223. var dx = x2 - x1;
  22224. var l = Math.sqrt(dx * dx + dy * dy);
  22225. return {
  22226. x: -dy / l,
  22227. y: dx / l
  22228. };
  22229. };
  22230. var edgeDistances = edge.pstyle('edge-distances').value;
  22231. switch (edgeDistances) {
  22232. case 'node-position':
  22233. midptPts = posPts;
  22234. break;
  22235. case 'intersection':
  22236. midptPts = intersectionPts;
  22237. break;
  22238. case 'endpoints':
  22239. {
  22240. if (haveManualEndPts) {
  22241. var _this$manualEndptToPx = this.manualEndptToPx(edge.source()[0], srcManEndpt),
  22242. _this$manualEndptToPx2 = _slicedToArray(_this$manualEndptToPx, 2),
  22243. x1 = _this$manualEndptToPx2[0],
  22244. y1 = _this$manualEndptToPx2[1];
  22245. var _this$manualEndptToPx3 = this.manualEndptToPx(edge.target()[0], tgtManEndpt),
  22246. _this$manualEndptToPx4 = _slicedToArray(_this$manualEndptToPx3, 2),
  22247. x2 = _this$manualEndptToPx4[0],
  22248. y2 = _this$manualEndptToPx4[1];
  22249. var endPts = {
  22250. x1: x1,
  22251. y1: y1,
  22252. x2: x2,
  22253. y2: y2
  22254. };
  22255. vectorNormInverse = recalcVectorNormInverse(x1, y1, x2, y2);
  22256. midptPts = endPts;
  22257. } else {
  22258. 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)."));
  22259. midptPts = intersectionPts; // back to default
  22260. }
  22261. break;
  22262. }
  22263. }
  22264. return {
  22265. midptPts: midptPts,
  22266. vectorNormInverse: vectorNormInverse
  22267. };
  22268. };
  22269. BRp$c.findHaystackPoints = function (edges) {
  22270. for (var i = 0; i < edges.length; i++) {
  22271. var edge = edges[i];
  22272. var _p = edge._private;
  22273. var rs = _p.rscratch;
  22274. if (!rs.haystack) {
  22275. var angle = Math.random() * 2 * Math.PI;
  22276. rs.source = {
  22277. x: Math.cos(angle),
  22278. y: Math.sin(angle)
  22279. };
  22280. angle = Math.random() * 2 * Math.PI;
  22281. rs.target = {
  22282. x: Math.cos(angle),
  22283. y: Math.sin(angle)
  22284. };
  22285. }
  22286. var src = _p.source;
  22287. var tgt = _p.target;
  22288. var srcPos = src.position();
  22289. var tgtPos = tgt.position();
  22290. var srcW = src.width();
  22291. var tgtW = tgt.width();
  22292. var srcH = src.height();
  22293. var tgtH = tgt.height();
  22294. var radius = edge.pstyle('haystack-radius').value;
  22295. var halfRadius = radius / 2; // b/c have to half width/height
  22296. 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];
  22297. rs.midX = (rs.allpts[0] + rs.allpts[2]) / 2;
  22298. rs.midY = (rs.allpts[1] + rs.allpts[3]) / 2;
  22299. // always override as haystack in case set to different type previously
  22300. rs.edgeType = 'haystack';
  22301. rs.haystack = true;
  22302. this.storeEdgeProjections(edge);
  22303. this.calculateArrowAngles(edge);
  22304. this.recalculateEdgeLabelProjections(edge);
  22305. this.calculateLabelAngles(edge);
  22306. }
  22307. };
  22308. BRp$c.findSegmentsPoints = function (edge, pairInfo) {
  22309. // Segments (multiple straight lines)
  22310. var rs = edge._private.rscratch;
  22311. var segmentWs = edge.pstyle('segment-weights');
  22312. var segmentDs = edge.pstyle('segment-distances');
  22313. var segmentRs = edge.pstyle('segment-radii');
  22314. var segmentTs = edge.pstyle('radius-type');
  22315. var segmentsN = Math.min(segmentWs.pfValue.length, segmentDs.pfValue.length);
  22316. var lastRadius = segmentRs.pfValue[segmentRs.pfValue.length - 1];
  22317. var lastRadiusType = segmentTs.pfValue[segmentTs.pfValue.length - 1];
  22318. rs.edgeType = 'segments';
  22319. rs.segpts = [];
  22320. rs.radii = [];
  22321. rs.isArcRadius = [];
  22322. for (var s = 0; s < segmentsN; s++) {
  22323. var w = segmentWs.pfValue[s];
  22324. var d = segmentDs.pfValue[s];
  22325. var w1 = 1 - w;
  22326. var w2 = w;
  22327. var _this$findMidptPtsEtc = this.findMidptPtsEtc(edge, pairInfo),
  22328. midptPts = _this$findMidptPtsEtc.midptPts,
  22329. vectorNormInverse = _this$findMidptPtsEtc.vectorNormInverse;
  22330. var adjustedMidpt = {
  22331. x: midptPts.x1 * w1 + midptPts.x2 * w2,
  22332. y: midptPts.y1 * w1 + midptPts.y2 * w2
  22333. };
  22334. rs.segpts.push(adjustedMidpt.x + vectorNormInverse.x * d, adjustedMidpt.y + vectorNormInverse.y * d);
  22335. rs.radii.push(segmentRs.pfValue[s] !== undefined ? segmentRs.pfValue[s] : lastRadius);
  22336. rs.isArcRadius.push((segmentTs.pfValue[s] !== undefined ? segmentTs.pfValue[s] : lastRadiusType) === 'arc-radius');
  22337. }
  22338. };
  22339. BRp$c.findLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  22340. // Self-edge
  22341. var rs = edge._private.rscratch;
  22342. var dirCounts = pairInfo.dirCounts,
  22343. srcPos = pairInfo.srcPos;
  22344. var ctrlptDists = edge.pstyle('control-point-distances');
  22345. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22346. var loopDir = edge.pstyle('loop-direction').pfValue;
  22347. var loopSwp = edge.pstyle('loop-sweep').pfValue;
  22348. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22349. rs.edgeType = 'self';
  22350. var j = i;
  22351. var loopDist = stepSize;
  22352. if (edgeIsUnbundled) {
  22353. j = 0;
  22354. loopDist = ctrlptDist;
  22355. }
  22356. var loopAngle = loopDir - Math.PI / 2;
  22357. var outAngle = loopAngle - loopSwp / 2;
  22358. var inAngle = loopAngle + loopSwp / 2;
  22359. // increase by step size for overlapping loops, keyed on direction and sweep values
  22360. var dc = String(loopDir + '_' + loopSwp);
  22361. j = dirCounts[dc] === undefined ? dirCounts[dc] = 0 : ++dirCounts[dc];
  22362. 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)];
  22363. };
  22364. BRp$c.findCompoundLoopPoints = function (edge, pairInfo, i, edgeIsUnbundled) {
  22365. // Compound edge
  22366. var rs = edge._private.rscratch;
  22367. rs.edgeType = 'compound';
  22368. var srcPos = pairInfo.srcPos,
  22369. tgtPos = pairInfo.tgtPos,
  22370. srcW = pairInfo.srcW,
  22371. srcH = pairInfo.srcH,
  22372. tgtW = pairInfo.tgtW,
  22373. tgtH = pairInfo.tgtH;
  22374. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22375. var ctrlptDists = edge.pstyle('control-point-distances');
  22376. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22377. var j = i;
  22378. var loopDist = stepSize;
  22379. if (edgeIsUnbundled) {
  22380. j = 0;
  22381. loopDist = ctrlptDist;
  22382. }
  22383. var loopW = 50;
  22384. var loopaPos = {
  22385. x: srcPos.x - srcW / 2,
  22386. y: srcPos.y - srcH / 2
  22387. };
  22388. var loopbPos = {
  22389. x: tgtPos.x - tgtW / 2,
  22390. y: tgtPos.y - tgtH / 2
  22391. };
  22392. var loopPos = {
  22393. x: Math.min(loopaPos.x, loopbPos.x),
  22394. y: Math.min(loopaPos.y, loopbPos.y)
  22395. };
  22396. // avoids cases with impossible beziers
  22397. var minCompoundStretch = 0.5;
  22398. var compoundStretchA = Math.max(minCompoundStretch, Math.log(srcW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22399. var compoundStretchB = Math.max(minCompoundStretch, Math.log(tgtW * AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22400. 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];
  22401. };
  22402. BRp$c.findStraightEdgePoints = function (edge) {
  22403. // Straight edge within bundle
  22404. edge._private.rscratch.edgeType = 'straight';
  22405. };
  22406. BRp$c.findBezierPoints = function (edge, pairInfo, i, edgeIsUnbundled, edgeIsSwapped) {
  22407. var rs = edge._private.rscratch;
  22408. var stepSize = edge.pstyle('control-point-step-size').pfValue;
  22409. var ctrlptDists = edge.pstyle('control-point-distances');
  22410. var ctrlptWs = edge.pstyle('control-point-weights');
  22411. var bezierN = ctrlptDists && ctrlptWs ? Math.min(ctrlptDists.value.length, ctrlptWs.value.length) : 1;
  22412. var ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[0] : undefined;
  22413. var ctrlptWeight = ctrlptWs.value[0];
  22414. // (Multi)bezier
  22415. var multi = edgeIsUnbundled;
  22416. rs.edgeType = multi ? 'multibezier' : 'bezier';
  22417. rs.ctrlpts = [];
  22418. for (var b = 0; b < bezierN; b++) {
  22419. var normctrlptDist = (0.5 - pairInfo.eles.length / 2 + i) * stepSize * (edgeIsSwapped ? -1 : 1);
  22420. var manctrlptDist = undefined;
  22421. var sign = signum(normctrlptDist);
  22422. if (multi) {
  22423. ctrlptDist = ctrlptDists ? ctrlptDists.pfValue[b] : stepSize; // fall back on step size
  22424. ctrlptWeight = ctrlptWs.value[b];
  22425. }
  22426. if (edgeIsUnbundled) {
  22427. // multi or single unbundled
  22428. manctrlptDist = ctrlptDist;
  22429. } else {
  22430. manctrlptDist = ctrlptDist !== undefined ? sign * ctrlptDist : undefined;
  22431. }
  22432. var distanceFromMidpoint = manctrlptDist !== undefined ? manctrlptDist : normctrlptDist;
  22433. var w1 = 1 - ctrlptWeight;
  22434. var w2 = ctrlptWeight;
  22435. var _this$findMidptPtsEtc2 = this.findMidptPtsEtc(edge, pairInfo),
  22436. midptPts = _this$findMidptPtsEtc2.midptPts,
  22437. vectorNormInverse = _this$findMidptPtsEtc2.vectorNormInverse;
  22438. var adjustedMidpt = {
  22439. x: midptPts.x1 * w1 + midptPts.x2 * w2,
  22440. y: midptPts.y1 * w1 + midptPts.y2 * w2
  22441. };
  22442. rs.ctrlpts.push(adjustedMidpt.x + vectorNormInverse.x * distanceFromMidpoint, adjustedMidpt.y + vectorNormInverse.y * distanceFromMidpoint);
  22443. }
  22444. };
  22445. BRp$c.findTaxiPoints = function (edge, pairInfo) {
  22446. // Taxicab geometry with two turns maximum
  22447. var rs = edge._private.rscratch;
  22448. rs.edgeType = 'segments';
  22449. var VERTICAL = 'vertical';
  22450. var HORIZONTAL = 'horizontal';
  22451. var LEFTWARD = 'leftward';
  22452. var RIGHTWARD = 'rightward';
  22453. var DOWNWARD = 'downward';
  22454. var UPWARD = 'upward';
  22455. var AUTO = 'auto';
  22456. var posPts = pairInfo.posPts,
  22457. srcW = pairInfo.srcW,
  22458. srcH = pairInfo.srcH,
  22459. tgtW = pairInfo.tgtW,
  22460. tgtH = pairInfo.tgtH;
  22461. var edgeDistances = edge.pstyle('edge-distances').value;
  22462. var dIncludesNodeBody = edgeDistances !== 'node-position';
  22463. var taxiDir = edge.pstyle('taxi-direction').value;
  22464. var rawTaxiDir = taxiDir; // unprocessed value
  22465. var taxiTurn = edge.pstyle('taxi-turn');
  22466. var turnIsPercent = taxiTurn.units === '%';
  22467. var taxiTurnPfVal = taxiTurn.pfValue;
  22468. var turnIsNegative = taxiTurnPfVal < 0; // i.e. from target side
  22469. var minD = edge.pstyle('taxi-turn-min-distance').pfValue;
  22470. var dw = dIncludesNodeBody ? (srcW + tgtW) / 2 : 0;
  22471. var dh = dIncludesNodeBody ? (srcH + tgtH) / 2 : 0;
  22472. var pdx = posPts.x2 - posPts.x1;
  22473. var pdy = posPts.y2 - posPts.y1;
  22474. // take away the effective w/h from the magnitude of the delta value
  22475. var subDWH = function subDWH(dxy, dwh) {
  22476. if (dxy > 0) {
  22477. return Math.max(dxy - dwh, 0);
  22478. } else {
  22479. return Math.min(dxy + dwh, 0);
  22480. }
  22481. };
  22482. var dx = subDWH(pdx, dw);
  22483. var dy = subDWH(pdy, dh);
  22484. var isExplicitDir = false;
  22485. if (rawTaxiDir === AUTO) {
  22486. taxiDir = Math.abs(dx) > Math.abs(dy) ? HORIZONTAL : VERTICAL;
  22487. } else if (rawTaxiDir === UPWARD || rawTaxiDir === DOWNWARD) {
  22488. taxiDir = VERTICAL;
  22489. isExplicitDir = true;
  22490. } else if (rawTaxiDir === LEFTWARD || rawTaxiDir === RIGHTWARD) {
  22491. taxiDir = HORIZONTAL;
  22492. isExplicitDir = true;
  22493. }
  22494. var isVert = taxiDir === VERTICAL;
  22495. var l = isVert ? dy : dx;
  22496. var pl = isVert ? pdy : pdx;
  22497. var sgnL = signum(pl);
  22498. var forcedDir = false;
  22499. if (!(isExplicitDir && (turnIsPercent || turnIsNegative)) // forcing in this case would cause weird growing in the opposite direction
  22500. && (rawTaxiDir === DOWNWARD && pl < 0 || rawTaxiDir === UPWARD && pl > 0 || rawTaxiDir === LEFTWARD && pl > 0 || rawTaxiDir === RIGHTWARD && pl < 0)) {
  22501. sgnL *= -1;
  22502. l = sgnL * Math.abs(l);
  22503. forcedDir = true;
  22504. }
  22505. var d;
  22506. if (turnIsPercent) {
  22507. var p = taxiTurnPfVal < 0 ? 1 + taxiTurnPfVal : taxiTurnPfVal;
  22508. d = p * l;
  22509. } else {
  22510. var k = taxiTurnPfVal < 0 ? l : 0;
  22511. d = k + taxiTurnPfVal * sgnL;
  22512. }
  22513. var getIsTooClose = function getIsTooClose(d) {
  22514. return Math.abs(d) < minD || Math.abs(d) >= Math.abs(l);
  22515. };
  22516. var isTooCloseSrc = getIsTooClose(d);
  22517. var isTooCloseTgt = getIsTooClose(Math.abs(l) - Math.abs(d));
  22518. var isTooClose = isTooCloseSrc || isTooCloseTgt;
  22519. if (isTooClose && !forcedDir) {
  22520. // non-ideal routing
  22521. if (isVert) {
  22522. // vertical fallbacks
  22523. var lShapeInsideSrc = Math.abs(pl) <= srcH / 2;
  22524. var lShapeInsideTgt = Math.abs(pdx) <= tgtW / 2;
  22525. if (lShapeInsideSrc) {
  22526. // horizontal Z-shape (direction not respected)
  22527. var x = (posPts.x1 + posPts.x2) / 2;
  22528. var y1 = posPts.y1,
  22529. y2 = posPts.y2;
  22530. rs.segpts = [x, y1, x, y2];
  22531. } else if (lShapeInsideTgt) {
  22532. // vertical Z-shape (distance not respected)
  22533. var y = (posPts.y1 + posPts.y2) / 2;
  22534. var x1 = posPts.x1,
  22535. x2 = posPts.x2;
  22536. rs.segpts = [x1, y, x2, y];
  22537. } else {
  22538. // L-shape fallback (turn distance not respected, but works well with tree siblings)
  22539. rs.segpts = [posPts.x1, posPts.y2];
  22540. }
  22541. } else {
  22542. // horizontal fallbacks
  22543. var _lShapeInsideSrc = Math.abs(pl) <= srcW / 2;
  22544. var _lShapeInsideTgt = Math.abs(pdy) <= tgtH / 2;
  22545. if (_lShapeInsideSrc) {
  22546. // vertical Z-shape (direction not respected)
  22547. var _y = (posPts.y1 + posPts.y2) / 2;
  22548. var _x = posPts.x1,
  22549. _x2 = posPts.x2;
  22550. rs.segpts = [_x, _y, _x2, _y];
  22551. } else if (_lShapeInsideTgt) {
  22552. // horizontal Z-shape (turn distance not respected)
  22553. var _x3 = (posPts.x1 + posPts.x2) / 2;
  22554. var _y2 = posPts.y1,
  22555. _y3 = posPts.y2;
  22556. rs.segpts = [_x3, _y2, _x3, _y3];
  22557. } else {
  22558. // L-shape (turn distance not respected, but works well for tree siblings)
  22559. rs.segpts = [posPts.x2, posPts.y1];
  22560. }
  22561. }
  22562. } else {
  22563. // ideal routing
  22564. if (isVert) {
  22565. var _y4 = posPts.y1 + d + (dIncludesNodeBody ? srcH / 2 * sgnL : 0);
  22566. var _x4 = posPts.x1,
  22567. _x5 = posPts.x2;
  22568. rs.segpts = [_x4, _y4, _x5, _y4];
  22569. } else {
  22570. // horizontal
  22571. var _x6 = posPts.x1 + d + (dIncludesNodeBody ? srcW / 2 * sgnL : 0);
  22572. var _y5 = posPts.y1,
  22573. _y6 = posPts.y2;
  22574. rs.segpts = [_x6, _y5, _x6, _y6];
  22575. }
  22576. }
  22577. if (rs.isRound) {
  22578. var radius = edge.pstyle('taxi-radius').value;
  22579. var isArcRadius = edge.pstyle('radius-type').value[0] === 'arc-radius';
  22580. rs.radii = new Array(rs.segpts.length / 2).fill(radius);
  22581. rs.isArcRadius = new Array(rs.segpts.length / 2).fill(isArcRadius);
  22582. }
  22583. };
  22584. BRp$c.tryToCorrectInvalidPoints = function (edge, pairInfo) {
  22585. var rs = edge._private.rscratch;
  22586. // can only correct beziers for now...
  22587. if (rs.edgeType === 'bezier') {
  22588. var srcPos = pairInfo.srcPos,
  22589. tgtPos = pairInfo.tgtPos,
  22590. srcW = pairInfo.srcW,
  22591. srcH = pairInfo.srcH,
  22592. tgtW = pairInfo.tgtW,
  22593. tgtH = pairInfo.tgtH,
  22594. srcShape = pairInfo.srcShape,
  22595. tgtShape = pairInfo.tgtShape,
  22596. srcCornerRadius = pairInfo.srcCornerRadius,
  22597. tgtCornerRadius = pairInfo.tgtCornerRadius,
  22598. srcRs = pairInfo.srcRs,
  22599. tgtRs = pairInfo.tgtRs;
  22600. var badStart = !number$1(rs.startX) || !number$1(rs.startY);
  22601. var badAStart = !number$1(rs.arrowStartX) || !number$1(rs.arrowStartY);
  22602. var badEnd = !number$1(rs.endX) || !number$1(rs.endY);
  22603. var badAEnd = !number$1(rs.arrowEndX) || !number$1(rs.arrowEndY);
  22604. var minCpADistFactor = 3;
  22605. var arrowW = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
  22606. var minCpADist = minCpADistFactor * arrowW;
  22607. var startACpDist = dist({
  22608. x: rs.ctrlpts[0],
  22609. y: rs.ctrlpts[1]
  22610. }, {
  22611. x: rs.startX,
  22612. y: rs.startY
  22613. });
  22614. var closeStartACp = startACpDist < minCpADist;
  22615. var endACpDist = dist({
  22616. x: rs.ctrlpts[0],
  22617. y: rs.ctrlpts[1]
  22618. }, {
  22619. x: rs.endX,
  22620. y: rs.endY
  22621. });
  22622. var closeEndACp = endACpDist < minCpADist;
  22623. var overlapping = false;
  22624. if (badStart || badAStart || closeStartACp) {
  22625. overlapping = true;
  22626. // project control point along line from src centre to outside the src shape
  22627. // (otherwise intersection will yield nothing)
  22628. var cpD = {
  22629. // delta
  22630. x: rs.ctrlpts[0] - srcPos.x,
  22631. y: rs.ctrlpts[1] - srcPos.y
  22632. };
  22633. var cpL = Math.sqrt(cpD.x * cpD.x + cpD.y * cpD.y); // length of line
  22634. var cpM = {
  22635. // normalised delta
  22636. x: cpD.x / cpL,
  22637. y: cpD.y / cpL
  22638. };
  22639. var radius = Math.max(srcW, srcH);
  22640. var cpProj = {
  22641. // *2 radius guarantees outside shape
  22642. x: rs.ctrlpts[0] + cpM.x * 2 * radius,
  22643. y: rs.ctrlpts[1] + cpM.y * 2 * radius
  22644. };
  22645. var srcCtrlPtIntn = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, cpProj.x, cpProj.y, 0, srcCornerRadius, srcRs);
  22646. if (closeStartACp) {
  22647. rs.ctrlpts[0] = rs.ctrlpts[0] + cpM.x * (minCpADist - startACpDist);
  22648. rs.ctrlpts[1] = rs.ctrlpts[1] + cpM.y * (minCpADist - startACpDist);
  22649. } else {
  22650. rs.ctrlpts[0] = srcCtrlPtIntn[0] + cpM.x * minCpADist;
  22651. rs.ctrlpts[1] = srcCtrlPtIntn[1] + cpM.y * minCpADist;
  22652. }
  22653. }
  22654. if (badEnd || badAEnd || closeEndACp) {
  22655. overlapping = true;
  22656. // project control point along line from tgt centre to outside the tgt shape
  22657. // (otherwise intersection will yield nothing)
  22658. var _cpD = {
  22659. // delta
  22660. x: rs.ctrlpts[0] - tgtPos.x,
  22661. y: rs.ctrlpts[1] - tgtPos.y
  22662. };
  22663. var _cpL = Math.sqrt(_cpD.x * _cpD.x + _cpD.y * _cpD.y); // length of line
  22664. var _cpM = {
  22665. // normalised delta
  22666. x: _cpD.x / _cpL,
  22667. y: _cpD.y / _cpL
  22668. };
  22669. var _radius = Math.max(srcW, srcH);
  22670. var _cpProj = {
  22671. // *2 radius guarantees outside shape
  22672. x: rs.ctrlpts[0] + _cpM.x * 2 * _radius,
  22673. y: rs.ctrlpts[1] + _cpM.y * 2 * _radius
  22674. };
  22675. var tgtCtrlPtIntn = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, _cpProj.x, _cpProj.y, 0, tgtCornerRadius, tgtRs);
  22676. if (closeEndACp) {
  22677. rs.ctrlpts[0] = rs.ctrlpts[0] + _cpM.x * (minCpADist - endACpDist);
  22678. rs.ctrlpts[1] = rs.ctrlpts[1] + _cpM.y * (minCpADist - endACpDist);
  22679. } else {
  22680. rs.ctrlpts[0] = tgtCtrlPtIntn[0] + _cpM.x * minCpADist;
  22681. rs.ctrlpts[1] = tgtCtrlPtIntn[1] + _cpM.y * minCpADist;
  22682. }
  22683. }
  22684. if (overlapping) {
  22685. // recalc endpts
  22686. this.findEndpoints(edge);
  22687. }
  22688. }
  22689. };
  22690. BRp$c.storeAllpts = function (edge) {
  22691. var rs = edge._private.rscratch;
  22692. if (rs.edgeType === 'multibezier' || rs.edgeType === 'bezier' || rs.edgeType === 'self' || rs.edgeType === 'compound') {
  22693. rs.allpts = [];
  22694. rs.allpts.push(rs.startX, rs.startY);
  22695. for (var b = 0; b + 1 < rs.ctrlpts.length; b += 2) {
  22696. // ctrl pt itself
  22697. rs.allpts.push(rs.ctrlpts[b], rs.ctrlpts[b + 1]);
  22698. // the midpt between ctrlpts as intermediate destination pts
  22699. if (b + 3 < rs.ctrlpts.length) {
  22700. rs.allpts.push((rs.ctrlpts[b] + rs.ctrlpts[b + 2]) / 2, (rs.ctrlpts[b + 1] + rs.ctrlpts[b + 3]) / 2);
  22701. }
  22702. }
  22703. rs.allpts.push(rs.endX, rs.endY);
  22704. var m, mt;
  22705. if (rs.ctrlpts.length / 2 % 2 === 0) {
  22706. m = rs.allpts.length / 2 - 1;
  22707. rs.midX = rs.allpts[m];
  22708. rs.midY = rs.allpts[m + 1];
  22709. } else {
  22710. m = rs.allpts.length / 2 - 3;
  22711. mt = 0.5;
  22712. rs.midX = qbezierAt(rs.allpts[m], rs.allpts[m + 2], rs.allpts[m + 4], mt);
  22713. rs.midY = qbezierAt(rs.allpts[m + 1], rs.allpts[m + 3], rs.allpts[m + 5], mt);
  22714. }
  22715. } else if (rs.edgeType === 'straight') {
  22716. // need to calc these after endpts
  22717. rs.allpts = [rs.startX, rs.startY, rs.endX, rs.endY];
  22718. // default midpt for labels etc
  22719. rs.midX = (rs.startX + rs.endX + rs.arrowStartX + rs.arrowEndX) / 4;
  22720. rs.midY = (rs.startY + rs.endY + rs.arrowStartY + rs.arrowEndY) / 4;
  22721. } else if (rs.edgeType === 'segments') {
  22722. rs.allpts = [];
  22723. rs.allpts.push(rs.startX, rs.startY);
  22724. rs.allpts.push.apply(rs.allpts, rs.segpts);
  22725. rs.allpts.push(rs.endX, rs.endY);
  22726. if (rs.isRound) {
  22727. rs.roundCorners = [];
  22728. for (var i = 2; i + 3 < rs.allpts.length; i += 2) {
  22729. var radius = rs.radii[i / 2 - 1];
  22730. var isArcRadius = rs.isArcRadius[i / 2 - 1];
  22731. rs.roundCorners.push(getRoundCorner({
  22732. x: rs.allpts[i - 2],
  22733. y: rs.allpts[i - 1]
  22734. }, {
  22735. x: rs.allpts[i],
  22736. y: rs.allpts[i + 1],
  22737. radius: radius
  22738. }, {
  22739. x: rs.allpts[i + 2],
  22740. y: rs.allpts[i + 3]
  22741. }, radius, isArcRadius));
  22742. }
  22743. }
  22744. if (rs.segpts.length % 4 === 0) {
  22745. var i2 = rs.segpts.length / 2;
  22746. var i1 = i2 - 2;
  22747. rs.midX = (rs.segpts[i1] + rs.segpts[i2]) / 2;
  22748. rs.midY = (rs.segpts[i1 + 1] + rs.segpts[i2 + 1]) / 2;
  22749. } else {
  22750. var _i = rs.segpts.length / 2 - 1;
  22751. if (!rs.isRound) {
  22752. rs.midX = rs.segpts[_i];
  22753. rs.midY = rs.segpts[_i + 1];
  22754. } else {
  22755. var point = {
  22756. x: rs.segpts[_i],
  22757. y: rs.segpts[_i + 1]
  22758. };
  22759. var corner = rs.roundCorners[_i / 2];
  22760. if (corner.radius === 0) {
  22761. // On collinear points
  22762. var nextPoint = {
  22763. x: rs.segpts[_i + 2],
  22764. y: rs.segpts[_i + 3]
  22765. };
  22766. rs.midX = point.x;
  22767. rs.midY = point.y;
  22768. rs.midVector = [point.y - nextPoint.y, nextPoint.x - point.x];
  22769. } else {
  22770. // On rounded points
  22771. var v = [point.x - corner.cx, point.y - corner.cy];
  22772. var factor = corner.radius / Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2));
  22773. v = v.map(function (c) {
  22774. return c * factor;
  22775. });
  22776. rs.midX = corner.cx + v[0];
  22777. rs.midY = corner.cy + v[1];
  22778. rs.midVector = v;
  22779. }
  22780. }
  22781. }
  22782. }
  22783. };
  22784. BRp$c.checkForInvalidEdgeWarning = function (edge) {
  22785. var rs = edge[0]._private.rscratch;
  22786. if (rs.nodesOverlap || number$1(rs.startX) && number$1(rs.startY) && number$1(rs.endX) && number$1(rs.endY)) {
  22787. rs.loggedErr = false;
  22788. } else {
  22789. if (!rs.loggedErr) {
  22790. rs.loggedErr = true;
  22791. 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.');
  22792. }
  22793. }
  22794. };
  22795. BRp$c.findEdgeControlPoints = function (edges) {
  22796. var _this = this;
  22797. if (!edges || edges.length === 0) {
  22798. return;
  22799. }
  22800. var r = this;
  22801. var cy = r.cy;
  22802. var hasCompounds = cy.hasCompoundNodes();
  22803. var hashTable = new Map$1();
  22804. var getKey = function getKey(pairId, edgeIsUnbundled) {
  22805. return [].concat(_toConsumableArray(pairId), [edgeIsUnbundled ? 1 : 0]).join('-');
  22806. };
  22807. var pairIds = [];
  22808. var haystackEdges = [];
  22809. // create a table of edge (src, tgt) => list of edges between them
  22810. for (var i = 0; i < edges.length; i++) {
  22811. var edge = edges[i];
  22812. var _p = edge._private;
  22813. var curveStyle = edge.pstyle('curve-style').value;
  22814. // ignore edges who are not to be displayed
  22815. // they shouldn't take up space
  22816. if (edge.removed() || !edge.takesUpSpace()) {
  22817. continue;
  22818. }
  22819. if (curveStyle === 'haystack') {
  22820. haystackEdges.push(edge);
  22821. continue;
  22822. }
  22823. var edgeIsUnbundled = curveStyle === 'unbundled-bezier' || endsWith(curveStyle, 'segments') || curveStyle === 'straight' || curveStyle === 'straight-triangle' || endsWith(curveStyle, 'taxi');
  22824. var edgeIsBezier = curveStyle === 'unbundled-bezier' || curveStyle === 'bezier';
  22825. var src = _p.source;
  22826. var tgt = _p.target;
  22827. var srcIndex = src.poolIndex();
  22828. var tgtIndex = tgt.poolIndex();
  22829. var pairId = [srcIndex, tgtIndex].sort();
  22830. var key = getKey(pairId, edgeIsUnbundled);
  22831. var tableEntry = hashTable.get(key);
  22832. if (tableEntry == null) {
  22833. tableEntry = {
  22834. eles: []
  22835. };
  22836. pairIds.push({
  22837. pairId: pairId,
  22838. edgeIsUnbundled: edgeIsUnbundled
  22839. });
  22840. hashTable.set(key, tableEntry);
  22841. }
  22842. tableEntry.eles.push(edge);
  22843. if (edgeIsUnbundled) {
  22844. tableEntry.hasUnbundled = true;
  22845. }
  22846. if (edgeIsBezier) {
  22847. tableEntry.hasBezier = true;
  22848. }
  22849. }
  22850. // for each pair (src, tgt), create the ctrl pts
  22851. // Nested for loop is OK; total number of iterations for both loops = edgeCount
  22852. var _loop = function _loop() {
  22853. var _pairIds$p = pairIds[p],
  22854. pairId = _pairIds$p.pairId,
  22855. edgeIsUnbundled = _pairIds$p.edgeIsUnbundled;
  22856. var key = getKey(pairId, edgeIsUnbundled);
  22857. var pairInfo = hashTable.get(key);
  22858. var swappedpairInfo;
  22859. if (!pairInfo.hasUnbundled) {
  22860. var pllEdges = pairInfo.eles[0].parallelEdges().filter(function (e) {
  22861. return e.isBundledBezier();
  22862. });
  22863. clearArray(pairInfo.eles);
  22864. pllEdges.forEach(function (edge) {
  22865. return pairInfo.eles.push(edge);
  22866. });
  22867. // for each pair id, the edges should be sorted by index
  22868. pairInfo.eles.sort(function (edge1, edge2) {
  22869. return edge1.poolIndex() - edge2.poolIndex();
  22870. });
  22871. }
  22872. var firstEdge = pairInfo.eles[0];
  22873. var src = firstEdge.source();
  22874. var tgt = firstEdge.target();
  22875. // make sure src/tgt distinction is consistent w.r.t. pairId
  22876. if (src.poolIndex() > tgt.poolIndex()) {
  22877. var temp = src;
  22878. src = tgt;
  22879. tgt = temp;
  22880. }
  22881. var srcPos = pairInfo.srcPos = src.position();
  22882. var tgtPos = pairInfo.tgtPos = tgt.position();
  22883. var srcW = pairInfo.srcW = src.outerWidth();
  22884. var srcH = pairInfo.srcH = src.outerHeight();
  22885. var tgtW = pairInfo.tgtW = tgt.outerWidth();
  22886. var tgtH = pairInfo.tgtH = tgt.outerHeight();
  22887. var srcShape = pairInfo.srcShape = r.nodeShapes[_this.getNodeShape(src)];
  22888. var tgtShape = pairInfo.tgtShape = r.nodeShapes[_this.getNodeShape(tgt)];
  22889. var srcCornerRadius = pairInfo.srcCornerRadius = src.pstyle('corner-radius').value === 'auto' ? 'auto' : src.pstyle('corner-radius').pfValue;
  22890. var tgtCornerRadius = pairInfo.tgtCornerRadius = tgt.pstyle('corner-radius').value === 'auto' ? 'auto' : tgt.pstyle('corner-radius').pfValue;
  22891. var tgtRs = pairInfo.tgtRs = tgt._private.rscratch;
  22892. var srcRs = pairInfo.srcRs = src._private.rscratch;
  22893. pairInfo.dirCounts = {
  22894. 'north': 0,
  22895. 'west': 0,
  22896. 'south': 0,
  22897. 'east': 0,
  22898. 'northwest': 0,
  22899. 'southwest': 0,
  22900. 'northeast': 0,
  22901. 'southeast': 0
  22902. };
  22903. for (var _i2 = 0; _i2 < pairInfo.eles.length; _i2++) {
  22904. var _edge = pairInfo.eles[_i2];
  22905. var rs = _edge[0]._private.rscratch;
  22906. var _curveStyle = _edge.pstyle('curve-style').value;
  22907. var _edgeIsUnbundled = _curveStyle === 'unbundled-bezier' || endsWith(_curveStyle, 'segments') || endsWith(_curveStyle, 'taxi');
  22908. // whether the normalised pair order is the reverse of the edge's src-tgt order
  22909. var edgeIsSwapped = !src.same(_edge.source());
  22910. if (!pairInfo.calculatedIntersection && src !== tgt && (pairInfo.hasBezier || pairInfo.hasUnbundled)) {
  22911. pairInfo.calculatedIntersection = true;
  22912. // pt outside src shape to calc distance/displacement from src to tgt
  22913. var srcOutside = srcShape.intersectLine(srcPos.x, srcPos.y, srcW, srcH, tgtPos.x, tgtPos.y, 0, srcCornerRadius, srcRs);
  22914. var srcIntn = pairInfo.srcIntn = srcOutside;
  22915. // pt outside tgt shape to calc distance/displacement from src to tgt
  22916. var tgtOutside = tgtShape.intersectLine(tgtPos.x, tgtPos.y, tgtW, tgtH, srcPos.x, srcPos.y, 0, tgtCornerRadius, tgtRs);
  22917. var tgtIntn = pairInfo.tgtIntn = tgtOutside;
  22918. var intersectionPts = pairInfo.intersectionPts = {
  22919. x1: srcOutside[0],
  22920. x2: tgtOutside[0],
  22921. y1: srcOutside[1],
  22922. y2: tgtOutside[1]
  22923. };
  22924. var posPts = pairInfo.posPts = {
  22925. x1: srcPos.x,
  22926. x2: tgtPos.x,
  22927. y1: srcPos.y,
  22928. y2: tgtPos.y
  22929. };
  22930. var dy = tgtOutside[1] - srcOutside[1];
  22931. var dx = tgtOutside[0] - srcOutside[0];
  22932. var l = Math.sqrt(dx * dx + dy * dy);
  22933. if (number$1(l) && l >= AVOID_IMPOSSIBLE_BEZIER_CONSTANT_L) ; else {
  22934. l = Math.sqrt(Math.max(dx * dx, AVOID_IMPOSSIBLE_BEZIER_CONSTANT) + Math.max(dy * dy, AVOID_IMPOSSIBLE_BEZIER_CONSTANT));
  22935. }
  22936. var vector = pairInfo.vector = {
  22937. x: dx,
  22938. y: dy
  22939. };
  22940. var vectorNorm = pairInfo.vectorNorm = {
  22941. x: vector.x / l,
  22942. y: vector.y / l
  22943. };
  22944. var vectorNormInverse = {
  22945. x: -vectorNorm.y,
  22946. y: vectorNorm.x
  22947. };
  22948. // if node shapes overlap, then no ctrl pts to draw
  22949. 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);
  22950. pairInfo.vectorNormInverse = vectorNormInverse;
  22951. swappedpairInfo = {
  22952. nodesOverlap: pairInfo.nodesOverlap,
  22953. dirCounts: pairInfo.dirCounts,
  22954. calculatedIntersection: true,
  22955. hasBezier: pairInfo.hasBezier,
  22956. hasUnbundled: pairInfo.hasUnbundled,
  22957. eles: pairInfo.eles,
  22958. srcPos: tgtPos,
  22959. srcRs: tgtRs,
  22960. tgtPos: srcPos,
  22961. tgtRs: srcRs,
  22962. srcW: tgtW,
  22963. srcH: tgtH,
  22964. tgtW: srcW,
  22965. tgtH: srcH,
  22966. srcIntn: tgtIntn,
  22967. tgtIntn: srcIntn,
  22968. srcShape: tgtShape,
  22969. tgtShape: srcShape,
  22970. posPts: {
  22971. x1: posPts.x2,
  22972. y1: posPts.y2,
  22973. x2: posPts.x1,
  22974. y2: posPts.y1
  22975. },
  22976. intersectionPts: {
  22977. x1: intersectionPts.x2,
  22978. y1: intersectionPts.y2,
  22979. x2: intersectionPts.x1,
  22980. y2: intersectionPts.y1
  22981. },
  22982. vector: {
  22983. x: -vector.x,
  22984. y: -vector.y
  22985. },
  22986. vectorNorm: {
  22987. x: -vectorNorm.x,
  22988. y: -vectorNorm.y
  22989. },
  22990. vectorNormInverse: {
  22991. x: -vectorNormInverse.x,
  22992. y: -vectorNormInverse.y
  22993. }
  22994. };
  22995. }
  22996. var passedPairInfo = edgeIsSwapped ? swappedpairInfo : pairInfo;
  22997. rs.nodesOverlap = passedPairInfo.nodesOverlap;
  22998. rs.srcIntn = passedPairInfo.srcIntn;
  22999. rs.tgtIntn = passedPairInfo.tgtIntn;
  23000. rs.isRound = _curveStyle.startsWith('round');
  23001. if (hasCompounds && (src.isParent() || src.isChild() || tgt.isParent() || tgt.isChild()) && (src.parents().anySame(tgt) || tgt.parents().anySame(src) || src.same(tgt) && src.isParent())) {
  23002. _this.findCompoundLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
  23003. } else if (src === tgt) {
  23004. _this.findLoopPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled);
  23005. } else if (_curveStyle.endsWith('segments')) {
  23006. _this.findSegmentsPoints(_edge, passedPairInfo);
  23007. } else if (_curveStyle.endsWith('taxi')) {
  23008. _this.findTaxiPoints(_edge, passedPairInfo);
  23009. } else if (_curveStyle === 'straight' || !_edgeIsUnbundled && pairInfo.eles.length % 2 === 1 && _i2 === Math.floor(pairInfo.eles.length / 2)) {
  23010. _this.findStraightEdgePoints(_edge);
  23011. } else {
  23012. _this.findBezierPoints(_edge, passedPairInfo, _i2, _edgeIsUnbundled, edgeIsSwapped);
  23013. }
  23014. _this.findEndpoints(_edge);
  23015. _this.tryToCorrectInvalidPoints(_edge, passedPairInfo);
  23016. _this.checkForInvalidEdgeWarning(_edge);
  23017. _this.storeAllpts(_edge);
  23018. _this.storeEdgeProjections(_edge);
  23019. _this.calculateArrowAngles(_edge);
  23020. _this.recalculateEdgeLabelProjections(_edge);
  23021. _this.calculateLabelAngles(_edge);
  23022. } // for pair edges
  23023. };
  23024. for (var p = 0; p < pairIds.length; p++) {
  23025. _loop();
  23026. } // for pair ids
  23027. // haystacks avoid the expense of pairInfo stuff (intersections etc.)
  23028. this.findHaystackPoints(haystackEdges);
  23029. };
  23030. function getPts(pts) {
  23031. var retPts = [];
  23032. if (pts == null) {
  23033. return;
  23034. }
  23035. for (var i = 0; i < pts.length; i += 2) {
  23036. var x = pts[i];
  23037. var y = pts[i + 1];
  23038. retPts.push({
  23039. x: x,
  23040. y: y
  23041. });
  23042. }
  23043. return retPts;
  23044. }
  23045. BRp$c.getSegmentPoints = function (edge) {
  23046. var rs = edge[0]._private.rscratch;
  23047. this.recalculateRenderedStyle(edge);
  23048. var type = rs.edgeType;
  23049. if (type === 'segments') {
  23050. return getPts(rs.segpts);
  23051. }
  23052. };
  23053. BRp$c.getControlPoints = function (edge) {
  23054. var rs = edge[0]._private.rscratch;
  23055. this.recalculateRenderedStyle(edge);
  23056. var type = rs.edgeType;
  23057. if (type === 'bezier' || type === 'multibezier' || type === 'self' || type === 'compound') {
  23058. return getPts(rs.ctrlpts);
  23059. }
  23060. };
  23061. BRp$c.getEdgeMidpoint = function (edge) {
  23062. var rs = edge[0]._private.rscratch;
  23063. this.recalculateRenderedStyle(edge);
  23064. return {
  23065. x: rs.midX,
  23066. y: rs.midY
  23067. };
  23068. };
  23069. var BRp$b = {};
  23070. BRp$b.manualEndptToPx = function (node, prop) {
  23071. var r = this;
  23072. var npos = node.position();
  23073. var w = node.outerWidth();
  23074. var h = node.outerHeight();
  23075. var rs = node._private.rscratch;
  23076. if (prop.value.length === 2) {
  23077. var p = [prop.pfValue[0], prop.pfValue[1]];
  23078. if (prop.units[0] === '%') {
  23079. p[0] = p[0] * w;
  23080. }
  23081. if (prop.units[1] === '%') {
  23082. p[1] = p[1] * h;
  23083. }
  23084. p[0] += npos.x;
  23085. p[1] += npos.y;
  23086. return p;
  23087. } else {
  23088. var angle = prop.pfValue[0];
  23089. angle = -Math.PI / 2 + angle; // start at 12 o'clock
  23090. var l = 2 * Math.max(w, h);
  23091. var _p = [npos.x + Math.cos(angle) * l, npos.y + Math.sin(angle) * l];
  23092. 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);
  23093. }
  23094. };
  23095. BRp$b.findEndpoints = function (edge) {
  23096. var _ref, _tgtManEndpt$pfValue, _ref2, _srcManEndpt$pfValue;
  23097. var r = this;
  23098. var intersect;
  23099. var source = edge.source()[0];
  23100. var target = edge.target()[0];
  23101. var srcPos = source.position();
  23102. var tgtPos = target.position();
  23103. var tgtArShape = edge.pstyle('target-arrow-shape').value;
  23104. var srcArShape = edge.pstyle('source-arrow-shape').value;
  23105. var tgtDist = edge.pstyle('target-distance-from-node').pfValue;
  23106. var srcDist = edge.pstyle('source-distance-from-node').pfValue;
  23107. var srcRs = source._private.rscratch;
  23108. var tgtRs = target._private.rscratch;
  23109. var curveStyle = edge.pstyle('curve-style').value;
  23110. var rs = edge._private.rscratch;
  23111. var et = rs.edgeType;
  23112. var taxi = endsWith(curveStyle, 'taxi'); // Covers taxi and round-taxi
  23113. var self = et === 'self' || et === 'compound';
  23114. var bezier = et === 'bezier' || et === 'multibezier' || self;
  23115. var multi = et !== 'bezier';
  23116. var lines = et === 'straight' || et === 'segments';
  23117. var segments = et === 'segments';
  23118. var hasEndpts = bezier || multi || lines;
  23119. var overrideEndpts = self || taxi;
  23120. var srcManEndpt = edge.pstyle('source-endpoint');
  23121. var srcManEndptVal = overrideEndpts ? 'outside-to-node' : srcManEndpt.value;
  23122. var srcCornerRadius = source.pstyle('corner-radius').value === 'auto' ? 'auto' : source.pstyle('corner-radius').pfValue;
  23123. var tgtManEndpt = edge.pstyle('target-endpoint');
  23124. var tgtManEndptVal = overrideEndpts ? 'outside-to-node' : tgtManEndpt.value;
  23125. var tgtCornerRadius = target.pstyle('corner-radius').value === 'auto' ? 'auto' : target.pstyle('corner-radius').pfValue;
  23126. rs.srcManEndpt = srcManEndpt;
  23127. rs.tgtManEndpt = tgtManEndpt;
  23128. var p1; // last known point of edge on target side
  23129. var p2; // last known point of edge on source side
  23130. var p1_i; // point to intersect with target shape
  23131. var p2_i; // point to intersect with source shape
  23132. 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];
  23133. 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];
  23134. if (bezier) {
  23135. var cpStart = [rs.ctrlpts[0], rs.ctrlpts[1]];
  23136. var cpEnd = multi ? [rs.ctrlpts[rs.ctrlpts.length - 2], rs.ctrlpts[rs.ctrlpts.length - 1]] : cpStart;
  23137. p1 = cpEnd;
  23138. p2 = cpStart;
  23139. } else if (lines) {
  23140. var srcArrowFromPt = !segments ? [tgtPos.x + tgtManEndptPt[0], tgtPos.y + tgtManEndptPt[1]] : rs.segpts.slice(0, 2);
  23141. var tgtArrowFromPt = !segments ? [srcPos.x + srcManEndptPt[0], srcPos.y + srcManEndptPt[1]] : rs.segpts.slice(rs.segpts.length - 2);
  23142. p1 = tgtArrowFromPt;
  23143. p2 = srcArrowFromPt;
  23144. }
  23145. if (tgtManEndptVal === 'inside-to-node') {
  23146. intersect = [tgtPos.x, tgtPos.y];
  23147. } else if (tgtManEndpt.units) {
  23148. intersect = this.manualEndptToPx(target, tgtManEndpt);
  23149. } else if (tgtManEndptVal === 'outside-to-line') {
  23150. intersect = rs.tgtIntn; // use cached value from ctrlpt calc
  23151. } else {
  23152. if (tgtManEndptVal === 'outside-to-node' || tgtManEndptVal === 'outside-to-node-or-label') {
  23153. p1_i = p1;
  23154. } else if (tgtManEndptVal === 'outside-to-line' || tgtManEndptVal === 'outside-to-line-or-label') {
  23155. p1_i = [srcPos.x, srcPos.y];
  23156. }
  23157. intersect = r.nodeShapes[this.getNodeShape(target)].intersectLine(tgtPos.x, tgtPos.y, target.outerWidth(), target.outerHeight(), p1_i[0], p1_i[1], 0, tgtCornerRadius, tgtRs);
  23158. if (tgtManEndptVal === 'outside-to-node-or-label' || tgtManEndptVal === 'outside-to-line-or-label') {
  23159. var trs = target._private.rscratch;
  23160. var lw = trs.labelWidth;
  23161. var lh = trs.labelHeight;
  23162. var lx = trs.labelX;
  23163. var ly = trs.labelY;
  23164. var lw2 = lw / 2;
  23165. var lh2 = lh / 2;
  23166. var va = target.pstyle('text-valign').value;
  23167. if (va === 'top') {
  23168. ly -= lh2;
  23169. } else if (va === 'bottom') {
  23170. ly += lh2;
  23171. }
  23172. var ha = target.pstyle('text-halign').value;
  23173. if (ha === 'left') {
  23174. lx -= lw2;
  23175. } else if (ha === 'right') {
  23176. lx += lw2;
  23177. }
  23178. 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);
  23179. if (labelIntersect.length > 0) {
  23180. var refPt = srcPos;
  23181. var intSqdist = sqdist(refPt, array2point(intersect));
  23182. var labIntSqdist = sqdist(refPt, array2point(labelIntersect));
  23183. var minSqDist = intSqdist;
  23184. if (labIntSqdist < intSqdist) {
  23185. intersect = labelIntersect;
  23186. minSqDist = labIntSqdist;
  23187. }
  23188. if (labelIntersect.length > 2) {
  23189. var labInt2SqDist = sqdist(refPt, {
  23190. x: labelIntersect[2],
  23191. y: labelIntersect[3]
  23192. });
  23193. if (labInt2SqDist < minSqDist) {
  23194. intersect = [labelIntersect[2], labelIntersect[3]];
  23195. }
  23196. }
  23197. }
  23198. }
  23199. }
  23200. var arrowEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].spacing(edge) + tgtDist);
  23201. var edgeEnd = shortenIntersection(intersect, p1, r.arrowShapes[tgtArShape].gap(edge) + tgtDist);
  23202. rs.endX = edgeEnd[0];
  23203. rs.endY = edgeEnd[1];
  23204. rs.arrowEndX = arrowEnd[0];
  23205. rs.arrowEndY = arrowEnd[1];
  23206. if (srcManEndptVal === 'inside-to-node') {
  23207. intersect = [srcPos.x, srcPos.y];
  23208. } else if (srcManEndpt.units) {
  23209. intersect = this.manualEndptToPx(source, srcManEndpt);
  23210. } else if (srcManEndptVal === 'outside-to-line') {
  23211. intersect = rs.srcIntn; // use cached value from ctrlpt calc
  23212. } else {
  23213. if (srcManEndptVal === 'outside-to-node' || srcManEndptVal === 'outside-to-node-or-label') {
  23214. p2_i = p2;
  23215. } else if (srcManEndptVal === 'outside-to-line' || srcManEndptVal === 'outside-to-line-or-label') {
  23216. p2_i = [tgtPos.x, tgtPos.y];
  23217. }
  23218. intersect = r.nodeShapes[this.getNodeShape(source)].intersectLine(srcPos.x, srcPos.y, source.outerWidth(), source.outerHeight(), p2_i[0], p2_i[1], 0, srcCornerRadius, srcRs);
  23219. if (srcManEndptVal === 'outside-to-node-or-label' || srcManEndptVal === 'outside-to-line-or-label') {
  23220. var srs = source._private.rscratch;
  23221. var _lw = srs.labelWidth;
  23222. var _lh = srs.labelHeight;
  23223. var _lx = srs.labelX;
  23224. var _ly = srs.labelY;
  23225. var _lw2 = _lw / 2;
  23226. var _lh2 = _lh / 2;
  23227. var _va = source.pstyle('text-valign').value;
  23228. if (_va === 'top') {
  23229. _ly -= _lh2;
  23230. } else if (_va === 'bottom') {
  23231. _ly += _lh2;
  23232. }
  23233. var _ha = source.pstyle('text-halign').value;
  23234. if (_ha === 'left') {
  23235. _lx -= _lw2;
  23236. } else if (_ha === 'right') {
  23237. _lx += _lw2;
  23238. }
  23239. 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);
  23240. if (_labelIntersect.length > 0) {
  23241. var _refPt = tgtPos;
  23242. var _intSqdist = sqdist(_refPt, array2point(intersect));
  23243. var _labIntSqdist = sqdist(_refPt, array2point(_labelIntersect));
  23244. var _minSqDist = _intSqdist;
  23245. if (_labIntSqdist < _intSqdist) {
  23246. intersect = [_labelIntersect[0], _labelIntersect[1]];
  23247. _minSqDist = _labIntSqdist;
  23248. }
  23249. if (_labelIntersect.length > 2) {
  23250. var _labInt2SqDist = sqdist(_refPt, {
  23251. x: _labelIntersect[2],
  23252. y: _labelIntersect[3]
  23253. });
  23254. if (_labInt2SqDist < _minSqDist) {
  23255. intersect = [_labelIntersect[2], _labelIntersect[3]];
  23256. }
  23257. }
  23258. }
  23259. }
  23260. }
  23261. var arrowStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].spacing(edge) + srcDist);
  23262. var edgeStart = shortenIntersection(intersect, p2, r.arrowShapes[srcArShape].gap(edge) + srcDist);
  23263. rs.startX = edgeStart[0];
  23264. rs.startY = edgeStart[1];
  23265. rs.arrowStartX = arrowStart[0];
  23266. rs.arrowStartY = arrowStart[1];
  23267. if (hasEndpts) {
  23268. if (!number$1(rs.startX) || !number$1(rs.startY) || !number$1(rs.endX) || !number$1(rs.endY)) {
  23269. rs.badLine = true;
  23270. } else {
  23271. rs.badLine = false;
  23272. }
  23273. }
  23274. };
  23275. BRp$b.getSourceEndpoint = function (edge) {
  23276. var rs = edge[0]._private.rscratch;
  23277. this.recalculateRenderedStyle(edge);
  23278. switch (rs.edgeType) {
  23279. case 'haystack':
  23280. return {
  23281. x: rs.haystackPts[0],
  23282. y: rs.haystackPts[1]
  23283. };
  23284. default:
  23285. return {
  23286. x: rs.arrowStartX,
  23287. y: rs.arrowStartY
  23288. };
  23289. }
  23290. };
  23291. BRp$b.getTargetEndpoint = function (edge) {
  23292. var rs = edge[0]._private.rscratch;
  23293. this.recalculateRenderedStyle(edge);
  23294. switch (rs.edgeType) {
  23295. case 'haystack':
  23296. return {
  23297. x: rs.haystackPts[2],
  23298. y: rs.haystackPts[3]
  23299. };
  23300. default:
  23301. return {
  23302. x: rs.arrowEndX,
  23303. y: rs.arrowEndY
  23304. };
  23305. }
  23306. };
  23307. var BRp$a = {};
  23308. function pushBezierPts(r, edge, pts) {
  23309. var qbezierAt$1 = function qbezierAt$1(p1, p2, p3, t) {
  23310. return qbezierAt(p1, p2, p3, t);
  23311. };
  23312. var _p = edge._private;
  23313. var bpts = _p.rstyle.bezierPts;
  23314. for (var i = 0; i < r.bezierProjPcts.length; i++) {
  23315. var p = r.bezierProjPcts[i];
  23316. bpts.push({
  23317. x: qbezierAt$1(pts[0], pts[2], pts[4], p),
  23318. y: qbezierAt$1(pts[1], pts[3], pts[5], p)
  23319. });
  23320. }
  23321. }
  23322. BRp$a.storeEdgeProjections = function (edge) {
  23323. var _p = edge._private;
  23324. var rs = _p.rscratch;
  23325. var et = rs.edgeType;
  23326. // clear the cached points state
  23327. _p.rstyle.bezierPts = null;
  23328. _p.rstyle.linePts = null;
  23329. _p.rstyle.haystackPts = null;
  23330. if (et === 'multibezier' || et === 'bezier' || et === 'self' || et === 'compound') {
  23331. _p.rstyle.bezierPts = [];
  23332. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  23333. pushBezierPts(this, edge, rs.allpts.slice(i, i + 6));
  23334. }
  23335. } else if (et === 'segments') {
  23336. var lpts = _p.rstyle.linePts = [];
  23337. for (var i = 0; i + 1 < rs.allpts.length; i += 2) {
  23338. lpts.push({
  23339. x: rs.allpts[i],
  23340. y: rs.allpts[i + 1]
  23341. });
  23342. }
  23343. } else if (et === 'haystack') {
  23344. var hpts = rs.haystackPts;
  23345. _p.rstyle.haystackPts = [{
  23346. x: hpts[0],
  23347. y: hpts[1]
  23348. }, {
  23349. x: hpts[2],
  23350. y: hpts[3]
  23351. }];
  23352. }
  23353. _p.rstyle.arrowWidth = this.getArrowWidth(edge.pstyle('width').pfValue, edge.pstyle('arrow-scale').value) * this.arrowShapeWidth;
  23354. };
  23355. BRp$a.recalculateEdgeProjections = function (edges) {
  23356. this.findEdgeControlPoints(edges);
  23357. };
  23358. var BRp$9 = {};
  23359. BRp$9.recalculateNodeLabelProjection = function (node) {
  23360. var content = node.pstyle('label').strValue;
  23361. if (emptyString(content)) {
  23362. return;
  23363. }
  23364. var textX, textY;
  23365. var _p = node._private;
  23366. var nodeWidth = node.width();
  23367. var nodeHeight = node.height();
  23368. var padding = node.padding();
  23369. var nodePos = node.position();
  23370. var textHalign = node.pstyle('text-halign').strValue;
  23371. var textValign = node.pstyle('text-valign').strValue;
  23372. var rs = _p.rscratch;
  23373. var rstyle = _p.rstyle;
  23374. switch (textHalign) {
  23375. case 'left':
  23376. textX = nodePos.x - nodeWidth / 2 - padding;
  23377. break;
  23378. case 'right':
  23379. textX = nodePos.x + nodeWidth / 2 + padding;
  23380. break;
  23381. default:
  23382. // e.g. center
  23383. textX = nodePos.x;
  23384. }
  23385. switch (textValign) {
  23386. case 'top':
  23387. textY = nodePos.y - nodeHeight / 2 - padding;
  23388. break;
  23389. case 'bottom':
  23390. textY = nodePos.y + nodeHeight / 2 + padding;
  23391. break;
  23392. default:
  23393. // e.g. middle
  23394. textY = nodePos.y;
  23395. }
  23396. rs.labelX = textX;
  23397. rs.labelY = textY;
  23398. rstyle.labelX = textX;
  23399. rstyle.labelY = textY;
  23400. this.calculateLabelAngles(node);
  23401. this.applyLabelDimensions(node);
  23402. };
  23403. var lineAngleFromDelta = function lineAngleFromDelta(dx, dy) {
  23404. var angle = Math.atan(dy / dx);
  23405. if (dx === 0 && angle < 0) {
  23406. angle = angle * -1;
  23407. }
  23408. return angle;
  23409. };
  23410. var lineAngle = function lineAngle(p0, p1) {
  23411. var dx = p1.x - p0.x;
  23412. var dy = p1.y - p0.y;
  23413. return lineAngleFromDelta(dx, dy);
  23414. };
  23415. var bezierAngle = function bezierAngle(p0, p1, p2, t) {
  23416. var t0 = bound(0, t - 0.001, 1);
  23417. var t1 = bound(0, t + 0.001, 1);
  23418. var lp0 = qbezierPtAt(p0, p1, p2, t0);
  23419. var lp1 = qbezierPtAt(p0, p1, p2, t1);
  23420. return lineAngle(lp0, lp1);
  23421. };
  23422. BRp$9.recalculateEdgeLabelProjections = function (edge) {
  23423. var p;
  23424. var _p = edge._private;
  23425. var rs = _p.rscratch;
  23426. var r = this;
  23427. var content = {
  23428. mid: edge.pstyle('label').strValue,
  23429. source: edge.pstyle('source-label').strValue,
  23430. target: edge.pstyle('target-label').strValue
  23431. };
  23432. if (content.mid || content.source || content.target) ; else {
  23433. return; // no labels => no calcs
  23434. }
  23435. // add center point to style so bounding box calculations can use it
  23436. //
  23437. p = {
  23438. x: rs.midX,
  23439. y: rs.midY
  23440. };
  23441. var setRs = function setRs(propName, prefix, value) {
  23442. setPrefixedProperty(_p.rscratch, propName, prefix, value);
  23443. setPrefixedProperty(_p.rstyle, propName, prefix, value);
  23444. };
  23445. setRs('labelX', null, p.x);
  23446. setRs('labelY', null, p.y);
  23447. var midAngle = lineAngleFromDelta(rs.midDispX, rs.midDispY);
  23448. setRs('labelAutoAngle', null, midAngle);
  23449. var _createControlPointInfo = function createControlPointInfo() {
  23450. if (_createControlPointInfo.cache) {
  23451. return _createControlPointInfo.cache;
  23452. } // use cache so only 1x per edge
  23453. var ctrlpts = [];
  23454. // store each ctrlpt info init
  23455. for (var i = 0; i + 5 < rs.allpts.length; i += 4) {
  23456. var p0 = {
  23457. x: rs.allpts[i],
  23458. y: rs.allpts[i + 1]
  23459. };
  23460. var p1 = {
  23461. x: rs.allpts[i + 2],
  23462. y: rs.allpts[i + 3]
  23463. }; // ctrlpt
  23464. var p2 = {
  23465. x: rs.allpts[i + 4],
  23466. y: rs.allpts[i + 5]
  23467. };
  23468. ctrlpts.push({
  23469. p0: p0,
  23470. p1: p1,
  23471. p2: p2,
  23472. startDist: 0,
  23473. length: 0,
  23474. segments: []
  23475. });
  23476. }
  23477. var bpts = _p.rstyle.bezierPts;
  23478. var nProjs = r.bezierProjPcts.length;
  23479. function addSegment(cp, p0, p1, t0, t1) {
  23480. var length = dist(p0, p1);
  23481. var prevSegment = cp.segments[cp.segments.length - 1];
  23482. var segment = {
  23483. p0: p0,
  23484. p1: p1,
  23485. t0: t0,
  23486. t1: t1,
  23487. startDist: prevSegment ? prevSegment.startDist + prevSegment.length : 0,
  23488. length: length
  23489. };
  23490. cp.segments.push(segment);
  23491. cp.length += length;
  23492. }
  23493. // update each ctrlpt with segment info
  23494. for (var _i = 0; _i < ctrlpts.length; _i++) {
  23495. var cp = ctrlpts[_i];
  23496. var prevCp = ctrlpts[_i - 1];
  23497. if (prevCp) {
  23498. cp.startDist = prevCp.startDist + prevCp.length;
  23499. }
  23500. addSegment(cp, cp.p0, bpts[_i * nProjs], 0, r.bezierProjPcts[0]); // first
  23501. for (var j = 0; j < nProjs - 1; j++) {
  23502. addSegment(cp, bpts[_i * nProjs + j], bpts[_i * nProjs + j + 1], r.bezierProjPcts[j], r.bezierProjPcts[j + 1]);
  23503. }
  23504. addSegment(cp, bpts[_i * nProjs + nProjs - 1], cp.p2, r.bezierProjPcts[nProjs - 1], 1); // last
  23505. }
  23506. return _createControlPointInfo.cache = ctrlpts;
  23507. };
  23508. var calculateEndProjection = function calculateEndProjection(prefix) {
  23509. var angle;
  23510. var isSrc = prefix === 'source';
  23511. if (!content[prefix]) {
  23512. return;
  23513. }
  23514. var offset = edge.pstyle(prefix + '-text-offset').pfValue;
  23515. switch (rs.edgeType) {
  23516. case 'self':
  23517. case 'compound':
  23518. case 'bezier':
  23519. case 'multibezier':
  23520. {
  23521. var cps = _createControlPointInfo();
  23522. var selected;
  23523. var startDist = 0;
  23524. var totalDist = 0;
  23525. // find the segment we're on
  23526. for (var i = 0; i < cps.length; i++) {
  23527. var _cp = cps[isSrc ? i : cps.length - 1 - i];
  23528. for (var j = 0; j < _cp.segments.length; j++) {
  23529. var _seg = _cp.segments[isSrc ? j : _cp.segments.length - 1 - j];
  23530. var lastSeg = i === cps.length - 1 && j === _cp.segments.length - 1;
  23531. startDist = totalDist;
  23532. totalDist += _seg.length;
  23533. if (totalDist >= offset || lastSeg) {
  23534. selected = {
  23535. cp: _cp,
  23536. segment: _seg
  23537. };
  23538. break;
  23539. }
  23540. }
  23541. if (selected) {
  23542. break;
  23543. }
  23544. }
  23545. var cp = selected.cp;
  23546. var seg = selected.segment;
  23547. var tSegment = (offset - startDist) / seg.length;
  23548. var segDt = seg.t1 - seg.t0;
  23549. var t = isSrc ? seg.t0 + segDt * tSegment : seg.t1 - segDt * tSegment;
  23550. t = bound(0, t, 1);
  23551. p = qbezierPtAt(cp.p0, cp.p1, cp.p2, t);
  23552. angle = bezierAngle(cp.p0, cp.p1, cp.p2, t);
  23553. break;
  23554. }
  23555. case 'straight':
  23556. case 'segments':
  23557. case 'haystack':
  23558. {
  23559. var d = 0,
  23560. di,
  23561. d0;
  23562. var p0, p1;
  23563. var l = rs.allpts.length;
  23564. for (var _i2 = 0; _i2 + 3 < l; _i2 += 2) {
  23565. if (isSrc) {
  23566. p0 = {
  23567. x: rs.allpts[_i2],
  23568. y: rs.allpts[_i2 + 1]
  23569. };
  23570. p1 = {
  23571. x: rs.allpts[_i2 + 2],
  23572. y: rs.allpts[_i2 + 3]
  23573. };
  23574. } else {
  23575. p0 = {
  23576. x: rs.allpts[l - 2 - _i2],
  23577. y: rs.allpts[l - 1 - _i2]
  23578. };
  23579. p1 = {
  23580. x: rs.allpts[l - 4 - _i2],
  23581. y: rs.allpts[l - 3 - _i2]
  23582. };
  23583. }
  23584. di = dist(p0, p1);
  23585. d0 = d;
  23586. d += di;
  23587. if (d >= offset) {
  23588. break;
  23589. }
  23590. }
  23591. var pD = offset - d0;
  23592. var _t = pD / di;
  23593. _t = bound(0, _t, 1);
  23594. p = lineAt(p0, p1, _t);
  23595. angle = lineAngle(p0, p1);
  23596. break;
  23597. }
  23598. }
  23599. setRs('labelX', prefix, p.x);
  23600. setRs('labelY', prefix, p.y);
  23601. setRs('labelAutoAngle', prefix, angle);
  23602. };
  23603. calculateEndProjection('source');
  23604. calculateEndProjection('target');
  23605. this.applyLabelDimensions(edge);
  23606. };
  23607. BRp$9.applyLabelDimensions = function (ele) {
  23608. this.applyPrefixedLabelDimensions(ele);
  23609. if (ele.isEdge()) {
  23610. this.applyPrefixedLabelDimensions(ele, 'source');
  23611. this.applyPrefixedLabelDimensions(ele, 'target');
  23612. }
  23613. };
  23614. BRp$9.applyPrefixedLabelDimensions = function (ele, prefix) {
  23615. var _p = ele._private;
  23616. var text = this.getLabelText(ele, prefix);
  23617. var cacheKey = hashString(text, ele._private.labelDimsKey);
  23618. // save recalc if the label is the same as before
  23619. if (getPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix) === cacheKey) {
  23620. return; // then the label dimensions + text are the same
  23621. }
  23622. // save the key
  23623. setPrefixedProperty(_p.rscratch, 'prefixedLabelDimsKey', prefix, cacheKey);
  23624. var labelDims = this.calculateLabelDimensions(ele, text);
  23625. var lineHeight = ele.pstyle('line-height').pfValue;
  23626. var textWrap = ele.pstyle('text-wrap').strValue;
  23627. var lines = getPrefixedProperty(_p.rscratch, 'labelWrapCachedLines', prefix) || [];
  23628. var numLines = textWrap !== 'wrap' ? 1 : Math.max(lines.length, 1);
  23629. var normPerLineHeight = labelDims.height / numLines;
  23630. var labelLineHeight = normPerLineHeight * lineHeight;
  23631. var width = labelDims.width;
  23632. var height = labelDims.height + (numLines - 1) * (lineHeight - 1) * normPerLineHeight;
  23633. setPrefixedProperty(_p.rstyle, 'labelWidth', prefix, width);
  23634. setPrefixedProperty(_p.rscratch, 'labelWidth', prefix, width);
  23635. setPrefixedProperty(_p.rstyle, 'labelHeight', prefix, height);
  23636. setPrefixedProperty(_p.rscratch, 'labelHeight', prefix, height);
  23637. setPrefixedProperty(_p.rscratch, 'labelLineHeight', prefix, labelLineHeight);
  23638. };
  23639. BRp$9.getLabelText = function (ele, prefix) {
  23640. var _p = ele._private;
  23641. var pfd = prefix ? prefix + '-' : '';
  23642. var text = ele.pstyle(pfd + 'label').strValue;
  23643. var textTransform = ele.pstyle('text-transform').value;
  23644. var rscratch = function rscratch(propName, value) {
  23645. if (value) {
  23646. setPrefixedProperty(_p.rscratch, propName, prefix, value);
  23647. return value;
  23648. } else {
  23649. return getPrefixedProperty(_p.rscratch, propName, prefix);
  23650. }
  23651. };
  23652. // for empty text, skip all processing
  23653. if (!text) {
  23654. return '';
  23655. }
  23656. if (textTransform == 'none') ; else if (textTransform == 'uppercase') {
  23657. text = text.toUpperCase();
  23658. } else if (textTransform == 'lowercase') {
  23659. text = text.toLowerCase();
  23660. }
  23661. var wrapStyle = ele.pstyle('text-wrap').value;
  23662. if (wrapStyle === 'wrap') {
  23663. var labelKey = rscratch('labelKey');
  23664. // save recalc if the label is the same as before
  23665. if (labelKey != null && rscratch('labelWrapKey') === labelKey) {
  23666. return rscratch('labelWrapCachedText');
  23667. }
  23668. var zwsp = "\u200B";
  23669. var lines = text.split('\n');
  23670. var maxW = ele.pstyle('text-max-width').pfValue;
  23671. var overflow = ele.pstyle('text-overflow-wrap').value;
  23672. var overflowAny = overflow === 'anywhere';
  23673. var wrappedLines = [];
  23674. var separatorRegex = /[\s\u200b]+|$/g; // Include end of string to add last word
  23675. for (var l = 0; l < lines.length; l++) {
  23676. var line = lines[l];
  23677. var lineDims = this.calculateLabelDimensions(ele, line);
  23678. var lineW = lineDims.width;
  23679. if (overflowAny) {
  23680. var processedLine = line.split('').join(zwsp);
  23681. line = processedLine;
  23682. }
  23683. if (lineW > maxW) {
  23684. // line is too long
  23685. var separatorMatches = line.matchAll(separatorRegex);
  23686. var subline = '';
  23687. var previousIndex = 0;
  23688. // Add fake match
  23689. var _iterator = _createForOfIteratorHelper(separatorMatches),
  23690. _step;
  23691. try {
  23692. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  23693. var separatorMatch = _step.value;
  23694. var wordSeparator = separatorMatch[0];
  23695. var word = line.substring(previousIndex, separatorMatch.index);
  23696. previousIndex = separatorMatch.index + wordSeparator.length;
  23697. var testLine = subline.length === 0 ? word : subline + word + wordSeparator;
  23698. var testDims = this.calculateLabelDimensions(ele, testLine);
  23699. var testW = testDims.width;
  23700. if (testW <= maxW) {
  23701. // word fits on current line
  23702. subline += word + wordSeparator;
  23703. } else {
  23704. // word starts new line
  23705. if (subline) {
  23706. wrappedLines.push(subline);
  23707. }
  23708. subline = word + wordSeparator;
  23709. }
  23710. }
  23711. // if there's remaining text, put it in a wrapped line
  23712. } catch (err) {
  23713. _iterator.e(err);
  23714. } finally {
  23715. _iterator.f();
  23716. }
  23717. if (!subline.match(/^[\s\u200b]+$/)) {
  23718. wrappedLines.push(subline);
  23719. }
  23720. } else {
  23721. // line is already short enough
  23722. wrappedLines.push(line);
  23723. }
  23724. } // for
  23725. rscratch('labelWrapCachedLines', wrappedLines);
  23726. text = rscratch('labelWrapCachedText', wrappedLines.join('\n'));
  23727. rscratch('labelWrapKey', labelKey);
  23728. } else if (wrapStyle === 'ellipsis') {
  23729. var _maxW = ele.pstyle('text-max-width').pfValue;
  23730. var ellipsized = '';
  23731. var ellipsis = "\u2026";
  23732. var incLastCh = false;
  23733. if (this.calculateLabelDimensions(ele, text).width < _maxW) {
  23734. // the label already fits
  23735. return text;
  23736. }
  23737. for (var i = 0; i < text.length; i++) {
  23738. var widthWithNextCh = this.calculateLabelDimensions(ele, ellipsized + text[i] + ellipsis).width;
  23739. if (widthWithNextCh > _maxW) {
  23740. break;
  23741. }
  23742. ellipsized += text[i];
  23743. if (i === text.length - 1) {
  23744. incLastCh = true;
  23745. }
  23746. }
  23747. if (!incLastCh) {
  23748. ellipsized += ellipsis;
  23749. }
  23750. return ellipsized;
  23751. } // if ellipsize
  23752. return text;
  23753. };
  23754. BRp$9.getLabelJustification = function (ele) {
  23755. var justification = ele.pstyle('text-justification').strValue;
  23756. var textHalign = ele.pstyle('text-halign').strValue;
  23757. if (justification === 'auto') {
  23758. if (ele.isNode()) {
  23759. switch (textHalign) {
  23760. case 'left':
  23761. return 'right';
  23762. case 'right':
  23763. return 'left';
  23764. default:
  23765. return 'center';
  23766. }
  23767. } else {
  23768. return 'center';
  23769. }
  23770. } else {
  23771. return justification;
  23772. }
  23773. };
  23774. BRp$9.calculateLabelDimensions = function (ele, text) {
  23775. var r = this;
  23776. var containerWindow = r.cy.window();
  23777. var document = containerWindow.document;
  23778. var padding = 0; // add padding around text dims, as the measurement isn't that accurate
  23779. var fStyle = ele.pstyle('font-style').strValue;
  23780. var size = ele.pstyle('font-size').pfValue;
  23781. var family = ele.pstyle('font-family').strValue;
  23782. var weight = ele.pstyle('font-weight').strValue;
  23783. var canvas = this.labelCalcCanvas;
  23784. var c2d = this.labelCalcCanvasContext;
  23785. if (!canvas) {
  23786. canvas = this.labelCalcCanvas = document.createElement('canvas');
  23787. c2d = this.labelCalcCanvasContext = canvas.getContext('2d');
  23788. var ds = canvas.style;
  23789. ds.position = 'absolute';
  23790. ds.left = '-9999px';
  23791. ds.top = '-9999px';
  23792. ds.zIndex = '-1';
  23793. ds.visibility = 'hidden';
  23794. ds.pointerEvents = 'none';
  23795. }
  23796. c2d.font = "".concat(fStyle, " ").concat(weight, " ").concat(size, "px ").concat(family);
  23797. var width = 0;
  23798. var height = 0;
  23799. var lines = text.split('\n');
  23800. for (var i = 0; i < lines.length; i++) {
  23801. var line = lines[i];
  23802. var metrics = c2d.measureText(line);
  23803. var w = Math.ceil(metrics.width);
  23804. var h = size;
  23805. width = Math.max(w, width);
  23806. height += h;
  23807. }
  23808. width += padding;
  23809. height += padding;
  23810. return {
  23811. width: width,
  23812. height: height
  23813. };
  23814. };
  23815. BRp$9.calculateLabelAngle = function (ele, prefix) {
  23816. var _p = ele._private;
  23817. var rs = _p.rscratch;
  23818. var isEdge = ele.isEdge();
  23819. var prefixDash = prefix ? prefix + '-' : '';
  23820. var rot = ele.pstyle(prefixDash + 'text-rotation');
  23821. var rotStr = rot.strValue;
  23822. if (rotStr === 'none') {
  23823. return 0;
  23824. } else if (isEdge && rotStr === 'autorotate') {
  23825. return rs.labelAutoAngle;
  23826. } else if (rotStr === 'autorotate') {
  23827. return 0;
  23828. } else {
  23829. return rot.pfValue;
  23830. }
  23831. };
  23832. BRp$9.calculateLabelAngles = function (ele) {
  23833. var r = this;
  23834. var isEdge = ele.isEdge();
  23835. var _p = ele._private;
  23836. var rs = _p.rscratch;
  23837. rs.labelAngle = r.calculateLabelAngle(ele);
  23838. if (isEdge) {
  23839. rs.sourceLabelAngle = r.calculateLabelAngle(ele, 'source');
  23840. rs.targetLabelAngle = r.calculateLabelAngle(ele, 'target');
  23841. }
  23842. };
  23843. var BRp$8 = {};
  23844. var TOO_SMALL_CUT_RECT = 28;
  23845. var warnedCutRect = false;
  23846. BRp$8.getNodeShape = function (node) {
  23847. var r = this;
  23848. var shape = node.pstyle('shape').value;
  23849. if (shape === 'cutrectangle' && (node.width() < TOO_SMALL_CUT_RECT || node.height() < TOO_SMALL_CUT_RECT)) {
  23850. if (!warnedCutRect) {
  23851. warn('The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead');
  23852. warnedCutRect = true;
  23853. }
  23854. return 'rectangle';
  23855. }
  23856. if (node.isParent()) {
  23857. if (shape === 'rectangle' || shape === 'roundrectangle' || shape === 'round-rectangle' || shape === 'cutrectangle' || shape === 'cut-rectangle' || shape === 'barrel') {
  23858. return shape;
  23859. } else {
  23860. return 'rectangle';
  23861. }
  23862. }
  23863. if (shape === 'polygon') {
  23864. var points = node.pstyle('shape-polygon-points').value;
  23865. return r.nodeShapes.makePolygon(points).name;
  23866. }
  23867. return shape;
  23868. };
  23869. var BRp$7 = {};
  23870. BRp$7.registerCalculationListeners = function () {
  23871. var cy = this.cy;
  23872. var elesToUpdate = cy.collection();
  23873. var r = this;
  23874. var enqueue = function enqueue(eles) {
  23875. var dirtyStyleCaches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  23876. elesToUpdate.merge(eles);
  23877. if (dirtyStyleCaches) {
  23878. for (var i = 0; i < eles.length; i++) {
  23879. var ele = eles[i];
  23880. var _p = ele._private;
  23881. var rstyle = _p.rstyle;
  23882. rstyle.clean = false;
  23883. rstyle.cleanConnected = false;
  23884. }
  23885. }
  23886. };
  23887. r.binder(cy).on('bounds.* dirty.*', function onDirtyBounds(e) {
  23888. var ele = e.target;
  23889. enqueue(ele);
  23890. }).on('style.* background.*', function onDirtyStyle(e) {
  23891. var ele = e.target;
  23892. enqueue(ele, false);
  23893. });
  23894. var updateEleCalcs = function updateEleCalcs(willDraw) {
  23895. if (willDraw) {
  23896. var fns = r.onUpdateEleCalcsFns;
  23897. // because we need to have up-to-date style (e.g. stylesheet mappers)
  23898. // before calculating rendered style (and pstyle might not be called yet)
  23899. elesToUpdate.cleanStyle();
  23900. for (var i = 0; i < elesToUpdate.length; i++) {
  23901. var ele = elesToUpdate[i];
  23902. var rstyle = ele._private.rstyle;
  23903. if (ele.isNode() && !rstyle.cleanConnected) {
  23904. enqueue(ele.connectedEdges());
  23905. rstyle.cleanConnected = true;
  23906. }
  23907. }
  23908. if (fns) {
  23909. for (var _i = 0; _i < fns.length; _i++) {
  23910. var fn = fns[_i];
  23911. fn(willDraw, elesToUpdate);
  23912. }
  23913. }
  23914. r.recalculateRenderedStyle(elesToUpdate);
  23915. elesToUpdate = cy.collection();
  23916. }
  23917. };
  23918. r.flushRenderedStyleQueue = function () {
  23919. updateEleCalcs(true);
  23920. };
  23921. r.beforeRender(updateEleCalcs, r.beforeRenderPriorities.eleCalcs);
  23922. };
  23923. BRp$7.onUpdateEleCalcs = function (fn) {
  23924. var fns = this.onUpdateEleCalcsFns = this.onUpdateEleCalcsFns || [];
  23925. fns.push(fn);
  23926. };
  23927. BRp$7.recalculateRenderedStyle = function (eles, useCache) {
  23928. var isCleanConnected = function isCleanConnected(ele) {
  23929. return ele._private.rstyle.cleanConnected;
  23930. };
  23931. if (eles.length === 0) {
  23932. return;
  23933. }
  23934. var edges = [];
  23935. var nodes = [];
  23936. // the renderer can't be used for calcs when destroyed, e.g. ele.boundingBox()
  23937. if (this.destroyed) {
  23938. return;
  23939. }
  23940. // use cache by default for perf
  23941. if (useCache === undefined) {
  23942. useCache = true;
  23943. }
  23944. for (var i = 0; i < eles.length; i++) {
  23945. var ele = eles[i];
  23946. var _p = ele._private;
  23947. var rstyle = _p.rstyle;
  23948. // an edge may be implicitly dirty b/c of one of its connected nodes
  23949. // (and a request for recalc may come in between frames)
  23950. if (ele.isEdge() && (!isCleanConnected(ele.source()) || !isCleanConnected(ele.target()))) {
  23951. rstyle.clean = false;
  23952. }
  23953. if (ele.isEdge() && ele.isBundledBezier()) {
  23954. if (ele.parallelEdges().some(function (ele) {
  23955. return !ele._private.rstyle.clean && ele.isBundledBezier();
  23956. })) {
  23957. rstyle.clean = false;
  23958. }
  23959. }
  23960. // only update if dirty and in graph
  23961. if (useCache && rstyle.clean || ele.removed()) {
  23962. continue;
  23963. }
  23964. // only update if not display: none
  23965. if (ele.pstyle('display').value === 'none') {
  23966. continue;
  23967. }
  23968. if (_p.group === 'nodes') {
  23969. nodes.push(ele);
  23970. } else {
  23971. // edges
  23972. edges.push(ele);
  23973. }
  23974. rstyle.clean = true;
  23975. }
  23976. // update node data from projections
  23977. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  23978. var _ele = nodes[_i2];
  23979. var _p2 = _ele._private;
  23980. var _rstyle = _p2.rstyle;
  23981. var pos = _ele.position();
  23982. this.recalculateNodeLabelProjection(_ele);
  23983. _rstyle.nodeX = pos.x;
  23984. _rstyle.nodeY = pos.y;
  23985. _rstyle.nodeW = _ele.pstyle('width').pfValue;
  23986. _rstyle.nodeH = _ele.pstyle('height').pfValue;
  23987. }
  23988. this.recalculateEdgeProjections(edges);
  23989. // update edge data from projections
  23990. for (var _i3 = 0; _i3 < edges.length; _i3++) {
  23991. var _ele2 = edges[_i3];
  23992. var _p3 = _ele2._private;
  23993. var _rstyle2 = _p3.rstyle;
  23994. var rs = _p3.rscratch;
  23995. // update rstyle positions
  23996. _rstyle2.srcX = rs.arrowStartX;
  23997. _rstyle2.srcY = rs.arrowStartY;
  23998. _rstyle2.tgtX = rs.arrowEndX;
  23999. _rstyle2.tgtY = rs.arrowEndY;
  24000. _rstyle2.midX = rs.midX;
  24001. _rstyle2.midY = rs.midY;
  24002. _rstyle2.labelAngle = rs.labelAngle;
  24003. _rstyle2.sourceLabelAngle = rs.sourceLabelAngle;
  24004. _rstyle2.targetLabelAngle = rs.targetLabelAngle;
  24005. }
  24006. };
  24007. var BRp$6 = {};
  24008. BRp$6.updateCachedGrabbedEles = function () {
  24009. var eles = this.cachedZSortedEles;
  24010. if (!eles) {
  24011. // just let this be recalculated on the next z sort tick
  24012. return;
  24013. }
  24014. eles.drag = [];
  24015. eles.nondrag = [];
  24016. var grabTargets = [];
  24017. for (var i = 0; i < eles.length; i++) {
  24018. var ele = eles[i];
  24019. var rs = ele._private.rscratch;
  24020. if (ele.grabbed() && !ele.isParent()) {
  24021. grabTargets.push(ele);
  24022. } else if (rs.inDragLayer) {
  24023. eles.drag.push(ele);
  24024. } else {
  24025. eles.nondrag.push(ele);
  24026. }
  24027. }
  24028. // put the grab target nodes last so it's on top of its neighbourhood
  24029. for (var i = 0; i < grabTargets.length; i++) {
  24030. var ele = grabTargets[i];
  24031. eles.drag.push(ele);
  24032. }
  24033. };
  24034. BRp$6.invalidateCachedZSortedEles = function () {
  24035. this.cachedZSortedEles = null;
  24036. };
  24037. BRp$6.getCachedZSortedEles = function (forceRecalc) {
  24038. if (forceRecalc || !this.cachedZSortedEles) {
  24039. var eles = this.cy.mutableElements().toArray();
  24040. eles.sort(zIndexSort);
  24041. eles.interactive = eles.filter(function (ele) {
  24042. return ele.interactive();
  24043. });
  24044. this.cachedZSortedEles = eles;
  24045. this.updateCachedGrabbedEles();
  24046. } else {
  24047. eles = this.cachedZSortedEles;
  24048. }
  24049. return eles;
  24050. };
  24051. var BRp$5 = {};
  24052. [BRp$e, BRp$d, BRp$c, BRp$b, BRp$a, BRp$9, BRp$8, BRp$7, BRp$6].forEach(function (props) {
  24053. extend(BRp$5, props);
  24054. });
  24055. var BRp$4 = {};
  24056. BRp$4.getCachedImage = function (url, crossOrigin, onLoad) {
  24057. var r = this;
  24058. var imageCache = r.imageCache = r.imageCache || {};
  24059. var cache = imageCache[url];
  24060. if (cache) {
  24061. if (!cache.image.complete) {
  24062. cache.image.addEventListener('load', onLoad);
  24063. }
  24064. return cache.image;
  24065. } else {
  24066. cache = imageCache[url] = imageCache[url] || {};
  24067. var image = cache.image = new Image(); // eslint-disable-line no-undef
  24068. image.addEventListener('load', onLoad);
  24069. image.addEventListener('error', function () {
  24070. image.error = true;
  24071. });
  24072. // #1582 safari doesn't load data uris with crossOrigin properly
  24073. // https://bugs.webkit.org/show_bug.cgi?id=123978
  24074. var dataUriPrefix = 'data:';
  24075. var isDataUri = url.substring(0, dataUriPrefix.length).toLowerCase() === dataUriPrefix;
  24076. if (!isDataUri) {
  24077. // if crossorigin is 'null'(stringified), then manually set it to null
  24078. crossOrigin = crossOrigin === 'null' ? null : crossOrigin;
  24079. image.crossOrigin = crossOrigin; // prevent tainted canvas
  24080. }
  24081. image.src = url;
  24082. return image;
  24083. }
  24084. };
  24085. var BRp$3 = {};
  24086. /* global document, ResizeObserver, MutationObserver */
  24087. BRp$3.registerBinding = function (target, event, handler, useCapture) {
  24088. // eslint-disable-line no-unused-vars
  24089. var args = Array.prototype.slice.apply(arguments, [1]); // copy
  24090. if (Array.isArray(target)) {
  24091. var res = [];
  24092. for (var i = 0; i < target.length; i++) {
  24093. var t = target[i];
  24094. if (t !== undefined) {
  24095. var b = this.binder(t);
  24096. res.push(b.on.apply(b, args));
  24097. }
  24098. }
  24099. return res;
  24100. }
  24101. var b = this.binder(target);
  24102. return b.on.apply(b, args);
  24103. };
  24104. BRp$3.binder = function (tgt) {
  24105. var r = this;
  24106. var containerWindow = r.cy.window();
  24107. var tgtIsDom = tgt === containerWindow || tgt === containerWindow.document || tgt === containerWindow.document.body || domElement(tgt);
  24108. if (r.supportsPassiveEvents == null) {
  24109. // from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  24110. var supportsPassive = false;
  24111. try {
  24112. var opts = Object.defineProperty({}, 'passive', {
  24113. get: function get() {
  24114. supportsPassive = true;
  24115. return true;
  24116. }
  24117. });
  24118. containerWindow.addEventListener('test', null, opts);
  24119. } catch (err) {
  24120. // not supported
  24121. }
  24122. r.supportsPassiveEvents = supportsPassive;
  24123. }
  24124. var on = function on(event, handler, useCapture) {
  24125. var args = Array.prototype.slice.call(arguments);
  24126. if (tgtIsDom && r.supportsPassiveEvents) {
  24127. // replace useCapture w/ opts obj
  24128. args[2] = {
  24129. capture: useCapture != null ? useCapture : false,
  24130. passive: false,
  24131. once: false
  24132. };
  24133. }
  24134. r.bindings.push({
  24135. target: tgt,
  24136. args: args
  24137. });
  24138. (tgt.addEventListener || tgt.on).apply(tgt, args);
  24139. return this;
  24140. };
  24141. return {
  24142. on: on,
  24143. addEventListener: on,
  24144. addListener: on,
  24145. bind: on
  24146. };
  24147. };
  24148. BRp$3.nodeIsDraggable = function (node) {
  24149. return node && node.isNode() && !node.locked() && node.grabbable();
  24150. };
  24151. BRp$3.nodeIsGrabbable = function (node) {
  24152. return this.nodeIsDraggable(node) && node.interactive();
  24153. };
  24154. BRp$3.load = function () {
  24155. var r = this;
  24156. var containerWindow = r.cy.window();
  24157. var isSelected = function isSelected(ele) {
  24158. return ele.selected();
  24159. };
  24160. var getShadowRoot = function getShadowRoot(element) {
  24161. var rootNode = element.getRootNode();
  24162. // Check if the root node is a shadow root
  24163. if (rootNode && rootNode.nodeType === 11 && rootNode.host !== undefined) {
  24164. return rootNode;
  24165. }
  24166. };
  24167. var triggerEvents = function triggerEvents(target, names, e, position) {
  24168. if (target == null) {
  24169. target = r.cy;
  24170. }
  24171. for (var i = 0; i < names.length; i++) {
  24172. var name = names[i];
  24173. target.emit({
  24174. originalEvent: e,
  24175. type: name,
  24176. position: position
  24177. });
  24178. }
  24179. };
  24180. var isMultSelKeyDown = function isMultSelKeyDown(e) {
  24181. return e.shiftKey || e.metaKey || e.ctrlKey; // maybe e.altKey
  24182. };
  24183. var allowPanningPassthrough = function allowPanningPassthrough(down, downs) {
  24184. var allowPassthrough = true;
  24185. if (r.cy.hasCompoundNodes() && down && down.pannable()) {
  24186. // a grabbable compound node below the ele => no passthrough panning
  24187. for (var i = 0; downs && i < downs.length; i++) {
  24188. var down = downs[i];
  24189. //if any parent node in event hierarchy isn't pannable, reject passthrough
  24190. if (down.isNode() && down.isParent() && !down.pannable()) {
  24191. allowPassthrough = false;
  24192. break;
  24193. }
  24194. }
  24195. } else {
  24196. allowPassthrough = true;
  24197. }
  24198. return allowPassthrough;
  24199. };
  24200. var setGrabbed = function setGrabbed(ele) {
  24201. ele[0]._private.grabbed = true;
  24202. };
  24203. var setFreed = function setFreed(ele) {
  24204. ele[0]._private.grabbed = false;
  24205. };
  24206. var setInDragLayer = function setInDragLayer(ele) {
  24207. ele[0]._private.rscratch.inDragLayer = true;
  24208. };
  24209. var setOutDragLayer = function setOutDragLayer(ele) {
  24210. ele[0]._private.rscratch.inDragLayer = false;
  24211. };
  24212. var setGrabTarget = function setGrabTarget(ele) {
  24213. ele[0]._private.rscratch.isGrabTarget = true;
  24214. };
  24215. var removeGrabTarget = function removeGrabTarget(ele) {
  24216. ele[0]._private.rscratch.isGrabTarget = false;
  24217. };
  24218. var addToDragList = function addToDragList(ele, opts) {
  24219. var list = opts.addToList;
  24220. var listHasEle = list.has(ele);
  24221. if (!listHasEle && ele.grabbable() && !ele.locked()) {
  24222. list.merge(ele);
  24223. setGrabbed(ele);
  24224. }
  24225. };
  24226. // helper function to determine which child nodes and inner edges
  24227. // of a compound node to be dragged as well as the grabbed and selected nodes
  24228. var addDescendantsToDrag = function addDescendantsToDrag(node, opts) {
  24229. if (!node.cy().hasCompoundNodes()) {
  24230. return;
  24231. }
  24232. if (opts.inDragLayer == null && opts.addToList == null) {
  24233. return;
  24234. } // nothing to do
  24235. var innerNodes = node.descendants();
  24236. if (opts.inDragLayer) {
  24237. innerNodes.forEach(setInDragLayer);
  24238. innerNodes.connectedEdges().forEach(setInDragLayer);
  24239. }
  24240. if (opts.addToList) {
  24241. addToDragList(innerNodes, opts);
  24242. }
  24243. };
  24244. // adds the given nodes and its neighbourhood to the drag layer
  24245. var addNodesToDrag = function addNodesToDrag(nodes, opts) {
  24246. opts = opts || {};
  24247. var hasCompoundNodes = nodes.cy().hasCompoundNodes();
  24248. if (opts.inDragLayer) {
  24249. nodes.forEach(setInDragLayer);
  24250. nodes.neighborhood().stdFilter(function (ele) {
  24251. return !hasCompoundNodes || ele.isEdge();
  24252. }).forEach(setInDragLayer);
  24253. }
  24254. if (opts.addToList) {
  24255. nodes.forEach(function (ele) {
  24256. addToDragList(ele, opts);
  24257. });
  24258. }
  24259. addDescendantsToDrag(nodes, opts); // always add to drag
  24260. // also add nodes and edges related to the topmost ancestor
  24261. updateAncestorsInDragLayer(nodes, {
  24262. inDragLayer: opts.inDragLayer
  24263. });
  24264. r.updateCachedGrabbedEles();
  24265. };
  24266. var addNodeToDrag = addNodesToDrag;
  24267. var freeDraggedElements = function freeDraggedElements(grabbedEles) {
  24268. if (!grabbedEles) {
  24269. return;
  24270. }
  24271. // just go over all elements rather than doing a bunch of (possibly expensive) traversals
  24272. r.getCachedZSortedEles().forEach(function (ele) {
  24273. setFreed(ele);
  24274. setOutDragLayer(ele);
  24275. removeGrabTarget(ele);
  24276. });
  24277. r.updateCachedGrabbedEles();
  24278. };
  24279. // helper function to determine which ancestor nodes and edges should go
  24280. // to the drag layer (or should be removed from drag layer).
  24281. var updateAncestorsInDragLayer = function updateAncestorsInDragLayer(node, opts) {
  24282. if (opts.inDragLayer == null && opts.addToList == null) {
  24283. return;
  24284. } // nothing to do
  24285. if (!node.cy().hasCompoundNodes()) {
  24286. return;
  24287. }
  24288. // find top-level parent
  24289. var parent = node.ancestors().orphans();
  24290. // no parent node: no nodes to add to the drag layer
  24291. if (parent.same(node)) {
  24292. return;
  24293. }
  24294. var nodes = parent.descendants().spawnSelf().merge(parent).unmerge(node).unmerge(node.descendants());
  24295. var edges = nodes.connectedEdges();
  24296. if (opts.inDragLayer) {
  24297. edges.forEach(setInDragLayer);
  24298. nodes.forEach(setInDragLayer);
  24299. }
  24300. if (opts.addToList) {
  24301. nodes.forEach(function (ele) {
  24302. addToDragList(ele, opts);
  24303. });
  24304. }
  24305. };
  24306. var blurActiveDomElement = function blurActiveDomElement() {
  24307. if (document.activeElement != null && document.activeElement.blur != null) {
  24308. document.activeElement.blur();
  24309. }
  24310. };
  24311. var haveMutationsApi = typeof MutationObserver !== 'undefined';
  24312. var haveResizeObserverApi = typeof ResizeObserver !== 'undefined';
  24313. // watch for when the cy container is removed from the dom
  24314. if (haveMutationsApi) {
  24315. r.removeObserver = new MutationObserver(function (mutns) {
  24316. // eslint-disable-line no-undef
  24317. for (var i = 0; i < mutns.length; i++) {
  24318. var mutn = mutns[i];
  24319. var rNodes = mutn.removedNodes;
  24320. if (rNodes) {
  24321. for (var j = 0; j < rNodes.length; j++) {
  24322. var rNode = rNodes[j];
  24323. if (rNode === r.container) {
  24324. r.destroy();
  24325. break;
  24326. }
  24327. }
  24328. }
  24329. }
  24330. });
  24331. if (r.container.parentNode) {
  24332. r.removeObserver.observe(r.container.parentNode, {
  24333. childList: true
  24334. });
  24335. }
  24336. } else {
  24337. r.registerBinding(r.container, 'DOMNodeRemoved', function (e) {
  24338. // eslint-disable-line no-unused-vars
  24339. r.destroy();
  24340. });
  24341. }
  24342. var onResize = debounce(function () {
  24343. r.cy.resize();
  24344. }, 100);
  24345. if (haveMutationsApi) {
  24346. r.styleObserver = new MutationObserver(onResize); // eslint-disable-line no-undef
  24347. r.styleObserver.observe(r.container, {
  24348. attributes: true
  24349. });
  24350. }
  24351. // auto resize
  24352. r.registerBinding(containerWindow, 'resize', onResize); // eslint-disable-line no-undef
  24353. if (haveResizeObserverApi) {
  24354. r.resizeObserver = new ResizeObserver(onResize); // eslint-disable-line no-undef
  24355. r.resizeObserver.observe(r.container);
  24356. }
  24357. var forEachUp = function forEachUp(domEle, fn) {
  24358. while (domEle != null) {
  24359. fn(domEle);
  24360. domEle = domEle.parentNode;
  24361. }
  24362. };
  24363. var invalidateCoords = function invalidateCoords() {
  24364. r.invalidateContainerClientCoordsCache();
  24365. };
  24366. forEachUp(r.container, function (domEle) {
  24367. r.registerBinding(domEle, 'transitionend', invalidateCoords);
  24368. r.registerBinding(domEle, 'animationend', invalidateCoords);
  24369. r.registerBinding(domEle, 'scroll', invalidateCoords);
  24370. });
  24371. // stop right click menu from appearing on cy
  24372. r.registerBinding(r.container, 'contextmenu', function (e) {
  24373. e.preventDefault();
  24374. });
  24375. var inBoxSelection = function inBoxSelection() {
  24376. return r.selection[4] !== 0;
  24377. };
  24378. var eventInContainer = function eventInContainer(e) {
  24379. // save cycles if mouse events aren't to be captured
  24380. var containerPageCoords = r.findContainerClientCoords();
  24381. var x = containerPageCoords[0];
  24382. var y = containerPageCoords[1];
  24383. var width = containerPageCoords[2];
  24384. var height = containerPageCoords[3];
  24385. var positions = e.touches ? e.touches : [e];
  24386. var atLeastOnePosInside = false;
  24387. for (var i = 0; i < positions.length; i++) {
  24388. var p = positions[i];
  24389. if (x <= p.clientX && p.clientX <= x + width && y <= p.clientY && p.clientY <= y + height) {
  24390. atLeastOnePosInside = true;
  24391. break;
  24392. }
  24393. }
  24394. if (!atLeastOnePosInside) {
  24395. return false;
  24396. }
  24397. var container = r.container;
  24398. var target = e.target;
  24399. var tParent = target.parentNode;
  24400. var containerIsTarget = false;
  24401. while (tParent) {
  24402. if (tParent === container) {
  24403. containerIsTarget = true;
  24404. break;
  24405. }
  24406. tParent = tParent.parentNode;
  24407. }
  24408. if (!containerIsTarget) {
  24409. return false;
  24410. } // if target is outisde cy container, then this event is not for us
  24411. return true;
  24412. };
  24413. // Primary key
  24414. r.registerBinding(r.container, 'mousedown', function mousedownHandler(e) {
  24415. if (!eventInContainer(e)) {
  24416. return;
  24417. }
  24418. // during left mouse button gestures, ignore other buttons
  24419. if (r.hoverData.which === 1 && e.which !== 1) {
  24420. return;
  24421. }
  24422. e.preventDefault();
  24423. blurActiveDomElement();
  24424. r.hoverData.capture = true;
  24425. r.hoverData.which = e.which;
  24426. var cy = r.cy;
  24427. var gpos = [e.clientX, e.clientY];
  24428. var pos = r.projectIntoViewport(gpos[0], gpos[1]);
  24429. var select = r.selection;
  24430. var nears = r.findNearestElements(pos[0], pos[1], true, false);
  24431. var near = nears[0];
  24432. var draggedElements = r.dragData.possibleDragElements;
  24433. r.hoverData.mdownPos = pos;
  24434. r.hoverData.mdownGPos = gpos;
  24435. var makeEvent = function makeEvent(type) {
  24436. return {
  24437. originalEvent: e,
  24438. type: type,
  24439. position: {
  24440. x: pos[0],
  24441. y: pos[1]
  24442. }
  24443. };
  24444. };
  24445. var checkForTaphold = function checkForTaphold() {
  24446. r.hoverData.tapholdCancelled = false;
  24447. clearTimeout(r.hoverData.tapholdTimeout);
  24448. r.hoverData.tapholdTimeout = setTimeout(function () {
  24449. if (r.hoverData.tapholdCancelled) {
  24450. return;
  24451. } else {
  24452. var ele = r.hoverData.down;
  24453. if (ele) {
  24454. ele.emit(makeEvent('taphold'));
  24455. } else {
  24456. cy.emit(makeEvent('taphold'));
  24457. }
  24458. }
  24459. }, r.tapholdDuration);
  24460. };
  24461. // Right click button
  24462. if (e.which == 3) {
  24463. r.hoverData.cxtStarted = true;
  24464. var cxtEvt = {
  24465. originalEvent: e,
  24466. type: 'cxttapstart',
  24467. position: {
  24468. x: pos[0],
  24469. y: pos[1]
  24470. }
  24471. };
  24472. if (near) {
  24473. near.activate();
  24474. near.emit(cxtEvt);
  24475. r.hoverData.down = near;
  24476. } else {
  24477. cy.emit(cxtEvt);
  24478. }
  24479. r.hoverData.downTime = new Date().getTime();
  24480. r.hoverData.cxtDragged = false;
  24481. // Primary button
  24482. } else if (e.which == 1) {
  24483. if (near) {
  24484. near.activate();
  24485. }
  24486. // Element dragging
  24487. {
  24488. // If something is under the cursor and it is draggable, prepare to grab it
  24489. if (near != null) {
  24490. if (r.nodeIsGrabbable(near)) {
  24491. var triggerGrab = function triggerGrab(ele) {
  24492. ele.emit(makeEvent('grab'));
  24493. };
  24494. setGrabTarget(near);
  24495. if (!near.selected()) {
  24496. draggedElements = r.dragData.possibleDragElements = cy.collection();
  24497. addNodeToDrag(near, {
  24498. addToList: draggedElements
  24499. });
  24500. near.emit(makeEvent('grabon')).emit(makeEvent('grab'));
  24501. } else {
  24502. draggedElements = r.dragData.possibleDragElements = cy.collection();
  24503. var selectedNodes = cy.$(function (ele) {
  24504. return ele.isNode() && ele.selected() && r.nodeIsGrabbable(ele);
  24505. });
  24506. addNodesToDrag(selectedNodes, {
  24507. addToList: draggedElements
  24508. });
  24509. near.emit(makeEvent('grabon'));
  24510. selectedNodes.forEach(triggerGrab);
  24511. }
  24512. r.redrawHint('eles', true);
  24513. r.redrawHint('drag', true);
  24514. }
  24515. }
  24516. r.hoverData.down = near;
  24517. r.hoverData.downs = nears;
  24518. r.hoverData.downTime = new Date().getTime();
  24519. }
  24520. triggerEvents(near, ['mousedown', 'tapstart', 'vmousedown'], e, {
  24521. x: pos[0],
  24522. y: pos[1]
  24523. });
  24524. if (near == null) {
  24525. select[4] = 1;
  24526. r.data.bgActivePosistion = {
  24527. x: pos[0],
  24528. y: pos[1]
  24529. };
  24530. r.redrawHint('select', true);
  24531. r.redraw();
  24532. } else if (near.pannable()) {
  24533. select[4] = 1; // for future pan
  24534. }
  24535. checkForTaphold();
  24536. }
  24537. // Initialize selection box coordinates
  24538. select[0] = select[2] = pos[0];
  24539. select[1] = select[3] = pos[1];
  24540. }, false);
  24541. var shadowRoot = getShadowRoot(r.container);
  24542. r.registerBinding([containerWindow, shadowRoot], 'mousemove', function mousemoveHandler(e) {
  24543. // eslint-disable-line no-undef
  24544. var capture = r.hoverData.capture;
  24545. if (!capture && !eventInContainer(e)) {
  24546. return;
  24547. }
  24548. var preventDefault = false;
  24549. var cy = r.cy;
  24550. var zoom = cy.zoom();
  24551. var gpos = [e.clientX, e.clientY];
  24552. var pos = r.projectIntoViewport(gpos[0], gpos[1]);
  24553. var mdownPos = r.hoverData.mdownPos;
  24554. var mdownGPos = r.hoverData.mdownGPos;
  24555. var select = r.selection;
  24556. var near = null;
  24557. if (!r.hoverData.draggingEles && !r.hoverData.dragging && !r.hoverData.selecting) {
  24558. near = r.findNearestElement(pos[0], pos[1], true, false);
  24559. }
  24560. var last = r.hoverData.last;
  24561. var down = r.hoverData.down;
  24562. var disp = [pos[0] - select[2], pos[1] - select[3]];
  24563. var draggedElements = r.dragData.possibleDragElements;
  24564. var isOverThresholdDrag;
  24565. if (mdownGPos) {
  24566. var dx = gpos[0] - mdownGPos[0];
  24567. var dx2 = dx * dx;
  24568. var dy = gpos[1] - mdownGPos[1];
  24569. var dy2 = dy * dy;
  24570. var dist2 = dx2 + dy2;
  24571. r.hoverData.isOverThresholdDrag = isOverThresholdDrag = dist2 >= r.desktopTapThreshold2;
  24572. }
  24573. var multSelKeyDown = isMultSelKeyDown(e);
  24574. if (isOverThresholdDrag) {
  24575. r.hoverData.tapholdCancelled = true;
  24576. }
  24577. var updateDragDelta = function updateDragDelta() {
  24578. var dragDelta = r.hoverData.dragDelta = r.hoverData.dragDelta || [];
  24579. if (dragDelta.length === 0) {
  24580. dragDelta.push(disp[0]);
  24581. dragDelta.push(disp[1]);
  24582. } else {
  24583. dragDelta[0] += disp[0];
  24584. dragDelta[1] += disp[1];
  24585. }
  24586. };
  24587. preventDefault = true;
  24588. triggerEvents(near, ['mousemove', 'vmousemove', 'tapdrag'], e, {
  24589. x: pos[0],
  24590. y: pos[1]
  24591. });
  24592. var makeEvent = function makeEvent(type) {
  24593. return {
  24594. originalEvent: e,
  24595. type: type,
  24596. position: {
  24597. x: pos[0],
  24598. y: pos[1]
  24599. }
  24600. };
  24601. };
  24602. var goIntoBoxMode = function goIntoBoxMode() {
  24603. r.data.bgActivePosistion = undefined;
  24604. if (!r.hoverData.selecting) {
  24605. cy.emit(makeEvent('boxstart'));
  24606. }
  24607. select[4] = 1;
  24608. r.hoverData.selecting = true;
  24609. r.redrawHint('select', true);
  24610. r.redraw();
  24611. };
  24612. // trigger context drag if rmouse down
  24613. if (r.hoverData.which === 3) {
  24614. // but only if over threshold
  24615. if (isOverThresholdDrag) {
  24616. var cxtEvt = makeEvent('cxtdrag');
  24617. if (down) {
  24618. down.emit(cxtEvt);
  24619. } else {
  24620. cy.emit(cxtEvt);
  24621. }
  24622. r.hoverData.cxtDragged = true;
  24623. if (!r.hoverData.cxtOver || near !== r.hoverData.cxtOver) {
  24624. if (r.hoverData.cxtOver) {
  24625. r.hoverData.cxtOver.emit(makeEvent('cxtdragout'));
  24626. }
  24627. r.hoverData.cxtOver = near;
  24628. if (near) {
  24629. near.emit(makeEvent('cxtdragover'));
  24630. }
  24631. }
  24632. }
  24633. // Check if we are drag panning the entire graph
  24634. } else if (r.hoverData.dragging) {
  24635. preventDefault = true;
  24636. if (cy.panningEnabled() && cy.userPanningEnabled()) {
  24637. var deltaP;
  24638. if (r.hoverData.justStartedPan) {
  24639. var mdPos = r.hoverData.mdownPos;
  24640. deltaP = {
  24641. x: (pos[0] - mdPos[0]) * zoom,
  24642. y: (pos[1] - mdPos[1]) * zoom
  24643. };
  24644. r.hoverData.justStartedPan = false;
  24645. } else {
  24646. deltaP = {
  24647. x: disp[0] * zoom,
  24648. y: disp[1] * zoom
  24649. };
  24650. }
  24651. cy.panBy(deltaP);
  24652. cy.emit(makeEvent('dragpan'));
  24653. r.hoverData.dragged = true;
  24654. }
  24655. // Needs reproject due to pan changing viewport
  24656. pos = r.projectIntoViewport(e.clientX, e.clientY);
  24657. // Checks primary button down & out of time & mouse not moved much
  24658. } else if (select[4] == 1 && (down == null || down.pannable())) {
  24659. if (isOverThresholdDrag) {
  24660. if (!r.hoverData.dragging && cy.boxSelectionEnabled() && (multSelKeyDown || !cy.panningEnabled() || !cy.userPanningEnabled())) {
  24661. goIntoBoxMode();
  24662. } else if (!r.hoverData.selecting && cy.panningEnabled() && cy.userPanningEnabled()) {
  24663. var allowPassthrough = allowPanningPassthrough(down, r.hoverData.downs);
  24664. if (allowPassthrough) {
  24665. r.hoverData.dragging = true;
  24666. r.hoverData.justStartedPan = true;
  24667. select[4] = 0;
  24668. r.data.bgActivePosistion = array2point(mdownPos);
  24669. r.redrawHint('select', true);
  24670. r.redraw();
  24671. }
  24672. }
  24673. if (down && down.pannable() && down.active()) {
  24674. down.unactivate();
  24675. }
  24676. }
  24677. } else {
  24678. if (down && down.pannable() && down.active()) {
  24679. down.unactivate();
  24680. }
  24681. if ((!down || !down.grabbed()) && near != last) {
  24682. if (last) {
  24683. triggerEvents(last, ['mouseout', 'tapdragout'], e, {
  24684. x: pos[0],
  24685. y: pos[1]
  24686. });
  24687. }
  24688. if (near) {
  24689. triggerEvents(near, ['mouseover', 'tapdragover'], e, {
  24690. x: pos[0],
  24691. y: pos[1]
  24692. });
  24693. }
  24694. r.hoverData.last = near;
  24695. }
  24696. if (down) {
  24697. if (isOverThresholdDrag) {
  24698. // then we can take action
  24699. if (cy.boxSelectionEnabled() && multSelKeyDown) {
  24700. // then selection overrides
  24701. if (down && down.grabbed()) {
  24702. freeDraggedElements(draggedElements);
  24703. down.emit(makeEvent('freeon'));
  24704. draggedElements.emit(makeEvent('free'));
  24705. if (r.dragData.didDrag) {
  24706. down.emit(makeEvent('dragfreeon'));
  24707. draggedElements.emit(makeEvent('dragfree'));
  24708. }
  24709. }
  24710. goIntoBoxMode();
  24711. } else if (down && down.grabbed() && r.nodeIsDraggable(down)) {
  24712. // drag node
  24713. var justStartedDrag = !r.dragData.didDrag;
  24714. if (justStartedDrag) {
  24715. r.redrawHint('eles', true);
  24716. }
  24717. r.dragData.didDrag = true; // indicate that we actually did drag the node
  24718. // now, add the elements to the drag layer if not done already
  24719. if (!r.hoverData.draggingEles) {
  24720. addNodesToDrag(draggedElements, {
  24721. inDragLayer: true
  24722. });
  24723. }
  24724. var totalShift = {
  24725. x: 0,
  24726. y: 0
  24727. };
  24728. if (number$1(disp[0]) && number$1(disp[1])) {
  24729. totalShift.x += disp[0];
  24730. totalShift.y += disp[1];
  24731. if (justStartedDrag) {
  24732. var dragDelta = r.hoverData.dragDelta;
  24733. if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
  24734. totalShift.x += dragDelta[0];
  24735. totalShift.y += dragDelta[1];
  24736. }
  24737. }
  24738. }
  24739. r.hoverData.draggingEles = true;
  24740. draggedElements.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
  24741. r.redrawHint('drag', true);
  24742. r.redraw();
  24743. }
  24744. } else {
  24745. // otherwise save drag delta for when we actually start dragging so the relative grab pos is constant
  24746. updateDragDelta();
  24747. }
  24748. }
  24749. // prevent the dragging from triggering text selection on the page
  24750. preventDefault = true;
  24751. }
  24752. select[2] = pos[0];
  24753. select[3] = pos[1];
  24754. if (preventDefault) {
  24755. if (e.stopPropagation) e.stopPropagation();
  24756. if (e.preventDefault) e.preventDefault();
  24757. return false;
  24758. }
  24759. }, false);
  24760. var clickTimeout, didDoubleClick, prevClickTimeStamp;
  24761. r.registerBinding(containerWindow, 'mouseup', function mouseupHandler(e) {
  24762. // eslint-disable-line no-undef
  24763. // during left mouse button gestures, ignore other buttons
  24764. if (r.hoverData.which === 1 && e.which !== 1 && r.hoverData.capture) {
  24765. return;
  24766. }
  24767. var capture = r.hoverData.capture;
  24768. if (!capture) {
  24769. return;
  24770. }
  24771. r.hoverData.capture = false;
  24772. var cy = r.cy;
  24773. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  24774. var select = r.selection;
  24775. var near = r.findNearestElement(pos[0], pos[1], true, false);
  24776. var draggedElements = r.dragData.possibleDragElements;
  24777. var down = r.hoverData.down;
  24778. var multSelKeyDown = isMultSelKeyDown(e);
  24779. if (r.data.bgActivePosistion) {
  24780. r.redrawHint('select', true);
  24781. r.redraw();
  24782. }
  24783. r.hoverData.tapholdCancelled = true;
  24784. r.data.bgActivePosistion = undefined; // not active bg now
  24785. if (down) {
  24786. down.unactivate();
  24787. }
  24788. var makeEvent = function makeEvent(type) {
  24789. return {
  24790. originalEvent: e,
  24791. type: type,
  24792. position: {
  24793. x: pos[0],
  24794. y: pos[1]
  24795. }
  24796. };
  24797. };
  24798. if (r.hoverData.which === 3) {
  24799. var cxtEvt = makeEvent('cxttapend');
  24800. if (down) {
  24801. down.emit(cxtEvt);
  24802. } else {
  24803. cy.emit(cxtEvt);
  24804. }
  24805. if (!r.hoverData.cxtDragged) {
  24806. var cxtTap = makeEvent('cxttap');
  24807. if (down) {
  24808. down.emit(cxtTap);
  24809. } else {
  24810. cy.emit(cxtTap);
  24811. }
  24812. }
  24813. r.hoverData.cxtDragged = false;
  24814. r.hoverData.which = null;
  24815. } else if (r.hoverData.which === 1) {
  24816. triggerEvents(near, ['mouseup', 'tapend', 'vmouseup'], e, {
  24817. x: pos[0],
  24818. y: pos[1]
  24819. });
  24820. if (!r.dragData.didDrag &&
  24821. // didn't move a node around
  24822. !r.hoverData.dragged &&
  24823. // didn't pan
  24824. !r.hoverData.selecting &&
  24825. // not box selection
  24826. !r.hoverData.isOverThresholdDrag // didn't move too much
  24827. ) {
  24828. triggerEvents(down, ["click", "tap", "vclick"], e, {
  24829. x: pos[0],
  24830. y: pos[1]
  24831. });
  24832. didDoubleClick = false;
  24833. if (e.timeStamp - prevClickTimeStamp <= cy.multiClickDebounceTime()) {
  24834. clickTimeout && clearTimeout(clickTimeout);
  24835. didDoubleClick = true;
  24836. prevClickTimeStamp = null;
  24837. triggerEvents(down, ["dblclick", "dbltap", "vdblclick"], e, {
  24838. x: pos[0],
  24839. y: pos[1]
  24840. });
  24841. } else {
  24842. clickTimeout = setTimeout(function () {
  24843. if (didDoubleClick) return;
  24844. triggerEvents(down, ["oneclick", "onetap", "voneclick"], e, {
  24845. x: pos[0],
  24846. y: pos[1]
  24847. });
  24848. }, cy.multiClickDebounceTime());
  24849. prevClickTimeStamp = e.timeStamp;
  24850. }
  24851. }
  24852. // Deselect all elements if nothing is currently under the mouse cursor and we aren't dragging something
  24853. if (down == null // not mousedown on node
  24854. && !r.dragData.didDrag // didn't move the node around
  24855. && !r.hoverData.selecting // not box selection
  24856. && !r.hoverData.dragged // didn't pan
  24857. && !isMultSelKeyDown(e)) {
  24858. cy.$(isSelected).unselect(['tapunselect']);
  24859. if (draggedElements.length > 0) {
  24860. r.redrawHint('eles', true);
  24861. }
  24862. r.dragData.possibleDragElements = draggedElements = cy.collection();
  24863. }
  24864. // Single selection
  24865. if (near == down && !r.dragData.didDrag && !r.hoverData.selecting) {
  24866. if (near != null && near._private.selectable) {
  24867. if (r.hoverData.dragging) ; else if (cy.selectionType() === 'additive' || multSelKeyDown) {
  24868. if (near.selected()) {
  24869. near.unselect(['tapunselect']);
  24870. } else {
  24871. near.select(['tapselect']);
  24872. }
  24873. } else {
  24874. if (!multSelKeyDown) {
  24875. cy.$(isSelected).unmerge(near).unselect(['tapunselect']);
  24876. near.select(['tapselect']);
  24877. }
  24878. }
  24879. r.redrawHint('eles', true);
  24880. }
  24881. }
  24882. if (r.hoverData.selecting) {
  24883. var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
  24884. r.redrawHint('select', true);
  24885. if (box.length > 0) {
  24886. r.redrawHint('eles', true);
  24887. }
  24888. cy.emit(makeEvent('boxend'));
  24889. var eleWouldBeSelected = function eleWouldBeSelected(ele) {
  24890. return ele.selectable() && !ele.selected();
  24891. };
  24892. if (cy.selectionType() === 'additive') {
  24893. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  24894. } else {
  24895. if (!multSelKeyDown) {
  24896. cy.$(isSelected).unmerge(box).unselect();
  24897. }
  24898. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  24899. }
  24900. // always need redraw in case eles unselectable
  24901. r.redraw();
  24902. }
  24903. // Cancel drag pan
  24904. if (r.hoverData.dragging) {
  24905. r.hoverData.dragging = false;
  24906. r.redrawHint('select', true);
  24907. r.redrawHint('eles', true);
  24908. r.redraw();
  24909. }
  24910. if (!select[4]) {
  24911. r.redrawHint('drag', true);
  24912. r.redrawHint('eles', true);
  24913. var downWasGrabbed = down && down.grabbed();
  24914. freeDraggedElements(draggedElements);
  24915. if (downWasGrabbed) {
  24916. down.emit(makeEvent('freeon'));
  24917. draggedElements.emit(makeEvent('free'));
  24918. if (r.dragData.didDrag) {
  24919. down.emit(makeEvent('dragfreeon'));
  24920. draggedElements.emit(makeEvent('dragfree'));
  24921. }
  24922. }
  24923. }
  24924. } // else not right mouse
  24925. select[4] = 0;
  24926. r.hoverData.down = null;
  24927. r.hoverData.cxtStarted = false;
  24928. r.hoverData.draggingEles = false;
  24929. r.hoverData.selecting = false;
  24930. r.hoverData.isOverThresholdDrag = false;
  24931. r.dragData.didDrag = false;
  24932. r.hoverData.dragged = false;
  24933. r.hoverData.dragDelta = [];
  24934. r.hoverData.mdownPos = null;
  24935. r.hoverData.mdownGPos = null;
  24936. r.hoverData.which = null;
  24937. }, false);
  24938. var wheelDeltas = []; // log of first N wheel deltas
  24939. var wheelDeltaN = 4; // how many events to log
  24940. var inaccurateScrollDevice;
  24941. var inaccurateScrollFactor = 100000; // base of inaccurate wheel deltas (e.g. base 5 could yield wheels of 10, 25, 50, etc.)
  24942. var allAreDivisibleBy = function allAreDivisibleBy(list, factor) {
  24943. for (var i = 0; i < list.length; i++) {
  24944. if (list[i] % factor !== 0) {
  24945. return false;
  24946. }
  24947. }
  24948. return true;
  24949. };
  24950. var allAreSameMagnitude = function allAreSameMagnitude(list) {
  24951. var firstMag = Math.abs(list[0]);
  24952. for (var i = 1; i < list.length; i++) {
  24953. if (Math.abs(list[i]) !== firstMag) {
  24954. return false;
  24955. }
  24956. }
  24957. return true;
  24958. };
  24959. var wheelHandler = function wheelHandler(e) {
  24960. var clamp = false;
  24961. var delta = e.deltaY;
  24962. if (delta == null) {
  24963. // compatibility with old browsers
  24964. if (e.wheelDeltaY != null) {
  24965. delta = e.wheelDeltaY / 4;
  24966. } else if (e.wheelDelta != null) {
  24967. delta = e.wheelDelta / 4;
  24968. }
  24969. }
  24970. if (delta === 0) {
  24971. return; // no change in zoom (Bug: Zoom becomes erratic on rapid scroll due to deltaY: 0 event #3394)
  24972. }
  24973. if (inaccurateScrollDevice == null) {
  24974. if (wheelDeltas.length >= wheelDeltaN) {
  24975. // use log to determine if inaccurate
  24976. var wds = wheelDeltas;
  24977. inaccurateScrollDevice = allAreDivisibleBy(wds, 5);
  24978. if (!inaccurateScrollDevice) {
  24979. // check for all large values of exact same magnitude
  24980. var firstMag = Math.abs(wds[0]);
  24981. inaccurateScrollDevice = allAreSameMagnitude(wds) && firstMag > 5;
  24982. }
  24983. if (inaccurateScrollDevice) {
  24984. for (var i = 0; i < wds.length; i++) {
  24985. inaccurateScrollFactor = Math.min(Math.abs(wds[i]), inaccurateScrollFactor);
  24986. }
  24987. }
  24988. // console.log('Sampled wheel deltas:', wds);
  24989. // console.log('inaccurateScrollDevice:', inaccurateScrollDevice);
  24990. // console.log('inaccurateScrollFactor:', inaccurateScrollFactor);
  24991. } else {
  24992. // clamp and log until we reach N
  24993. wheelDeltas.push(delta);
  24994. clamp = true;
  24995. // console.log('Clamping initial wheel events until we get a good sample');
  24996. }
  24997. } else if (inaccurateScrollDevice) {
  24998. // keep updating
  24999. inaccurateScrollFactor = Math.min(Math.abs(delta), inaccurateScrollFactor);
  25000. // console.log('Keep updating inaccurateScrollFactor beyond sample in case we did not get the smallest possible val:', inaccurateScrollFactor);
  25001. }
  25002. if (r.scrollingPage) {
  25003. return;
  25004. } // while scrolling, ignore wheel-to-zoom
  25005. var cy = r.cy;
  25006. var zoom = cy.zoom();
  25007. var pan = cy.pan();
  25008. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25009. var rpos = [pos[0] * zoom + pan.x, pos[1] * zoom + pan.y];
  25010. if (r.hoverData.draggingEles || r.hoverData.dragging || r.hoverData.cxtStarted || inBoxSelection()) {
  25011. // if pan dragging or cxt dragging, wheel movements make no zoom
  25012. e.preventDefault();
  25013. return;
  25014. }
  25015. if (cy.panningEnabled() && cy.userPanningEnabled() && cy.zoomingEnabled() && cy.userZoomingEnabled()) {
  25016. e.preventDefault();
  25017. r.data.wheelZooming = true;
  25018. clearTimeout(r.data.wheelTimeout);
  25019. r.data.wheelTimeout = setTimeout(function () {
  25020. r.data.wheelZooming = false;
  25021. r.redrawHint('eles', true);
  25022. r.redraw();
  25023. }, 150);
  25024. var diff;
  25025. if (clamp && Math.abs(delta) > 5) {
  25026. delta = signum(delta) * 5;
  25027. }
  25028. diff = delta / -250;
  25029. if (inaccurateScrollDevice) {
  25030. diff /= inaccurateScrollFactor;
  25031. diff *= 3;
  25032. }
  25033. diff = diff * r.wheelSensitivity;
  25034. // console.log(`delta = ${delta}, diff = ${diff}, mode = ${e.deltaMode}`)
  25035. var needsWheelFix = e.deltaMode === 1;
  25036. if (needsWheelFix) {
  25037. // fixes slow wheel events on ff/linux and ff/windows
  25038. diff *= 33;
  25039. }
  25040. var newZoom = cy.zoom() * Math.pow(10, diff);
  25041. if (e.type === 'gesturechange') {
  25042. newZoom = r.gestureStartZoom * e.scale;
  25043. }
  25044. cy.zoom({
  25045. level: newZoom,
  25046. renderedPosition: {
  25047. x: rpos[0],
  25048. y: rpos[1]
  25049. }
  25050. });
  25051. cy.emit({
  25052. type: e.type === 'gesturechange' ? 'pinchzoom' : 'scrollzoom',
  25053. originalEvent: e,
  25054. position: {
  25055. x: pos[0],
  25056. y: pos[1]
  25057. }
  25058. });
  25059. }
  25060. };
  25061. // Functions to help with whether mouse wheel should trigger zooming
  25062. // --
  25063. r.registerBinding(r.container, 'wheel', wheelHandler, true);
  25064. // disable nonstandard wheel events
  25065. // r.registerBinding(r.container, 'mousewheel', wheelHandler, true);
  25066. // r.registerBinding(r.container, 'DOMMouseScroll', wheelHandler, true);
  25067. // r.registerBinding(r.container, 'MozMousePixelScroll', wheelHandler, true); // older firefox
  25068. r.registerBinding(containerWindow, 'scroll', function scrollHandler(e) {
  25069. // eslint-disable-line no-unused-vars
  25070. r.scrollingPage = true;
  25071. clearTimeout(r.scrollingPageTimeout);
  25072. r.scrollingPageTimeout = setTimeout(function () {
  25073. r.scrollingPage = false;
  25074. }, 250);
  25075. }, true);
  25076. // desktop safari pinch to zoom start
  25077. r.registerBinding(r.container, 'gesturestart', function gestureStartHandler(e) {
  25078. r.gestureStartZoom = r.cy.zoom();
  25079. if (!r.hasTouchStarted) {
  25080. // don't affect touch devices like iphone
  25081. e.preventDefault();
  25082. }
  25083. }, true);
  25084. r.registerBinding(r.container, 'gesturechange', function (e) {
  25085. if (!r.hasTouchStarted) {
  25086. // don't affect touch devices like iphone
  25087. wheelHandler(e);
  25088. }
  25089. }, true);
  25090. // Functions to help with handling mouseout/mouseover on the Cytoscape container
  25091. // Handle mouseout on Cytoscape container
  25092. r.registerBinding(r.container, 'mouseout', function mouseOutHandler(e) {
  25093. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25094. r.cy.emit({
  25095. originalEvent: e,
  25096. type: 'mouseout',
  25097. position: {
  25098. x: pos[0],
  25099. y: pos[1]
  25100. }
  25101. });
  25102. }, false);
  25103. r.registerBinding(r.container, 'mouseover', function mouseOverHandler(e) {
  25104. var pos = r.projectIntoViewport(e.clientX, e.clientY);
  25105. r.cy.emit({
  25106. originalEvent: e,
  25107. type: 'mouseover',
  25108. position: {
  25109. x: pos[0],
  25110. y: pos[1]
  25111. }
  25112. });
  25113. }, false);
  25114. var f1x1, f1y1, f2x1, f2y1; // starting points for pinch-to-zoom
  25115. var distance1, distance1Sq; // initial distance between finger 1 and finger 2 for pinch-to-zoom
  25116. var center1, modelCenter1; // center point on start pinch to zoom
  25117. var offsetLeft, offsetTop;
  25118. var containerWidth, containerHeight;
  25119. var twoFingersStartInside;
  25120. var distance = function distance(x1, y1, x2, y2) {
  25121. return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  25122. };
  25123. var distanceSq = function distanceSq(x1, y1, x2, y2) {
  25124. return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
  25125. };
  25126. var touchstartHandler;
  25127. r.registerBinding(r.container, 'touchstart', touchstartHandler = function touchstartHandler(e) {
  25128. r.hasTouchStarted = true;
  25129. if (!eventInContainer(e)) {
  25130. return;
  25131. }
  25132. blurActiveDomElement();
  25133. r.touchData.capture = true;
  25134. r.data.bgActivePosistion = undefined;
  25135. var cy = r.cy;
  25136. var now = r.touchData.now;
  25137. var earlier = r.touchData.earlier;
  25138. if (e.touches[0]) {
  25139. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25140. now[0] = pos[0];
  25141. now[1] = pos[1];
  25142. }
  25143. if (e.touches[1]) {
  25144. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25145. now[2] = pos[0];
  25146. now[3] = pos[1];
  25147. }
  25148. if (e.touches[2]) {
  25149. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25150. now[4] = pos[0];
  25151. now[5] = pos[1];
  25152. }
  25153. var makeEvent = function makeEvent(type) {
  25154. return {
  25155. originalEvent: e,
  25156. type: type,
  25157. position: {
  25158. x: now[0],
  25159. y: now[1]
  25160. }
  25161. };
  25162. };
  25163. // record starting points for pinch-to-zoom
  25164. if (e.touches[1]) {
  25165. r.touchData.singleTouchMoved = true;
  25166. freeDraggedElements(r.dragData.touchDragEles);
  25167. var offsets = r.findContainerClientCoords();
  25168. offsetLeft = offsets[0];
  25169. offsetTop = offsets[1];
  25170. containerWidth = offsets[2];
  25171. containerHeight = offsets[3];
  25172. f1x1 = e.touches[0].clientX - offsetLeft;
  25173. f1y1 = e.touches[0].clientY - offsetTop;
  25174. f2x1 = e.touches[1].clientX - offsetLeft;
  25175. f2y1 = e.touches[1].clientY - offsetTop;
  25176. twoFingersStartInside = 0 <= f1x1 && f1x1 <= containerWidth && 0 <= f2x1 && f2x1 <= containerWidth && 0 <= f1y1 && f1y1 <= containerHeight && 0 <= f2y1 && f2y1 <= containerHeight;
  25177. var pan = cy.pan();
  25178. var zoom = cy.zoom();
  25179. distance1 = distance(f1x1, f1y1, f2x1, f2y1);
  25180. distance1Sq = distanceSq(f1x1, f1y1, f2x1, f2y1);
  25181. center1 = [(f1x1 + f2x1) / 2, (f1y1 + f2y1) / 2];
  25182. modelCenter1 = [(center1[0] - pan.x) / zoom, (center1[1] - pan.y) / zoom];
  25183. // consider context tap
  25184. var cxtDistThreshold = 200;
  25185. var cxtDistThresholdSq = cxtDistThreshold * cxtDistThreshold;
  25186. if (distance1Sq < cxtDistThresholdSq && !e.touches[2]) {
  25187. var near1 = r.findNearestElement(now[0], now[1], true, true);
  25188. var near2 = r.findNearestElement(now[2], now[3], true, true);
  25189. if (near1 && near1.isNode()) {
  25190. near1.activate().emit(makeEvent('cxttapstart'));
  25191. r.touchData.start = near1;
  25192. } else if (near2 && near2.isNode()) {
  25193. near2.activate().emit(makeEvent('cxttapstart'));
  25194. r.touchData.start = near2;
  25195. } else {
  25196. cy.emit(makeEvent('cxttapstart'));
  25197. }
  25198. if (r.touchData.start) {
  25199. r.touchData.start._private.grabbed = false;
  25200. }
  25201. r.touchData.cxt = true;
  25202. r.touchData.cxtDragged = false;
  25203. r.data.bgActivePosistion = undefined;
  25204. r.redraw();
  25205. return;
  25206. }
  25207. }
  25208. if (e.touches[2]) {
  25209. // ignore
  25210. // safari on ios pans the page otherwise (normally you should be able to preventdefault on touchmove...)
  25211. if (cy.boxSelectionEnabled()) {
  25212. e.preventDefault();
  25213. }
  25214. } else if (e.touches[1]) ; else if (e.touches[0]) {
  25215. var nears = r.findNearestElements(now[0], now[1], true, true);
  25216. var near = nears[0];
  25217. if (near != null) {
  25218. near.activate();
  25219. r.touchData.start = near;
  25220. r.touchData.starts = nears;
  25221. if (r.nodeIsGrabbable(near)) {
  25222. var draggedEles = r.dragData.touchDragEles = cy.collection();
  25223. var selectedNodes = null;
  25224. r.redrawHint('eles', true);
  25225. r.redrawHint('drag', true);
  25226. if (near.selected()) {
  25227. // reset drag elements, since near will be added again
  25228. selectedNodes = cy.$(function (ele) {
  25229. return ele.selected() && r.nodeIsGrabbable(ele);
  25230. });
  25231. addNodesToDrag(selectedNodes, {
  25232. addToList: draggedEles
  25233. });
  25234. } else {
  25235. addNodeToDrag(near, {
  25236. addToList: draggedEles
  25237. });
  25238. }
  25239. setGrabTarget(near);
  25240. near.emit(makeEvent('grabon'));
  25241. if (selectedNodes) {
  25242. selectedNodes.forEach(function (n) {
  25243. n.emit(makeEvent('grab'));
  25244. });
  25245. } else {
  25246. near.emit(makeEvent('grab'));
  25247. }
  25248. }
  25249. }
  25250. triggerEvents(near, ['touchstart', 'tapstart', 'vmousedown'], e, {
  25251. x: now[0],
  25252. y: now[1]
  25253. });
  25254. if (near == null) {
  25255. r.data.bgActivePosistion = {
  25256. x: pos[0],
  25257. y: pos[1]
  25258. };
  25259. r.redrawHint('select', true);
  25260. r.redraw();
  25261. }
  25262. // Tap, taphold
  25263. // -----
  25264. r.touchData.singleTouchMoved = false;
  25265. r.touchData.singleTouchStartTime = +new Date();
  25266. clearTimeout(r.touchData.tapholdTimeout);
  25267. r.touchData.tapholdTimeout = setTimeout(function () {
  25268. if (r.touchData.singleTouchMoved === false && !r.pinching // if pinching, then taphold unselect shouldn't take effect
  25269. && !r.touchData.selecting // box selection shouldn't allow taphold through
  25270. ) {
  25271. triggerEvents(r.touchData.start, ['taphold'], e, {
  25272. x: now[0],
  25273. y: now[1]
  25274. });
  25275. }
  25276. }, r.tapholdDuration);
  25277. }
  25278. if (e.touches.length >= 1) {
  25279. var sPos = r.touchData.startPosition = [null, null, null, null, null, null];
  25280. for (var i = 0; i < now.length; i++) {
  25281. sPos[i] = earlier[i] = now[i];
  25282. }
  25283. var touch0 = e.touches[0];
  25284. r.touchData.startGPosition = [touch0.clientX, touch0.clientY];
  25285. }
  25286. }, false);
  25287. var touchmoveHandler;
  25288. r.registerBinding(containerWindow, 'touchmove', touchmoveHandler = function touchmoveHandler(e) {
  25289. // eslint-disable-line no-undef
  25290. var capture = r.touchData.capture;
  25291. if (!capture && !eventInContainer(e)) {
  25292. return;
  25293. }
  25294. var select = r.selection;
  25295. var cy = r.cy;
  25296. var now = r.touchData.now;
  25297. var earlier = r.touchData.earlier;
  25298. var zoom = cy.zoom();
  25299. if (e.touches[0]) {
  25300. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25301. now[0] = pos[0];
  25302. now[1] = pos[1];
  25303. }
  25304. if (e.touches[1]) {
  25305. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25306. now[2] = pos[0];
  25307. now[3] = pos[1];
  25308. }
  25309. if (e.touches[2]) {
  25310. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25311. now[4] = pos[0];
  25312. now[5] = pos[1];
  25313. }
  25314. var makeEvent = function makeEvent(type) {
  25315. return {
  25316. originalEvent: e,
  25317. type: type,
  25318. position: {
  25319. x: now[0],
  25320. y: now[1]
  25321. }
  25322. };
  25323. };
  25324. var startGPos = r.touchData.startGPosition;
  25325. var isOverThresholdDrag;
  25326. if (capture && e.touches[0] && startGPos) {
  25327. var disp = [];
  25328. for (var j = 0; j < now.length; j++) {
  25329. disp[j] = now[j] - earlier[j];
  25330. }
  25331. var dx = e.touches[0].clientX - startGPos[0];
  25332. var dx2 = dx * dx;
  25333. var dy = e.touches[0].clientY - startGPos[1];
  25334. var dy2 = dy * dy;
  25335. var dist2 = dx2 + dy2;
  25336. isOverThresholdDrag = dist2 >= r.touchTapThreshold2;
  25337. }
  25338. // context swipe cancelling
  25339. if (capture && r.touchData.cxt) {
  25340. e.preventDefault();
  25341. var f1x2 = e.touches[0].clientX - offsetLeft,
  25342. f1y2 = e.touches[0].clientY - offsetTop;
  25343. var f2x2 = e.touches[1].clientX - offsetLeft,
  25344. f2y2 = e.touches[1].clientY - offsetTop;
  25345. // var distance2 = distance( f1x2, f1y2, f2x2, f2y2 );
  25346. var distance2Sq = distanceSq(f1x2, f1y2, f2x2, f2y2);
  25347. var factorSq = distance2Sq / distance1Sq;
  25348. var distThreshold = 150;
  25349. var distThresholdSq = distThreshold * distThreshold;
  25350. var factorThreshold = 1.5;
  25351. var factorThresholdSq = factorThreshold * factorThreshold;
  25352. // cancel ctx gestures if the distance b/t the fingers increases
  25353. if (factorSq >= factorThresholdSq || distance2Sq >= distThresholdSq) {
  25354. r.touchData.cxt = false;
  25355. r.data.bgActivePosistion = undefined;
  25356. r.redrawHint('select', true);
  25357. var cxtEvt = makeEvent('cxttapend');
  25358. if (r.touchData.start) {
  25359. r.touchData.start.unactivate().emit(cxtEvt);
  25360. r.touchData.start = null;
  25361. } else {
  25362. cy.emit(cxtEvt);
  25363. }
  25364. }
  25365. }
  25366. // context swipe
  25367. if (capture && r.touchData.cxt) {
  25368. var cxtEvt = makeEvent('cxtdrag');
  25369. r.data.bgActivePosistion = undefined;
  25370. r.redrawHint('select', true);
  25371. if (r.touchData.start) {
  25372. r.touchData.start.emit(cxtEvt);
  25373. } else {
  25374. cy.emit(cxtEvt);
  25375. }
  25376. if (r.touchData.start) {
  25377. r.touchData.start._private.grabbed = false;
  25378. }
  25379. r.touchData.cxtDragged = true;
  25380. var near = r.findNearestElement(now[0], now[1], true, true);
  25381. if (!r.touchData.cxtOver || near !== r.touchData.cxtOver) {
  25382. if (r.touchData.cxtOver) {
  25383. r.touchData.cxtOver.emit(makeEvent('cxtdragout'));
  25384. }
  25385. r.touchData.cxtOver = near;
  25386. if (near) {
  25387. near.emit(makeEvent('cxtdragover'));
  25388. }
  25389. }
  25390. // box selection
  25391. } else if (capture && e.touches[2] && cy.boxSelectionEnabled()) {
  25392. e.preventDefault();
  25393. r.data.bgActivePosistion = undefined;
  25394. this.lastThreeTouch = +new Date();
  25395. if (!r.touchData.selecting) {
  25396. cy.emit(makeEvent('boxstart'));
  25397. }
  25398. r.touchData.selecting = true;
  25399. r.touchData.didSelect = true;
  25400. select[4] = 1;
  25401. if (!select || select.length === 0 || select[0] === undefined) {
  25402. select[0] = (now[0] + now[2] + now[4]) / 3;
  25403. select[1] = (now[1] + now[3] + now[5]) / 3;
  25404. select[2] = (now[0] + now[2] + now[4]) / 3 + 1;
  25405. select[3] = (now[1] + now[3] + now[5]) / 3 + 1;
  25406. } else {
  25407. select[2] = (now[0] + now[2] + now[4]) / 3;
  25408. select[3] = (now[1] + now[3] + now[5]) / 3;
  25409. }
  25410. r.redrawHint('select', true);
  25411. r.redraw();
  25412. // pinch to zoom
  25413. } else if (capture && e.touches[1] && !r.touchData.didSelect // don't allow box selection to degrade to pinch-to-zoom
  25414. && cy.zoomingEnabled() && cy.panningEnabled() && cy.userZoomingEnabled() && cy.userPanningEnabled()) {
  25415. // two fingers => pinch to zoom
  25416. e.preventDefault();
  25417. r.data.bgActivePosistion = undefined;
  25418. r.redrawHint('select', true);
  25419. var draggedEles = r.dragData.touchDragEles;
  25420. if (draggedEles) {
  25421. r.redrawHint('drag', true);
  25422. for (var i = 0; i < draggedEles.length; i++) {
  25423. var de_p = draggedEles[i]._private;
  25424. de_p.grabbed = false;
  25425. de_p.rscratch.inDragLayer = false;
  25426. }
  25427. }
  25428. var _start = r.touchData.start;
  25429. // (x2, y2) for fingers 1 and 2
  25430. var f1x2 = e.touches[0].clientX - offsetLeft,
  25431. f1y2 = e.touches[0].clientY - offsetTop;
  25432. var f2x2 = e.touches[1].clientX - offsetLeft,
  25433. f2y2 = e.touches[1].clientY - offsetTop;
  25434. var distance2 = distance(f1x2, f1y2, f2x2, f2y2);
  25435. // var distance2Sq = distanceSq( f1x2, f1y2, f2x2, f2y2 );
  25436. // var factor = Math.sqrt( distance2Sq ) / Math.sqrt( distance1Sq );
  25437. var factor = distance2 / distance1;
  25438. if (twoFingersStartInside) {
  25439. // delta finger1
  25440. var df1x = f1x2 - f1x1;
  25441. var df1y = f1y2 - f1y1;
  25442. // delta finger 2
  25443. var df2x = f2x2 - f2x1;
  25444. var df2y = f2y2 - f2y1;
  25445. // translation is the normalised vector of the two fingers movement
  25446. // i.e. so pinching cancels out and moving together pans
  25447. var tx = (df1x + df2x) / 2;
  25448. var ty = (df1y + df2y) / 2;
  25449. // now calculate the zoom
  25450. var zoom1 = cy.zoom();
  25451. var zoom2 = zoom1 * factor;
  25452. var pan1 = cy.pan();
  25453. // the model center point converted to the current rendered pos
  25454. var ctrx = modelCenter1[0] * zoom1 + pan1.x;
  25455. var ctry = modelCenter1[1] * zoom1 + pan1.y;
  25456. var pan2 = {
  25457. x: -zoom2 / zoom1 * (ctrx - pan1.x - tx) + ctrx,
  25458. y: -zoom2 / zoom1 * (ctry - pan1.y - ty) + ctry
  25459. };
  25460. // remove dragged eles
  25461. if (_start && _start.active()) {
  25462. var draggedEles = r.dragData.touchDragEles;
  25463. freeDraggedElements(draggedEles);
  25464. r.redrawHint('drag', true);
  25465. r.redrawHint('eles', true);
  25466. _start.unactivate().emit(makeEvent('freeon'));
  25467. draggedEles.emit(makeEvent('free'));
  25468. if (r.dragData.didDrag) {
  25469. _start.emit(makeEvent('dragfreeon'));
  25470. draggedEles.emit(makeEvent('dragfree'));
  25471. }
  25472. }
  25473. cy.viewport({
  25474. zoom: zoom2,
  25475. pan: pan2,
  25476. cancelOnFailedZoom: true
  25477. });
  25478. cy.emit(makeEvent('pinchzoom'));
  25479. distance1 = distance2;
  25480. f1x1 = f1x2;
  25481. f1y1 = f1y2;
  25482. f2x1 = f2x2;
  25483. f2y1 = f2y2;
  25484. r.pinching = true;
  25485. }
  25486. // Re-project
  25487. if (e.touches[0]) {
  25488. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25489. now[0] = pos[0];
  25490. now[1] = pos[1];
  25491. }
  25492. if (e.touches[1]) {
  25493. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25494. now[2] = pos[0];
  25495. now[3] = pos[1];
  25496. }
  25497. if (e.touches[2]) {
  25498. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25499. now[4] = pos[0];
  25500. now[5] = pos[1];
  25501. }
  25502. } else if (e.touches[0] && !r.touchData.didSelect // don't allow box selection to degrade to single finger events like panning
  25503. ) {
  25504. var start = r.touchData.start;
  25505. var last = r.touchData.last;
  25506. var near;
  25507. if (!r.hoverData.draggingEles && !r.swipePanning) {
  25508. near = r.findNearestElement(now[0], now[1], true, true);
  25509. }
  25510. if (capture && start != null) {
  25511. e.preventDefault();
  25512. }
  25513. // dragging nodes
  25514. if (capture && start != null && r.nodeIsDraggable(start)) {
  25515. if (isOverThresholdDrag) {
  25516. // then dragging can happen
  25517. var draggedEles = r.dragData.touchDragEles;
  25518. var justStartedDrag = !r.dragData.didDrag;
  25519. if (justStartedDrag) {
  25520. addNodesToDrag(draggedEles, {
  25521. inDragLayer: true
  25522. });
  25523. }
  25524. r.dragData.didDrag = true;
  25525. var totalShift = {
  25526. x: 0,
  25527. y: 0
  25528. };
  25529. if (number$1(disp[0]) && number$1(disp[1])) {
  25530. totalShift.x += disp[0];
  25531. totalShift.y += disp[1];
  25532. if (justStartedDrag) {
  25533. r.redrawHint('eles', true);
  25534. var dragDelta = r.touchData.dragDelta;
  25535. if (dragDelta && number$1(dragDelta[0]) && number$1(dragDelta[1])) {
  25536. totalShift.x += dragDelta[0];
  25537. totalShift.y += dragDelta[1];
  25538. }
  25539. }
  25540. }
  25541. r.hoverData.draggingEles = true;
  25542. draggedEles.silentShift(totalShift).emit(makeEvent('position')).emit(makeEvent('drag'));
  25543. r.redrawHint('drag', true);
  25544. if (r.touchData.startPosition[0] == earlier[0] && r.touchData.startPosition[1] == earlier[1]) {
  25545. r.redrawHint('eles', true);
  25546. }
  25547. r.redraw();
  25548. } else {
  25549. // otherwise keep track of drag delta for later
  25550. var dragDelta = r.touchData.dragDelta = r.touchData.dragDelta || [];
  25551. if (dragDelta.length === 0) {
  25552. dragDelta.push(disp[0]);
  25553. dragDelta.push(disp[1]);
  25554. } else {
  25555. dragDelta[0] += disp[0];
  25556. dragDelta[1] += disp[1];
  25557. }
  25558. }
  25559. }
  25560. // touchmove
  25561. {
  25562. triggerEvents(start || near, ['touchmove', 'tapdrag', 'vmousemove'], e, {
  25563. x: now[0],
  25564. y: now[1]
  25565. });
  25566. if ((!start || !start.grabbed()) && near != last) {
  25567. if (last) {
  25568. last.emit(makeEvent('tapdragout'));
  25569. }
  25570. if (near) {
  25571. near.emit(makeEvent('tapdragover'));
  25572. }
  25573. }
  25574. r.touchData.last = near;
  25575. }
  25576. // check to cancel taphold
  25577. if (capture) {
  25578. for (var i = 0; i < now.length; i++) {
  25579. if (now[i] && r.touchData.startPosition[i] && isOverThresholdDrag) {
  25580. r.touchData.singleTouchMoved = true;
  25581. }
  25582. }
  25583. }
  25584. // panning
  25585. if (capture && (start == null || start.pannable()) && cy.panningEnabled() && cy.userPanningEnabled()) {
  25586. var allowPassthrough = allowPanningPassthrough(start, r.touchData.starts);
  25587. if (allowPassthrough) {
  25588. e.preventDefault();
  25589. if (!r.data.bgActivePosistion) {
  25590. r.data.bgActivePosistion = array2point(r.touchData.startPosition);
  25591. }
  25592. if (r.swipePanning) {
  25593. cy.panBy({
  25594. x: disp[0] * zoom,
  25595. y: disp[1] * zoom
  25596. });
  25597. cy.emit(makeEvent('dragpan'));
  25598. } else if (isOverThresholdDrag) {
  25599. r.swipePanning = true;
  25600. cy.panBy({
  25601. x: dx * zoom,
  25602. y: dy * zoom
  25603. });
  25604. cy.emit(makeEvent('dragpan'));
  25605. if (start) {
  25606. start.unactivate();
  25607. r.redrawHint('select', true);
  25608. r.touchData.start = null;
  25609. }
  25610. }
  25611. }
  25612. // Re-project
  25613. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25614. now[0] = pos[0];
  25615. now[1] = pos[1];
  25616. }
  25617. }
  25618. for (var j = 0; j < now.length; j++) {
  25619. earlier[j] = now[j];
  25620. }
  25621. // the active bg indicator should be removed when making a swipe that is neither for dragging nodes or panning
  25622. if (capture && e.touches.length > 0 && !r.hoverData.draggingEles && !r.swipePanning && r.data.bgActivePosistion != null) {
  25623. r.data.bgActivePosistion = undefined;
  25624. r.redrawHint('select', true);
  25625. r.redraw();
  25626. }
  25627. }, false);
  25628. var touchcancelHandler;
  25629. r.registerBinding(containerWindow, 'touchcancel', touchcancelHandler = function touchcancelHandler(e) {
  25630. // eslint-disable-line no-unused-vars
  25631. var start = r.touchData.start;
  25632. r.touchData.capture = false;
  25633. if (start) {
  25634. start.unactivate();
  25635. }
  25636. });
  25637. var touchendHandler, didDoubleTouch, touchTimeout, prevTouchTimeStamp;
  25638. r.registerBinding(containerWindow, 'touchend', touchendHandler = function touchendHandler(e) {
  25639. // eslint-disable-line no-unused-vars
  25640. var start = r.touchData.start;
  25641. var capture = r.touchData.capture;
  25642. if (capture) {
  25643. if (e.touches.length === 0) {
  25644. r.touchData.capture = false;
  25645. }
  25646. e.preventDefault();
  25647. } else {
  25648. return;
  25649. }
  25650. var select = r.selection;
  25651. r.swipePanning = false;
  25652. r.hoverData.draggingEles = false;
  25653. var cy = r.cy;
  25654. var zoom = cy.zoom();
  25655. var now = r.touchData.now;
  25656. var earlier = r.touchData.earlier;
  25657. if (e.touches[0]) {
  25658. var pos = r.projectIntoViewport(e.touches[0].clientX, e.touches[0].clientY);
  25659. now[0] = pos[0];
  25660. now[1] = pos[1];
  25661. }
  25662. if (e.touches[1]) {
  25663. var pos = r.projectIntoViewport(e.touches[1].clientX, e.touches[1].clientY);
  25664. now[2] = pos[0];
  25665. now[3] = pos[1];
  25666. }
  25667. if (e.touches[2]) {
  25668. var pos = r.projectIntoViewport(e.touches[2].clientX, e.touches[2].clientY);
  25669. now[4] = pos[0];
  25670. now[5] = pos[1];
  25671. }
  25672. var makeEvent = function makeEvent(type) {
  25673. return {
  25674. originalEvent: e,
  25675. type: type,
  25676. position: {
  25677. x: now[0],
  25678. y: now[1]
  25679. }
  25680. };
  25681. };
  25682. if (start) {
  25683. start.unactivate();
  25684. }
  25685. var ctxTapend;
  25686. if (r.touchData.cxt) {
  25687. ctxTapend = makeEvent('cxttapend');
  25688. if (start) {
  25689. start.emit(ctxTapend);
  25690. } else {
  25691. cy.emit(ctxTapend);
  25692. }
  25693. if (!r.touchData.cxtDragged) {
  25694. var ctxTap = makeEvent('cxttap');
  25695. if (start) {
  25696. start.emit(ctxTap);
  25697. } else {
  25698. cy.emit(ctxTap);
  25699. }
  25700. }
  25701. if (r.touchData.start) {
  25702. r.touchData.start._private.grabbed = false;
  25703. }
  25704. r.touchData.cxt = false;
  25705. r.touchData.start = null;
  25706. r.redraw();
  25707. return;
  25708. }
  25709. // no more box selection if we don't have three fingers
  25710. if (!e.touches[2] && cy.boxSelectionEnabled() && r.touchData.selecting) {
  25711. r.touchData.selecting = false;
  25712. var box = cy.collection(r.getAllInBox(select[0], select[1], select[2], select[3]));
  25713. select[0] = undefined;
  25714. select[1] = undefined;
  25715. select[2] = undefined;
  25716. select[3] = undefined;
  25717. select[4] = 0;
  25718. r.redrawHint('select', true);
  25719. cy.emit(makeEvent('boxend'));
  25720. var eleWouldBeSelected = function eleWouldBeSelected(ele) {
  25721. return ele.selectable() && !ele.selected();
  25722. };
  25723. box.emit(makeEvent('box')).stdFilter(eleWouldBeSelected).select().emit(makeEvent('boxselect'));
  25724. if (box.nonempty()) {
  25725. r.redrawHint('eles', true);
  25726. }
  25727. r.redraw();
  25728. }
  25729. if (start != null) {
  25730. start.unactivate();
  25731. }
  25732. if (e.touches[2]) {
  25733. r.data.bgActivePosistion = undefined;
  25734. r.redrawHint('select', true);
  25735. } else if (e.touches[1]) ; else if (e.touches[0]) ; else if (!e.touches[0]) {
  25736. r.data.bgActivePosistion = undefined;
  25737. r.redrawHint('select', true);
  25738. var draggedEles = r.dragData.touchDragEles;
  25739. if (start != null) {
  25740. var startWasGrabbed = start._private.grabbed;
  25741. freeDraggedElements(draggedEles);
  25742. r.redrawHint('drag', true);
  25743. r.redrawHint('eles', true);
  25744. if (startWasGrabbed) {
  25745. start.emit(makeEvent('freeon'));
  25746. draggedEles.emit(makeEvent('free'));
  25747. if (r.dragData.didDrag) {
  25748. start.emit(makeEvent('dragfreeon'));
  25749. draggedEles.emit(makeEvent('dragfree'));
  25750. }
  25751. }
  25752. triggerEvents(start, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
  25753. x: now[0],
  25754. y: now[1]
  25755. });
  25756. start.unactivate();
  25757. r.touchData.start = null;
  25758. } else {
  25759. var near = r.findNearestElement(now[0], now[1], true, true);
  25760. triggerEvents(near, ['touchend', 'tapend', 'vmouseup', 'tapdragout'], e, {
  25761. x: now[0],
  25762. y: now[1]
  25763. });
  25764. }
  25765. var dx = r.touchData.startPosition[0] - now[0];
  25766. var dx2 = dx * dx;
  25767. var dy = r.touchData.startPosition[1] - now[1];
  25768. var dy2 = dy * dy;
  25769. var dist2 = dx2 + dy2;
  25770. var rdist2 = dist2 * zoom * zoom;
  25771. // Tap event, roughly same as mouse click event for touch
  25772. if (!r.touchData.singleTouchMoved) {
  25773. if (!start) {
  25774. cy.$(':selected').unselect(['tapunselect']);
  25775. }
  25776. triggerEvents(start, ['tap', 'vclick'], e, {
  25777. x: now[0],
  25778. y: now[1]
  25779. });
  25780. didDoubleTouch = false;
  25781. if (e.timeStamp - prevTouchTimeStamp <= cy.multiClickDebounceTime()) {
  25782. touchTimeout && clearTimeout(touchTimeout);
  25783. didDoubleTouch = true;
  25784. prevTouchTimeStamp = null;
  25785. triggerEvents(start, ['dbltap', 'vdblclick'], e, {
  25786. x: now[0],
  25787. y: now[1]
  25788. });
  25789. } else {
  25790. touchTimeout = setTimeout(function () {
  25791. if (didDoubleTouch) return;
  25792. triggerEvents(start, ['onetap', 'voneclick'], e, {
  25793. x: now[0],
  25794. y: now[1]
  25795. });
  25796. }, cy.multiClickDebounceTime());
  25797. prevTouchTimeStamp = e.timeStamp;
  25798. }
  25799. }
  25800. // Prepare to select the currently touched node, only if it hasn't been dragged past a certain distance
  25801. if (start != null && !r.dragData.didDrag // didn't drag nodes around
  25802. && start._private.selectable && rdist2 < r.touchTapThreshold2 && !r.pinching // pinch to zoom should not affect selection
  25803. ) {
  25804. if (cy.selectionType() === 'single') {
  25805. cy.$(isSelected).unmerge(start).unselect(['tapunselect']);
  25806. start.select(['tapselect']);
  25807. } else {
  25808. if (start.selected()) {
  25809. start.unselect(['tapunselect']);
  25810. } else {
  25811. start.select(['tapselect']);
  25812. }
  25813. }
  25814. r.redrawHint('eles', true);
  25815. }
  25816. r.touchData.singleTouchMoved = true;
  25817. }
  25818. for (var j = 0; j < now.length; j++) {
  25819. earlier[j] = now[j];
  25820. }
  25821. r.dragData.didDrag = false; // reset for next touchstart
  25822. if (e.touches.length === 0) {
  25823. r.touchData.dragDelta = [];
  25824. r.touchData.startPosition = [null, null, null, null, null, null];
  25825. r.touchData.startGPosition = null;
  25826. r.touchData.didSelect = false;
  25827. }
  25828. if (e.touches.length < 2) {
  25829. if (e.touches.length === 1) {
  25830. // the old start global pos'n may not be the same finger that remains
  25831. r.touchData.startGPosition = [e.touches[0].clientX, e.touches[0].clientY];
  25832. }
  25833. r.pinching = false;
  25834. r.redrawHint('eles', true);
  25835. r.redraw();
  25836. }
  25837. //r.redraw();
  25838. }, false);
  25839. // fallback compatibility layer for ms pointer events
  25840. if (typeof TouchEvent === 'undefined') {
  25841. var pointers = [];
  25842. var makeTouch = function makeTouch(e) {
  25843. return {
  25844. clientX: e.clientX,
  25845. clientY: e.clientY,
  25846. force: 1,
  25847. identifier: e.pointerId,
  25848. pageX: e.pageX,
  25849. pageY: e.pageY,
  25850. radiusX: e.width / 2,
  25851. radiusY: e.height / 2,
  25852. screenX: e.screenX,
  25853. screenY: e.screenY,
  25854. target: e.target
  25855. };
  25856. };
  25857. var makePointer = function makePointer(e) {
  25858. return {
  25859. event: e,
  25860. touch: makeTouch(e)
  25861. };
  25862. };
  25863. var addPointer = function addPointer(e) {
  25864. pointers.push(makePointer(e));
  25865. };
  25866. var removePointer = function removePointer(e) {
  25867. for (var i = 0; i < pointers.length; i++) {
  25868. var p = pointers[i];
  25869. if (p.event.pointerId === e.pointerId) {
  25870. pointers.splice(i, 1);
  25871. return;
  25872. }
  25873. }
  25874. };
  25875. var updatePointer = function updatePointer(e) {
  25876. var p = pointers.filter(function (p) {
  25877. return p.event.pointerId === e.pointerId;
  25878. })[0];
  25879. p.event = e;
  25880. p.touch = makeTouch(e);
  25881. };
  25882. var addTouchesToEvent = function addTouchesToEvent(e) {
  25883. e.touches = pointers.map(function (p) {
  25884. return p.touch;
  25885. });
  25886. };
  25887. var pointerIsMouse = function pointerIsMouse(e) {
  25888. return e.pointerType === 'mouse' || e.pointerType === 4;
  25889. };
  25890. r.registerBinding(r.container, 'pointerdown', function (e) {
  25891. if (pointerIsMouse(e)) {
  25892. return;
  25893. } // mouse already handled
  25894. e.preventDefault();
  25895. addPointer(e);
  25896. addTouchesToEvent(e);
  25897. touchstartHandler(e);
  25898. });
  25899. r.registerBinding(r.container, 'pointerup', function (e) {
  25900. if (pointerIsMouse(e)) {
  25901. return;
  25902. } // mouse already handled
  25903. removePointer(e);
  25904. addTouchesToEvent(e);
  25905. touchendHandler(e);
  25906. });
  25907. r.registerBinding(r.container, 'pointercancel', function (e) {
  25908. if (pointerIsMouse(e)) {
  25909. return;
  25910. } // mouse already handled
  25911. removePointer(e);
  25912. addTouchesToEvent(e);
  25913. touchcancelHandler(e);
  25914. });
  25915. r.registerBinding(r.container, 'pointermove', function (e) {
  25916. if (pointerIsMouse(e)) {
  25917. return;
  25918. } // mouse already handled
  25919. e.preventDefault();
  25920. updatePointer(e);
  25921. addTouchesToEvent(e);
  25922. touchmoveHandler(e);
  25923. });
  25924. }
  25925. };
  25926. var BRp$2 = {};
  25927. BRp$2.generatePolygon = function (name, points) {
  25928. return this.nodeShapes[name] = {
  25929. renderer: this,
  25930. name: name,
  25931. points: points,
  25932. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  25933. this.renderer.nodeShapeImpl('polygon', context, centerX, centerY, width, height, this.points);
  25934. },
  25935. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  25936. return polygonIntersectLine(x, y, this.points, nodeX, nodeY, width / 2, height / 2, padding);
  25937. },
  25938. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  25939. return pointInsidePolygon(x, y, this.points, centerX, centerY, width, height, [0, -1], padding);
  25940. },
  25941. hasMiterBounds: name !== 'rectangle',
  25942. miterBounds: function miterBounds(centerX, centerY, width, height, strokeWidth, strokePosition) {
  25943. return miterBox(this.points, centerX, centerY, width, height, strokeWidth);
  25944. }
  25945. };
  25946. };
  25947. BRp$2.generateEllipse = function () {
  25948. return this.nodeShapes['ellipse'] = {
  25949. renderer: this,
  25950. name: 'ellipse',
  25951. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  25952. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
  25953. },
  25954. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  25955. return intersectLineEllipse(x, y, nodeX, nodeY, width / 2 + padding, height / 2 + padding);
  25956. },
  25957. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  25958. return checkInEllipse(x, y, width, height, centerX, centerY, padding);
  25959. }
  25960. };
  25961. };
  25962. BRp$2.generateRoundPolygon = function (name, points) {
  25963. return this.nodeShapes[name] = {
  25964. renderer: this,
  25965. name: name,
  25966. points: points,
  25967. getOrCreateCorners: function getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, field) {
  25968. if (rs[field] !== undefined && rs[field + '-cx'] === centerX && rs[field + '-cy'] === centerY) {
  25969. return rs[field];
  25970. }
  25971. rs[field] = new Array(points.length / 2);
  25972. rs[field + '-cx'] = centerX;
  25973. rs[field + '-cy'] = centerY;
  25974. var halfW = width / 2;
  25975. var halfH = height / 2;
  25976. cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(width, height) : cornerRadius;
  25977. var p = new Array(points.length / 2);
  25978. for (var _i = 0; _i < points.length / 2; _i++) {
  25979. p[_i] = {
  25980. x: centerX + halfW * points[_i * 2],
  25981. y: centerY + halfH * points[_i * 2 + 1]
  25982. };
  25983. }
  25984. var i,
  25985. p1,
  25986. p2,
  25987. p3,
  25988. len = p.length;
  25989. p1 = p[len - 1];
  25990. // for each point
  25991. for (i = 0; i < len; i++) {
  25992. p2 = p[i % len];
  25993. p3 = p[(i + 1) % len];
  25994. rs[field][i] = getRoundCorner(p1, p2, p3, cornerRadius);
  25995. p1 = p2;
  25996. p2 = p3;
  25997. }
  25998. return rs[field];
  25999. },
  26000. draw: function draw(context, centerX, centerY, width, height, cornerRadius, rs) {
  26001. this.renderer.nodeShapeImpl('round-polygon', context, centerX, centerY, width, height, this.points, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'drawCorners'));
  26002. },
  26003. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius, rs) {
  26004. return roundPolygonIntersectLine(x, y, this.points, nodeX, nodeY, width, height, padding, this.getOrCreateCorners(nodeX, nodeY, width, height, cornerRadius, rs, 'corners'));
  26005. },
  26006. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius, rs) {
  26007. return pointInsideRoundPolygon(x, y, this.points, centerX, centerY, width, height, this.getOrCreateCorners(centerX, centerY, width, height, cornerRadius, rs, 'corners'));
  26008. }
  26009. };
  26010. };
  26011. BRp$2.generateRoundRectangle = function () {
  26012. return this.nodeShapes['round-rectangle'] = this.nodeShapes['roundrectangle'] = {
  26013. renderer: this,
  26014. name: 'round-rectangle',
  26015. points: generateUnitNgonPointsFitToSquare(4, 0),
  26016. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26017. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
  26018. },
  26019. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26020. return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
  26021. },
  26022. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26023. var halfWidth = width / 2;
  26024. var halfHeight = height / 2;
  26025. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
  26026. cornerRadius = Math.min(halfWidth, halfHeight, cornerRadius);
  26027. var diam = cornerRadius * 2;
  26028. // Check hBox
  26029. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
  26030. return true;
  26031. }
  26032. // Check vBox
  26033. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
  26034. return true;
  26035. }
  26036. // Check top left quarter circle
  26037. if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
  26038. return true;
  26039. }
  26040. // Check top right quarter circle
  26041. if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY - halfHeight + cornerRadius, padding)) {
  26042. return true;
  26043. }
  26044. // Check bottom right quarter circle
  26045. if (checkInEllipse(x, y, diam, diam, centerX + halfWidth - cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
  26046. return true;
  26047. }
  26048. // Check bottom left quarter circle
  26049. if (checkInEllipse(x, y, diam, diam, centerX - halfWidth + cornerRadius, centerY + halfHeight - cornerRadius, padding)) {
  26050. return true;
  26051. }
  26052. return false;
  26053. }
  26054. };
  26055. };
  26056. BRp$2.generateCutRectangle = function () {
  26057. return this.nodeShapes['cut-rectangle'] = this.nodeShapes['cutrectangle'] = {
  26058. renderer: this,
  26059. name: 'cut-rectangle',
  26060. cornerLength: getCutRectangleCornerLength(),
  26061. points: generateUnitNgonPointsFitToSquare(4, 0),
  26062. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26063. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, null, cornerRadius);
  26064. },
  26065. generateCutTrianglePts: function generateCutTrianglePts(width, height, centerX, centerY, cornerRadius) {
  26066. var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
  26067. var hh = height / 2;
  26068. var hw = width / 2;
  26069. var xBegin = centerX - hw;
  26070. var xEnd = centerX + hw;
  26071. var yBegin = centerY - hh;
  26072. var yEnd = centerY + hh;
  26073. // points are in clockwise order, inner (imaginary) triangle pt on [4, 5]
  26074. return {
  26075. topLeft: [xBegin, yBegin + cl, xBegin + cl, yBegin, xBegin + cl, yBegin + cl],
  26076. topRight: [xEnd - cl, yBegin, xEnd, yBegin + cl, xEnd - cl, yBegin + cl],
  26077. bottomRight: [xEnd, yEnd - cl, xEnd - cl, yEnd, xEnd - cl, yEnd - cl],
  26078. bottomLeft: [xBegin + cl, yEnd, xBegin, yEnd - cl, xBegin + cl, yEnd - cl]
  26079. };
  26080. },
  26081. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26082. var cPts = this.generateCutTrianglePts(width + 2 * padding, height + 2 * padding, nodeX, nodeY, cornerRadius);
  26083. var pts = [].concat.apply([], [cPts.topLeft.splice(0, 4), cPts.topRight.splice(0, 4), cPts.bottomRight.splice(0, 4), cPts.bottomLeft.splice(0, 4)]);
  26084. return polygonIntersectLine(x, y, pts, nodeX, nodeY);
  26085. },
  26086. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26087. var cl = cornerRadius === 'auto' ? this.cornerLength : cornerRadius;
  26088. // Check hBox
  26089. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * cl, [0, -1], padding)) {
  26090. return true;
  26091. }
  26092. // Check vBox
  26093. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * cl, height, [0, -1], padding)) {
  26094. return true;
  26095. }
  26096. var cutTrianglePts = this.generateCutTrianglePts(width, height, centerX, centerY);
  26097. return pointInsidePolygonPoints(x, y, cutTrianglePts.topLeft) || pointInsidePolygonPoints(x, y, cutTrianglePts.topRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomRight) || pointInsidePolygonPoints(x, y, cutTrianglePts.bottomLeft);
  26098. }
  26099. };
  26100. };
  26101. BRp$2.generateBarrel = function () {
  26102. return this.nodeShapes['barrel'] = {
  26103. renderer: this,
  26104. name: 'barrel',
  26105. points: generateUnitNgonPointsFitToSquare(4, 0),
  26106. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26107. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height);
  26108. },
  26109. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26110. // use two fixed t values for the bezier curve approximation
  26111. var t0 = 0.15;
  26112. var t1 = 0.5;
  26113. var t2 = 0.85;
  26114. var bPts = this.generateBarrelBezierPts(width + 2 * padding, height + 2 * padding, nodeX, nodeY);
  26115. var approximateBarrelCurvePts = function approximateBarrelCurvePts(pts) {
  26116. // approximate curve pts based on the two t values
  26117. var m0 = qbezierPtAt({
  26118. x: pts[0],
  26119. y: pts[1]
  26120. }, {
  26121. x: pts[2],
  26122. y: pts[3]
  26123. }, {
  26124. x: pts[4],
  26125. y: pts[5]
  26126. }, t0);
  26127. var m1 = qbezierPtAt({
  26128. x: pts[0],
  26129. y: pts[1]
  26130. }, {
  26131. x: pts[2],
  26132. y: pts[3]
  26133. }, {
  26134. x: pts[4],
  26135. y: pts[5]
  26136. }, t1);
  26137. var m2 = qbezierPtAt({
  26138. x: pts[0],
  26139. y: pts[1]
  26140. }, {
  26141. x: pts[2],
  26142. y: pts[3]
  26143. }, {
  26144. x: pts[4],
  26145. y: pts[5]
  26146. }, t2);
  26147. return [pts[0], pts[1], m0.x, m0.y, m1.x, m1.y, m2.x, m2.y, pts[4], pts[5]];
  26148. };
  26149. var pts = [].concat(approximateBarrelCurvePts(bPts.topLeft), approximateBarrelCurvePts(bPts.topRight), approximateBarrelCurvePts(bPts.bottomRight), approximateBarrelCurvePts(bPts.bottomLeft));
  26150. return polygonIntersectLine(x, y, pts, nodeX, nodeY);
  26151. },
  26152. generateBarrelBezierPts: function generateBarrelBezierPts(width, height, centerX, centerY) {
  26153. var hh = height / 2;
  26154. var hw = width / 2;
  26155. var xBegin = centerX - hw;
  26156. var xEnd = centerX + hw;
  26157. var yBegin = centerY - hh;
  26158. var yEnd = centerY + hh;
  26159. var curveConstants = getBarrelCurveConstants(width, height);
  26160. var hOffset = curveConstants.heightOffset;
  26161. var wOffset = curveConstants.widthOffset;
  26162. var ctrlPtXOffset = curveConstants.ctrlPtOffsetPct * width;
  26163. // points are in clockwise order, inner (imaginary) control pt on [4, 5]
  26164. var pts = {
  26165. topLeft: [xBegin, yBegin + hOffset, xBegin + ctrlPtXOffset, yBegin, xBegin + wOffset, yBegin],
  26166. topRight: [xEnd - wOffset, yBegin, xEnd - ctrlPtXOffset, yBegin, xEnd, yBegin + hOffset],
  26167. bottomRight: [xEnd, yEnd - hOffset, xEnd - ctrlPtXOffset, yEnd, xEnd - wOffset, yEnd],
  26168. bottomLeft: [xBegin + wOffset, yEnd, xBegin + ctrlPtXOffset, yEnd, xBegin, yEnd - hOffset]
  26169. };
  26170. pts.topLeft.isTop = true;
  26171. pts.topRight.isTop = true;
  26172. pts.bottomLeft.isBottom = true;
  26173. pts.bottomRight.isBottom = true;
  26174. return pts;
  26175. },
  26176. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26177. var curveConstants = getBarrelCurveConstants(width, height);
  26178. var hOffset = curveConstants.heightOffset;
  26179. var wOffset = curveConstants.widthOffset;
  26180. // Check hBox
  26181. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - 2 * hOffset, [0, -1], padding)) {
  26182. return true;
  26183. }
  26184. // Check vBox
  26185. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - 2 * wOffset, height, [0, -1], padding)) {
  26186. return true;
  26187. }
  26188. var barrelCurvePts = this.generateBarrelBezierPts(width, height, centerX, centerY);
  26189. var getCurveT = function getCurveT(x, y, curvePts) {
  26190. var x0 = curvePts[4];
  26191. var x1 = curvePts[2];
  26192. var x2 = curvePts[0];
  26193. var y0 = curvePts[5];
  26194. // var y1 = curvePts[ 3 ];
  26195. var y2 = curvePts[1];
  26196. var xMin = Math.min(x0, x2);
  26197. var xMax = Math.max(x0, x2);
  26198. var yMin = Math.min(y0, y2);
  26199. var yMax = Math.max(y0, y2);
  26200. if (xMin <= x && x <= xMax && yMin <= y && y <= yMax) {
  26201. var coeff = bezierPtsToQuadCoeff(x0, x1, x2);
  26202. var roots = solveQuadratic(coeff[0], coeff[1], coeff[2], x);
  26203. var validRoots = roots.filter(function (r) {
  26204. return 0 <= r && r <= 1;
  26205. });
  26206. if (validRoots.length > 0) {
  26207. return validRoots[0];
  26208. }
  26209. }
  26210. return null;
  26211. };
  26212. var curveRegions = Object.keys(barrelCurvePts);
  26213. for (var i = 0; i < curveRegions.length; i++) {
  26214. var corner = curveRegions[i];
  26215. var cornerPts = barrelCurvePts[corner];
  26216. var t = getCurveT(x, y, cornerPts);
  26217. if (t == null) {
  26218. continue;
  26219. }
  26220. var y0 = cornerPts[5];
  26221. var y1 = cornerPts[3];
  26222. var y2 = cornerPts[1];
  26223. var bezY = qbezierAt(y0, y1, y2, t);
  26224. if (cornerPts.isTop && bezY <= y) {
  26225. return true;
  26226. }
  26227. if (cornerPts.isBottom && y <= bezY) {
  26228. return true;
  26229. }
  26230. }
  26231. return false;
  26232. }
  26233. };
  26234. };
  26235. BRp$2.generateBottomRoundrectangle = function () {
  26236. return this.nodeShapes['bottom-round-rectangle'] = this.nodeShapes['bottomroundrectangle'] = {
  26237. renderer: this,
  26238. name: 'bottom-round-rectangle',
  26239. points: generateUnitNgonPointsFitToSquare(4, 0),
  26240. draw: function draw(context, centerX, centerY, width, height, cornerRadius) {
  26241. this.renderer.nodeShapeImpl(this.name, context, centerX, centerY, width, height, this.points, cornerRadius);
  26242. },
  26243. intersectLine: function intersectLine(nodeX, nodeY, width, height, x, y, padding, cornerRadius) {
  26244. var topStartX = nodeX - (width / 2 + padding);
  26245. var topStartY = nodeY - (height / 2 + padding);
  26246. var topEndY = topStartY;
  26247. var topEndX = nodeX + (width / 2 + padding);
  26248. var topIntersections = finiteLinesIntersect(x, y, nodeX, nodeY, topStartX, topStartY, topEndX, topEndY, false);
  26249. if (topIntersections.length > 0) {
  26250. return topIntersections;
  26251. }
  26252. return roundRectangleIntersectLine(x, y, nodeX, nodeY, width, height, padding, cornerRadius);
  26253. },
  26254. checkPoint: function checkPoint(x, y, padding, width, height, centerX, centerY, cornerRadius) {
  26255. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(width, height) : cornerRadius;
  26256. var diam = 2 * cornerRadius;
  26257. // Check hBox
  26258. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width, height - diam, [0, -1], padding)) {
  26259. return true;
  26260. }
  26261. // Check vBox
  26262. if (pointInsidePolygon(x, y, this.points, centerX, centerY, width - diam, height, [0, -1], padding)) {
  26263. return true;
  26264. }
  26265. // check non-rounded top side
  26266. var outerWidth = width / 2 + 2 * padding;
  26267. var outerHeight = height / 2 + 2 * padding;
  26268. var points = [centerX - outerWidth, centerY - outerHeight, centerX - outerWidth, centerY, centerX + outerWidth, centerY, centerX + outerWidth, centerY - outerHeight];
  26269. if (pointInsidePolygonPoints(x, y, points)) {
  26270. return true;
  26271. }
  26272. // Check bottom right quarter circle
  26273. if (checkInEllipse(x, y, diam, diam, centerX + width / 2 - cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
  26274. return true;
  26275. }
  26276. // Check bottom left quarter circle
  26277. if (checkInEllipse(x, y, diam, diam, centerX - width / 2 + cornerRadius, centerY + height / 2 - cornerRadius, padding)) {
  26278. return true;
  26279. }
  26280. return false;
  26281. }
  26282. };
  26283. };
  26284. BRp$2.registerNodeShapes = function () {
  26285. var nodeShapes = this.nodeShapes = {};
  26286. var renderer = this;
  26287. this.generateEllipse();
  26288. this.generatePolygon('triangle', generateUnitNgonPointsFitToSquare(3, 0));
  26289. this.generateRoundPolygon('round-triangle', generateUnitNgonPointsFitToSquare(3, 0));
  26290. this.generatePolygon('rectangle', generateUnitNgonPointsFitToSquare(4, 0));
  26291. nodeShapes['square'] = nodeShapes['rectangle'];
  26292. this.generateRoundRectangle();
  26293. this.generateCutRectangle();
  26294. this.generateBarrel();
  26295. this.generateBottomRoundrectangle();
  26296. {
  26297. var diamondPoints = [0, 1, 1, 0, 0, -1, -1, 0];
  26298. this.generatePolygon('diamond', diamondPoints);
  26299. this.generateRoundPolygon('round-diamond', diamondPoints);
  26300. }
  26301. this.generatePolygon('pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  26302. this.generateRoundPolygon('round-pentagon', generateUnitNgonPointsFitToSquare(5, 0));
  26303. this.generatePolygon('hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  26304. this.generateRoundPolygon('round-hexagon', generateUnitNgonPointsFitToSquare(6, 0));
  26305. this.generatePolygon('heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  26306. this.generateRoundPolygon('round-heptagon', generateUnitNgonPointsFitToSquare(7, 0));
  26307. this.generatePolygon('octagon', generateUnitNgonPointsFitToSquare(8, 0));
  26308. this.generateRoundPolygon('round-octagon', generateUnitNgonPointsFitToSquare(8, 0));
  26309. var star5Points = new Array(20);
  26310. {
  26311. var outerPoints = generateUnitNgonPoints(5, 0);
  26312. var innerPoints = generateUnitNgonPoints(5, Math.PI / 5);
  26313. // Outer radius is 1; inner radius of star is smaller
  26314. var innerRadius = 0.5 * (3 - Math.sqrt(5));
  26315. innerRadius *= 1.57;
  26316. for (var i = 0; i < innerPoints.length / 2; i++) {
  26317. innerPoints[i * 2] *= innerRadius;
  26318. innerPoints[i * 2 + 1] *= innerRadius;
  26319. }
  26320. for (var i = 0; i < 20 / 4; i++) {
  26321. star5Points[i * 4] = outerPoints[i * 2];
  26322. star5Points[i * 4 + 1] = outerPoints[i * 2 + 1];
  26323. star5Points[i * 4 + 2] = innerPoints[i * 2];
  26324. star5Points[i * 4 + 3] = innerPoints[i * 2 + 1];
  26325. }
  26326. }
  26327. star5Points = fitPolygonToSquare(star5Points);
  26328. this.generatePolygon('star', star5Points);
  26329. this.generatePolygon('vee', [-1, -1, 0, -0.333, 1, -1, 0, 1]);
  26330. this.generatePolygon('rhomboid', [-1, -1, 0.333, -1, 1, 1, -0.333, 1]);
  26331. this.generatePolygon('right-rhomboid', [-0.333, -1, 1, -1, 0.333, 1, -1, 1]);
  26332. 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]);
  26333. {
  26334. var tagPoints = [-1, -1, 0.25, -1, 1, 0, 0.25, 1, -1, 1];
  26335. this.generatePolygon('tag', tagPoints);
  26336. this.generateRoundPolygon('round-tag', tagPoints);
  26337. }
  26338. nodeShapes.makePolygon = function (points) {
  26339. // use caching on user-specified polygons so they are as fast as native shapes
  26340. var key = points.join('$');
  26341. var name = 'polygon-' + key;
  26342. var shape;
  26343. if (shape = this[name]) {
  26344. // got cached shape
  26345. return shape;
  26346. }
  26347. // create and cache new shape
  26348. return renderer.generatePolygon(name, points);
  26349. };
  26350. };
  26351. var BRp$1 = {};
  26352. BRp$1.timeToRender = function () {
  26353. return this.redrawTotalTime / this.redrawCount;
  26354. };
  26355. BRp$1.redraw = function (options) {
  26356. options = options || staticEmptyObject();
  26357. var r = this;
  26358. if (r.averageRedrawTime === undefined) {
  26359. r.averageRedrawTime = 0;
  26360. }
  26361. if (r.lastRedrawTime === undefined) {
  26362. r.lastRedrawTime = 0;
  26363. }
  26364. if (r.lastDrawTime === undefined) {
  26365. r.lastDrawTime = 0;
  26366. }
  26367. r.requestedFrame = true;
  26368. r.renderOptions = options;
  26369. };
  26370. BRp$1.beforeRender = function (fn, priority) {
  26371. // the renderer can't add tick callbacks when destroyed
  26372. if (this.destroyed) {
  26373. return;
  26374. }
  26375. if (priority == null) {
  26376. error('Priority is not optional for beforeRender');
  26377. }
  26378. var cbs = this.beforeRenderCallbacks;
  26379. cbs.push({
  26380. fn: fn,
  26381. priority: priority
  26382. });
  26383. // higher priority callbacks executed first
  26384. cbs.sort(function (a, b) {
  26385. return b.priority - a.priority;
  26386. });
  26387. };
  26388. var beforeRenderCallbacks = function beforeRenderCallbacks(r, willDraw, startTime) {
  26389. var cbs = r.beforeRenderCallbacks;
  26390. for (var i = 0; i < cbs.length; i++) {
  26391. cbs[i].fn(willDraw, startTime);
  26392. }
  26393. };
  26394. BRp$1.startRenderLoop = function () {
  26395. var r = this;
  26396. var cy = r.cy;
  26397. if (r.renderLoopStarted) {
  26398. return;
  26399. } else {
  26400. r.renderLoopStarted = true;
  26401. }
  26402. var _renderFn = function renderFn(requestTime) {
  26403. if (r.destroyed) {
  26404. return;
  26405. }
  26406. if (cy.batching()) ; else if (r.requestedFrame && !r.skipFrame) {
  26407. beforeRenderCallbacks(r, true, requestTime);
  26408. var startTime = performanceNow();
  26409. r.render(r.renderOptions);
  26410. var endTime = r.lastDrawTime = performanceNow();
  26411. if (r.averageRedrawTime === undefined) {
  26412. r.averageRedrawTime = endTime - startTime;
  26413. }
  26414. if (r.redrawCount === undefined) {
  26415. r.redrawCount = 0;
  26416. }
  26417. r.redrawCount++;
  26418. if (r.redrawTotalTime === undefined) {
  26419. r.redrawTotalTime = 0;
  26420. }
  26421. var duration = endTime - startTime;
  26422. r.redrawTotalTime += duration;
  26423. r.lastRedrawTime = duration;
  26424. // use a weighted average with a bias from the previous average so we don't spike so easily
  26425. r.averageRedrawTime = r.averageRedrawTime / 2 + duration / 2;
  26426. r.requestedFrame = false;
  26427. } else {
  26428. beforeRenderCallbacks(r, false, requestTime);
  26429. }
  26430. r.skipFrame = false;
  26431. requestAnimationFrame(_renderFn);
  26432. };
  26433. requestAnimationFrame(_renderFn);
  26434. };
  26435. var BaseRenderer = function BaseRenderer(options) {
  26436. this.init(options);
  26437. };
  26438. var BR = BaseRenderer;
  26439. var BRp = BR.prototype;
  26440. BRp.clientFunctions = ['redrawHint', 'render', 'renderTo', 'matchCanvasSize', 'nodeShapeImpl', 'arrowShapeImpl'];
  26441. BRp.init = function (options) {
  26442. var r = this;
  26443. r.options = options;
  26444. r.cy = options.cy;
  26445. var ctr = r.container = options.cy.container();
  26446. var containerWindow = r.cy.window();
  26447. // prepend a stylesheet in the head such that
  26448. if (containerWindow) {
  26449. var document = containerWindow.document;
  26450. var head = document.head;
  26451. var stylesheetId = '__________cytoscape_stylesheet';
  26452. var className = '__________cytoscape_container';
  26453. var stylesheetAlreadyExists = document.getElementById(stylesheetId) != null;
  26454. if (ctr.className.indexOf(className) < 0) {
  26455. ctr.className = (ctr.className || '') + ' ' + className;
  26456. }
  26457. if (!stylesheetAlreadyExists) {
  26458. var stylesheet = document.createElement('style');
  26459. stylesheet.id = stylesheetId;
  26460. stylesheet.textContent = '.' + className + ' { position: relative; }';
  26461. head.insertBefore(stylesheet, head.children[0]); // first so lowest priority
  26462. }
  26463. var computedStyle = containerWindow.getComputedStyle(ctr);
  26464. var position = computedStyle.getPropertyValue('position');
  26465. if (position === 'static') {
  26466. warn('A Cytoscape container has style position:static and so can not use UI extensions properly');
  26467. }
  26468. }
  26469. r.selection = [undefined, undefined, undefined, undefined, 0]; // Coordinates for selection box, plus enabled flag
  26470. r.bezierProjPcts = [0.05, 0.225, 0.4, 0.5, 0.6, 0.775, 0.95];
  26471. //--Pointer-related data
  26472. r.hoverData = {
  26473. down: null,
  26474. last: null,
  26475. downTime: null,
  26476. triggerMode: null,
  26477. dragging: false,
  26478. initialPan: [null, null],
  26479. capture: false
  26480. };
  26481. r.dragData = {
  26482. possibleDragElements: []
  26483. };
  26484. r.touchData = {
  26485. start: null,
  26486. capture: false,
  26487. // These 3 fields related to tap, taphold events
  26488. startPosition: [null, null, null, null, null, null],
  26489. singleTouchStartTime: null,
  26490. singleTouchMoved: true,
  26491. now: [null, null, null, null, null, null],
  26492. earlier: [null, null, null, null, null, null]
  26493. };
  26494. r.redraws = 0;
  26495. r.showFps = options.showFps;
  26496. r.debug = options.debug;
  26497. r.webgl = options.webgl;
  26498. r.hideEdgesOnViewport = options.hideEdgesOnViewport;
  26499. r.textureOnViewport = options.textureOnViewport;
  26500. r.wheelSensitivity = options.wheelSensitivity;
  26501. r.motionBlurEnabled = options.motionBlur; // on by default
  26502. r.forcedPixelRatio = number$1(options.pixelRatio) ? options.pixelRatio : null;
  26503. r.motionBlur = options.motionBlur; // for initial kick off
  26504. r.motionBlurOpacity = options.motionBlurOpacity;
  26505. r.motionBlurTransparency = 1 - r.motionBlurOpacity;
  26506. r.motionBlurPxRatio = 1;
  26507. r.mbPxRBlurry = 1; //0.8;
  26508. r.minMbLowQualFrames = 4;
  26509. r.fullQualityMb = false;
  26510. r.clearedForMotionBlur = [];
  26511. r.desktopTapThreshold = options.desktopTapThreshold;
  26512. r.desktopTapThreshold2 = options.desktopTapThreshold * options.desktopTapThreshold;
  26513. r.touchTapThreshold = options.touchTapThreshold;
  26514. r.touchTapThreshold2 = options.touchTapThreshold * options.touchTapThreshold;
  26515. r.tapholdDuration = 500;
  26516. r.bindings = [];
  26517. r.beforeRenderCallbacks = [];
  26518. r.beforeRenderPriorities = {
  26519. // higher priority execs before lower one
  26520. animations: 400,
  26521. eleCalcs: 300,
  26522. eleTxrDeq: 200,
  26523. lyrTxrDeq: 150,
  26524. lyrTxrSkip: 100
  26525. };
  26526. r.registerNodeShapes();
  26527. r.registerArrowShapes();
  26528. r.registerCalculationListeners();
  26529. };
  26530. BRp.notify = function (eventName, eles) {
  26531. var r = this;
  26532. var cy = r.cy;
  26533. // the renderer can't be notified after it's destroyed
  26534. if (this.destroyed) {
  26535. return;
  26536. }
  26537. if (eventName === 'init') {
  26538. r.load();
  26539. return;
  26540. }
  26541. if (eventName === 'destroy') {
  26542. r.destroy();
  26543. return;
  26544. }
  26545. if (eventName === 'add' || eventName === 'remove' || eventName === 'move' && cy.hasCompoundNodes() || eventName === 'load' || eventName === 'zorder' || eventName === 'mount') {
  26546. r.invalidateCachedZSortedEles();
  26547. }
  26548. if (eventName === 'viewport') {
  26549. r.redrawHint('select', true);
  26550. }
  26551. if (eventName === 'gc') {
  26552. r.redrawHint('gc', true);
  26553. }
  26554. if (eventName === 'load' || eventName === 'resize' || eventName === 'mount') {
  26555. r.invalidateContainerClientCoordsCache();
  26556. r.matchCanvasSize(r.container);
  26557. }
  26558. r.redrawHint('eles', true);
  26559. r.redrawHint('drag', true);
  26560. this.startRenderLoop();
  26561. this.redraw();
  26562. };
  26563. BRp.destroy = function () {
  26564. var r = this;
  26565. r.destroyed = true;
  26566. r.cy.stopAnimationLoop();
  26567. for (var i = 0; i < r.bindings.length; i++) {
  26568. var binding = r.bindings[i];
  26569. var b = binding;
  26570. var tgt = b.target;
  26571. (tgt.off || tgt.removeEventListener).apply(tgt, b.args);
  26572. }
  26573. r.bindings = [];
  26574. r.beforeRenderCallbacks = [];
  26575. r.onUpdateEleCalcsFns = [];
  26576. if (r.removeObserver) {
  26577. r.removeObserver.disconnect();
  26578. }
  26579. if (r.styleObserver) {
  26580. r.styleObserver.disconnect();
  26581. }
  26582. if (r.resizeObserver) {
  26583. r.resizeObserver.disconnect();
  26584. }
  26585. if (r.labelCalcDiv) {
  26586. try {
  26587. document.body.removeChild(r.labelCalcDiv); // eslint-disable-line no-undef
  26588. } catch (e) {
  26589. // ie10 issue #1014
  26590. }
  26591. }
  26592. };
  26593. BRp.isHeadless = function () {
  26594. return false;
  26595. };
  26596. [BRp$f, BRp$5, BRp$4, BRp$3, BRp$2, BRp$1].forEach(function (props) {
  26597. extend(BRp, props);
  26598. });
  26599. var fullFpsTime = 1000 / 60; // assume 60 frames per second
  26600. var defs = {
  26601. setupDequeueing: function setupDequeueing(opts) {
  26602. return function setupDequeueingImpl() {
  26603. var self = this;
  26604. var r = this.renderer;
  26605. if (self.dequeueingSetup) {
  26606. return;
  26607. } else {
  26608. self.dequeueingSetup = true;
  26609. }
  26610. var queueRedraw = debounce(function () {
  26611. r.redrawHint('eles', true);
  26612. r.redrawHint('drag', true);
  26613. r.redraw();
  26614. }, opts.deqRedrawThreshold);
  26615. var dequeue = function dequeue(willDraw, frameStartTime) {
  26616. var startTime = performanceNow();
  26617. var avgRenderTime = r.averageRedrawTime;
  26618. var renderTime = r.lastRedrawTime;
  26619. var deqd = [];
  26620. var extent = r.cy.extent();
  26621. var pixelRatio = r.getPixelRatio();
  26622. // if we aren't in a tick that causes a draw, then the rendered style
  26623. // queue won't automatically be flushed before dequeueing starts
  26624. if (!willDraw) {
  26625. r.flushRenderedStyleQueue();
  26626. }
  26627. while (true) {
  26628. // eslint-disable-line no-constant-condition
  26629. var now = performanceNow();
  26630. var duration = now - startTime;
  26631. var frameDuration = now - frameStartTime;
  26632. if (renderTime < fullFpsTime) {
  26633. // if we're rendering faster than the ideal fps, then do dequeueing
  26634. // during all of the remaining frame time
  26635. var timeAvailable = fullFpsTime - (willDraw ? avgRenderTime : 0);
  26636. if (frameDuration >= opts.deqFastCost * timeAvailable) {
  26637. break;
  26638. }
  26639. } else {
  26640. if (willDraw) {
  26641. if (duration >= opts.deqCost * renderTime || duration >= opts.deqAvgCost * avgRenderTime) {
  26642. break;
  26643. }
  26644. } else if (frameDuration >= opts.deqNoDrawCost * fullFpsTime) {
  26645. break;
  26646. }
  26647. }
  26648. var thisDeqd = opts.deq(self, pixelRatio, extent);
  26649. if (thisDeqd.length > 0) {
  26650. for (var i = 0; i < thisDeqd.length; i++) {
  26651. deqd.push(thisDeqd[i]);
  26652. }
  26653. } else {
  26654. break;
  26655. }
  26656. }
  26657. // callbacks on dequeue
  26658. if (deqd.length > 0) {
  26659. opts.onDeqd(self, deqd);
  26660. if (!willDraw && opts.shouldRedraw(self, deqd, pixelRatio, extent)) {
  26661. queueRedraw();
  26662. }
  26663. }
  26664. };
  26665. var priority = opts.priority || noop$1;
  26666. r.beforeRender(dequeue, priority(self));
  26667. };
  26668. }
  26669. };
  26670. // Allows lookups for (ele, lvl) => cache.
  26671. // Uses keys so elements may share the same cache.
  26672. var ElementTextureCacheLookup = /*#__PURE__*/function () {
  26673. function ElementTextureCacheLookup(getKey) {
  26674. var doesEleInvalidateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : falsify;
  26675. _classCallCheck(this, ElementTextureCacheLookup);
  26676. this.idsByKey = new Map$1();
  26677. this.keyForId = new Map$1();
  26678. this.cachesByLvl = new Map$1();
  26679. this.lvls = [];
  26680. this.getKey = getKey;
  26681. this.doesEleInvalidateKey = doesEleInvalidateKey;
  26682. }
  26683. return _createClass(ElementTextureCacheLookup, [{
  26684. key: "getIdsFor",
  26685. value: function getIdsFor(key) {
  26686. if (key == null) {
  26687. error("Can not get id list for null key");
  26688. }
  26689. var idsByKey = this.idsByKey;
  26690. var ids = this.idsByKey.get(key);
  26691. if (!ids) {
  26692. ids = new Set$1();
  26693. idsByKey.set(key, ids);
  26694. }
  26695. return ids;
  26696. }
  26697. }, {
  26698. key: "addIdForKey",
  26699. value: function addIdForKey(key, id) {
  26700. if (key != null) {
  26701. this.getIdsFor(key).add(id);
  26702. }
  26703. }
  26704. }, {
  26705. key: "deleteIdForKey",
  26706. value: function deleteIdForKey(key, id) {
  26707. if (key != null) {
  26708. this.getIdsFor(key)["delete"](id);
  26709. }
  26710. }
  26711. }, {
  26712. key: "getNumberOfIdsForKey",
  26713. value: function getNumberOfIdsForKey(key) {
  26714. if (key == null) {
  26715. return 0;
  26716. } else {
  26717. return this.getIdsFor(key).size;
  26718. }
  26719. }
  26720. }, {
  26721. key: "updateKeyMappingFor",
  26722. value: function updateKeyMappingFor(ele) {
  26723. var id = ele.id();
  26724. var prevKey = this.keyForId.get(id);
  26725. var currKey = this.getKey(ele);
  26726. this.deleteIdForKey(prevKey, id);
  26727. this.addIdForKey(currKey, id);
  26728. this.keyForId.set(id, currKey);
  26729. }
  26730. }, {
  26731. key: "deleteKeyMappingFor",
  26732. value: function deleteKeyMappingFor(ele) {
  26733. var id = ele.id();
  26734. var prevKey = this.keyForId.get(id);
  26735. this.deleteIdForKey(prevKey, id);
  26736. this.keyForId["delete"](id);
  26737. }
  26738. }, {
  26739. key: "keyHasChangedFor",
  26740. value: function keyHasChangedFor(ele) {
  26741. var id = ele.id();
  26742. var prevKey = this.keyForId.get(id);
  26743. var newKey = this.getKey(ele);
  26744. return prevKey !== newKey;
  26745. }
  26746. }, {
  26747. key: "isInvalid",
  26748. value: function isInvalid(ele) {
  26749. return this.keyHasChangedFor(ele) || this.doesEleInvalidateKey(ele);
  26750. }
  26751. }, {
  26752. key: "getCachesAt",
  26753. value: function getCachesAt(lvl) {
  26754. var cachesByLvl = this.cachesByLvl,
  26755. lvls = this.lvls;
  26756. var caches = cachesByLvl.get(lvl);
  26757. if (!caches) {
  26758. caches = new Map$1();
  26759. cachesByLvl.set(lvl, caches);
  26760. lvls.push(lvl);
  26761. }
  26762. return caches;
  26763. }
  26764. }, {
  26765. key: "getCache",
  26766. value: function getCache(key, lvl) {
  26767. return this.getCachesAt(lvl).get(key);
  26768. }
  26769. }, {
  26770. key: "get",
  26771. value: function get(ele, lvl) {
  26772. var key = this.getKey(ele);
  26773. var cache = this.getCache(key, lvl);
  26774. // getting for an element may need to add to the id list b/c eles can share keys
  26775. if (cache != null) {
  26776. this.updateKeyMappingFor(ele);
  26777. }
  26778. return cache;
  26779. }
  26780. }, {
  26781. key: "getForCachedKey",
  26782. value: function getForCachedKey(ele, lvl) {
  26783. var key = this.keyForId.get(ele.id()); // n.b. use cached key, not newly computed key
  26784. var cache = this.getCache(key, lvl);
  26785. return cache;
  26786. }
  26787. }, {
  26788. key: "hasCache",
  26789. value: function hasCache(key, lvl) {
  26790. return this.getCachesAt(lvl).has(key);
  26791. }
  26792. }, {
  26793. key: "has",
  26794. value: function has(ele, lvl) {
  26795. var key = this.getKey(ele);
  26796. return this.hasCache(key, lvl);
  26797. }
  26798. }, {
  26799. key: "setCache",
  26800. value: function setCache(key, lvl, cache) {
  26801. cache.key = key;
  26802. this.getCachesAt(lvl).set(key, cache);
  26803. }
  26804. }, {
  26805. key: "set",
  26806. value: function set(ele, lvl, cache) {
  26807. var key = this.getKey(ele);
  26808. this.setCache(key, lvl, cache);
  26809. this.updateKeyMappingFor(ele);
  26810. }
  26811. }, {
  26812. key: "deleteCache",
  26813. value: function deleteCache(key, lvl) {
  26814. this.getCachesAt(lvl)["delete"](key);
  26815. }
  26816. }, {
  26817. key: "delete",
  26818. value: function _delete(ele, lvl) {
  26819. var key = this.getKey(ele);
  26820. this.deleteCache(key, lvl);
  26821. }
  26822. }, {
  26823. key: "invalidateKey",
  26824. value: function invalidateKey(key) {
  26825. var _this = this;
  26826. this.lvls.forEach(function (lvl) {
  26827. return _this.deleteCache(key, lvl);
  26828. });
  26829. }
  26830. // returns true if no other eles reference the invalidated cache (n.b. other eles may need the cache with the same key)
  26831. }, {
  26832. key: "invalidate",
  26833. value: function invalidate(ele) {
  26834. var id = ele.id();
  26835. var key = this.keyForId.get(id); // n.b. use stored key rather than current (potential key)
  26836. this.deleteKeyMappingFor(ele);
  26837. var entireKeyInvalidated = this.doesEleInvalidateKey(ele);
  26838. if (entireKeyInvalidated) {
  26839. // clear mapping for current key
  26840. this.invalidateKey(key);
  26841. }
  26842. return entireKeyInvalidated || this.getNumberOfIdsForKey(key) === 0;
  26843. }
  26844. }]);
  26845. }();
  26846. var minTxrH = 25; // the size of the texture cache for small height eles (special case)
  26847. var txrStepH = 50; // the min size of the regular cache, and the size it increases with each step up
  26848. var minLvl$1 = -4; // when scaling smaller than that we don't need to re-render
  26849. var maxLvl$1 = 3; // when larger than this scale just render directly (caching is not helpful)
  26850. var maxZoom$1 = 7.99; // beyond this zoom level, layered textures are not used
  26851. var eleTxrSpacing = 8; // spacing between elements on textures to avoid blitting overlaps
  26852. var defTxrWidth = 1024; // default/minimum texture width
  26853. var maxTxrW = 1024; // the maximum width of a texture
  26854. var maxTxrH = 1024; // the maximum height of a texture
  26855. var minUtility = 0.2; // if usage of texture is less than this, it is retired
  26856. var maxFullness = 0.8; // fullness of texture after which queue removal is checked
  26857. var maxFullnessChecks = 10; // dequeued after this many checks
  26858. var deqCost$1 = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
  26859. var deqAvgCost$1 = 0.1; // % of add'l rendering cost compared to average overall redraw time
  26860. var deqNoDrawCost$1 = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
  26861. var deqFastCost$1 = 0.9; // % of frame time to be used when >60fps
  26862. var deqRedrawThreshold$1 = 100; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
  26863. var maxDeqSize$1 = 1; // number of eles to dequeue and render at higher texture in each batch
  26864. var getTxrReasons = {
  26865. dequeue: 'dequeue',
  26866. downscale: 'downscale',
  26867. highQuality: 'highQuality'
  26868. };
  26869. var initDefaults = defaults$g({
  26870. getKey: null,
  26871. doesEleInvalidateKey: falsify,
  26872. drawElement: null,
  26873. getBoundingBox: null,
  26874. getRotationPoint: null,
  26875. getRotationOffset: null,
  26876. isVisible: trueify,
  26877. allowEdgeTxrCaching: true,
  26878. allowParentTxrCaching: true
  26879. });
  26880. var ElementTextureCache = function ElementTextureCache(renderer, initOptions) {
  26881. var self = this;
  26882. self.renderer = renderer;
  26883. self.onDequeues = [];
  26884. var opts = initDefaults(initOptions);
  26885. extend(self, opts);
  26886. self.lookup = new ElementTextureCacheLookup(opts.getKey, opts.doesEleInvalidateKey);
  26887. self.setupDequeueing();
  26888. };
  26889. var ETCp = ElementTextureCache.prototype;
  26890. ETCp.reasons = getTxrReasons;
  26891. // the list of textures in which new subtextures for elements can be placed
  26892. ETCp.getTextureQueue = function (txrH) {
  26893. var self = this;
  26894. self.eleImgCaches = self.eleImgCaches || {};
  26895. return self.eleImgCaches[txrH] = self.eleImgCaches[txrH] || [];
  26896. };
  26897. // the list of usused textures which can be recycled (in use in texture queue)
  26898. ETCp.getRetiredTextureQueue = function (txrH) {
  26899. var self = this;
  26900. var rtxtrQs = self.eleImgCaches.retired = self.eleImgCaches.retired || {};
  26901. var rtxtrQ = rtxtrQs[txrH] = rtxtrQs[txrH] || [];
  26902. return rtxtrQ;
  26903. };
  26904. // queue of element draw requests at different scale levels
  26905. ETCp.getElementQueue = function () {
  26906. var self = this;
  26907. var q = self.eleCacheQueue = self.eleCacheQueue || new Heap(function (a, b) {
  26908. return b.reqs - a.reqs;
  26909. });
  26910. return q;
  26911. };
  26912. // queue of element draw requests at different scale levels (element id lookup)
  26913. ETCp.getElementKeyToQueue = function () {
  26914. var self = this;
  26915. var k2q = self.eleKeyToCacheQueue = self.eleKeyToCacheQueue || {};
  26916. return k2q;
  26917. };
  26918. ETCp.getElement = function (ele, bb, pxRatio, lvl, reason) {
  26919. var self = this;
  26920. var r = this.renderer;
  26921. var zoom = r.cy.zoom();
  26922. var lookup = this.lookup;
  26923. if (!bb || bb.w === 0 || bb.h === 0 || isNaN(bb.w) || isNaN(bb.h) || !ele.visible() || ele.removed()) {
  26924. return null;
  26925. }
  26926. if (!self.allowEdgeTxrCaching && ele.isEdge() || !self.allowParentTxrCaching && ele.isParent()) {
  26927. return null;
  26928. }
  26929. if (lvl == null) {
  26930. lvl = Math.ceil(log2(zoom * pxRatio));
  26931. }
  26932. if (lvl < minLvl$1) {
  26933. lvl = minLvl$1;
  26934. } else if (zoom >= maxZoom$1 || lvl > maxLvl$1) {
  26935. return null;
  26936. }
  26937. var scale = Math.pow(2, lvl);
  26938. var eleScaledH = bb.h * scale;
  26939. var eleScaledW = bb.w * scale;
  26940. var scaledLabelShown = r.eleTextBiggerThanMin(ele, scale);
  26941. if (!this.isVisible(ele, scaledLabelShown)) {
  26942. return null;
  26943. }
  26944. var eleCache = lookup.get(ele, lvl);
  26945. // if this get was on an unused/invalidated cache, then restore the texture usage metric
  26946. if (eleCache && eleCache.invalidated) {
  26947. eleCache.invalidated = false;
  26948. eleCache.texture.invalidatedWidth -= eleCache.width;
  26949. }
  26950. if (eleCache) {
  26951. return eleCache;
  26952. }
  26953. var txrH; // which texture height this ele belongs to
  26954. if (eleScaledH <= minTxrH) {
  26955. txrH = minTxrH;
  26956. } else if (eleScaledH <= txrStepH) {
  26957. txrH = txrStepH;
  26958. } else {
  26959. txrH = Math.ceil(eleScaledH / txrStepH) * txrStepH;
  26960. }
  26961. if (eleScaledH > maxTxrH || eleScaledW > maxTxrW) {
  26962. return null; // caching large elements is not efficient
  26963. }
  26964. var txrQ = self.getTextureQueue(txrH);
  26965. // first try the second last one in case it has space at the end
  26966. var txr = txrQ[txrQ.length - 2];
  26967. var addNewTxr = function addNewTxr() {
  26968. return self.recycleTexture(txrH, eleScaledW) || self.addTexture(txrH, eleScaledW);
  26969. };
  26970. // try the last one if there is no second last one
  26971. if (!txr) {
  26972. txr = txrQ[txrQ.length - 1];
  26973. }
  26974. // if the last one doesn't exist, we need a first one
  26975. if (!txr) {
  26976. txr = addNewTxr();
  26977. }
  26978. // if there's no room in the current texture, we need a new one
  26979. if (txr.width - txr.usedWidth < eleScaledW) {
  26980. txr = addNewTxr();
  26981. }
  26982. var scalableFrom = function scalableFrom(otherCache) {
  26983. return otherCache && otherCache.scaledLabelShown === scaledLabelShown;
  26984. };
  26985. var deqing = reason && reason === getTxrReasons.dequeue;
  26986. var highQualityReq = reason && reason === getTxrReasons.highQuality;
  26987. var downscaleReq = reason && reason === getTxrReasons.downscale;
  26988. var higherCache; // the nearest cache with a higher level
  26989. for (var l = lvl + 1; l <= maxLvl$1; l++) {
  26990. var c = lookup.get(ele, l);
  26991. if (c) {
  26992. higherCache = c;
  26993. break;
  26994. }
  26995. }
  26996. var oneUpCache = higherCache && higherCache.level === lvl + 1 ? higherCache : null;
  26997. var downscale = function downscale() {
  26998. txr.context.drawImage(oneUpCache.texture.canvas, oneUpCache.x, 0, oneUpCache.width, oneUpCache.height, txr.usedWidth, 0, eleScaledW, eleScaledH);
  26999. };
  27000. // reset ele area in texture
  27001. txr.context.setTransform(1, 0, 0, 1, 0, 0);
  27002. txr.context.clearRect(txr.usedWidth, 0, eleScaledW, txrH);
  27003. if (scalableFrom(oneUpCache)) {
  27004. // then we can relatively cheaply rescale the existing image w/o rerendering
  27005. downscale();
  27006. } else if (scalableFrom(higherCache)) {
  27007. // then use the higher cache for now and queue the next level down
  27008. // to cheaply scale towards the smaller level
  27009. if (highQualityReq) {
  27010. for (var _l = higherCache.level; _l > lvl; _l--) {
  27011. oneUpCache = self.getElement(ele, bb, pxRatio, _l, getTxrReasons.downscale);
  27012. }
  27013. downscale();
  27014. } else {
  27015. self.queueElement(ele, higherCache.level - 1);
  27016. return higherCache;
  27017. }
  27018. } else {
  27019. var lowerCache; // the nearest cache with a lower level
  27020. if (!deqing && !highQualityReq && !downscaleReq) {
  27021. for (var _l2 = lvl - 1; _l2 >= minLvl$1; _l2--) {
  27022. var _c = lookup.get(ele, _l2);
  27023. if (_c) {
  27024. lowerCache = _c;
  27025. break;
  27026. }
  27027. }
  27028. }
  27029. if (scalableFrom(lowerCache)) {
  27030. // then use the lower quality cache for now and queue the better one for later
  27031. self.queueElement(ele, lvl);
  27032. return lowerCache;
  27033. }
  27034. txr.context.translate(txr.usedWidth, 0);
  27035. txr.context.scale(scale, scale);
  27036. this.drawElement(txr.context, ele, bb, scaledLabelShown, false);
  27037. txr.context.scale(1 / scale, 1 / scale);
  27038. txr.context.translate(-txr.usedWidth, 0);
  27039. }
  27040. eleCache = {
  27041. x: txr.usedWidth,
  27042. texture: txr,
  27043. level: lvl,
  27044. scale: scale,
  27045. width: eleScaledW,
  27046. height: eleScaledH,
  27047. scaledLabelShown: scaledLabelShown
  27048. };
  27049. txr.usedWidth += Math.ceil(eleScaledW + eleTxrSpacing);
  27050. txr.eleCaches.push(eleCache);
  27051. lookup.set(ele, lvl, eleCache);
  27052. self.checkTextureFullness(txr);
  27053. return eleCache;
  27054. };
  27055. ETCp.invalidateElements = function (eles) {
  27056. for (var i = 0; i < eles.length; i++) {
  27057. this.invalidateElement(eles[i]);
  27058. }
  27059. };
  27060. ETCp.invalidateElement = function (ele) {
  27061. var self = this;
  27062. var lookup = self.lookup;
  27063. var caches = [];
  27064. var invalid = lookup.isInvalid(ele);
  27065. if (!invalid) {
  27066. return; // override the invalidation request if the element key has not changed
  27067. }
  27068. for (var lvl = minLvl$1; lvl <= maxLvl$1; lvl++) {
  27069. var cache = lookup.getForCachedKey(ele, lvl);
  27070. if (cache) {
  27071. caches.push(cache);
  27072. }
  27073. }
  27074. var noOtherElesUseCache = lookup.invalidate(ele);
  27075. if (noOtherElesUseCache) {
  27076. for (var i = 0; i < caches.length; i++) {
  27077. var _cache = caches[i];
  27078. var txr = _cache.texture;
  27079. // remove space from the texture it belongs to
  27080. txr.invalidatedWidth += _cache.width;
  27081. // mark the cache as invalidated
  27082. _cache.invalidated = true;
  27083. // retire the texture if its utility is low
  27084. self.checkTextureUtility(txr);
  27085. }
  27086. }
  27087. // remove from queue since the old req was for the old state
  27088. self.removeFromQueue(ele);
  27089. };
  27090. ETCp.checkTextureUtility = function (txr) {
  27091. // invalidate all entries in the cache if the cache size is small
  27092. if (txr.invalidatedWidth >= minUtility * txr.width) {
  27093. this.retireTexture(txr);
  27094. }
  27095. };
  27096. ETCp.checkTextureFullness = function (txr) {
  27097. // if texture has been mostly filled and passed over several times, remove
  27098. // it from the queue so we don't need to waste time looking at it to put new things
  27099. var self = this;
  27100. var txrQ = self.getTextureQueue(txr.height);
  27101. if (txr.usedWidth / txr.width > maxFullness && txr.fullnessChecks >= maxFullnessChecks) {
  27102. removeFromArray(txrQ, txr);
  27103. } else {
  27104. txr.fullnessChecks++;
  27105. }
  27106. };
  27107. ETCp.retireTexture = function (txr) {
  27108. var self = this;
  27109. var txrH = txr.height;
  27110. var txrQ = self.getTextureQueue(txrH);
  27111. var lookup = this.lookup;
  27112. // retire the texture from the active / searchable queue:
  27113. removeFromArray(txrQ, txr);
  27114. txr.retired = true;
  27115. // remove the refs from the eles to the caches:
  27116. var eleCaches = txr.eleCaches;
  27117. for (var i = 0; i < eleCaches.length; i++) {
  27118. var eleCache = eleCaches[i];
  27119. lookup.deleteCache(eleCache.key, eleCache.level);
  27120. }
  27121. clearArray(eleCaches);
  27122. // add the texture to a retired queue so it can be recycled in future:
  27123. var rtxtrQ = self.getRetiredTextureQueue(txrH);
  27124. rtxtrQ.push(txr);
  27125. };
  27126. ETCp.addTexture = function (txrH, minW) {
  27127. var self = this;
  27128. var txrQ = self.getTextureQueue(txrH);
  27129. var txr = {};
  27130. txrQ.push(txr);
  27131. txr.eleCaches = [];
  27132. txr.height = txrH;
  27133. txr.width = Math.max(defTxrWidth, minW);
  27134. txr.usedWidth = 0;
  27135. txr.invalidatedWidth = 0;
  27136. txr.fullnessChecks = 0;
  27137. txr.canvas = self.renderer.makeOffscreenCanvas(txr.width, txr.height);
  27138. txr.context = txr.canvas.getContext('2d');
  27139. return txr;
  27140. };
  27141. ETCp.recycleTexture = function (txrH, minW) {
  27142. var self = this;
  27143. var txrQ = self.getTextureQueue(txrH);
  27144. var rtxtrQ = self.getRetiredTextureQueue(txrH);
  27145. for (var i = 0; i < rtxtrQ.length; i++) {
  27146. var txr = rtxtrQ[i];
  27147. if (txr.width >= minW) {
  27148. txr.retired = false;
  27149. txr.usedWidth = 0;
  27150. txr.invalidatedWidth = 0;
  27151. txr.fullnessChecks = 0;
  27152. clearArray(txr.eleCaches);
  27153. txr.context.setTransform(1, 0, 0, 1, 0, 0);
  27154. txr.context.clearRect(0, 0, txr.width, txr.height);
  27155. removeFromArray(rtxtrQ, txr);
  27156. txrQ.push(txr);
  27157. return txr;
  27158. }
  27159. }
  27160. };
  27161. ETCp.queueElement = function (ele, lvl) {
  27162. var self = this;
  27163. var q = self.getElementQueue();
  27164. var k2q = self.getElementKeyToQueue();
  27165. var key = this.getKey(ele);
  27166. var existingReq = k2q[key];
  27167. if (existingReq) {
  27168. // use the max lvl b/c in between lvls are cheap to make
  27169. existingReq.level = Math.max(existingReq.level, lvl);
  27170. existingReq.eles.merge(ele);
  27171. existingReq.reqs++;
  27172. q.updateItem(existingReq);
  27173. } else {
  27174. var req = {
  27175. eles: ele.spawn().merge(ele),
  27176. level: lvl,
  27177. reqs: 1,
  27178. key: key
  27179. };
  27180. q.push(req);
  27181. k2q[key] = req;
  27182. }
  27183. };
  27184. ETCp.dequeue = function (pxRatio /*, extent*/) {
  27185. var self = this;
  27186. var q = self.getElementQueue();
  27187. var k2q = self.getElementKeyToQueue();
  27188. var dequeued = [];
  27189. var lookup = self.lookup;
  27190. for (var i = 0; i < maxDeqSize$1; i++) {
  27191. if (q.size() > 0) {
  27192. var req = q.pop();
  27193. var key = req.key;
  27194. var ele = req.eles[0]; // all eles have the same key
  27195. var cacheExists = lookup.hasCache(ele, req.level);
  27196. // clear out the key to req lookup
  27197. k2q[key] = null;
  27198. // dequeueing isn't necessary with an existing cache
  27199. if (cacheExists) {
  27200. continue;
  27201. }
  27202. dequeued.push(req);
  27203. var bb = self.getBoundingBox(ele);
  27204. self.getElement(ele, bb, pxRatio, req.level, getTxrReasons.dequeue);
  27205. } else {
  27206. break;
  27207. }
  27208. }
  27209. return dequeued;
  27210. };
  27211. ETCp.removeFromQueue = function (ele) {
  27212. var self = this;
  27213. var q = self.getElementQueue();
  27214. var k2q = self.getElementKeyToQueue();
  27215. var key = this.getKey(ele);
  27216. var req = k2q[key];
  27217. if (req != null) {
  27218. if (req.eles.length === 1) {
  27219. // remove if last ele in the req
  27220. // bring to front of queue
  27221. req.reqs = MAX_INT$1;
  27222. q.updateItem(req);
  27223. q.pop(); // remove from queue
  27224. k2q[key] = null; // remove from lookup map
  27225. } else {
  27226. // otherwise just remove ele from req
  27227. req.eles.unmerge(ele);
  27228. }
  27229. }
  27230. };
  27231. ETCp.onDequeue = function (fn) {
  27232. this.onDequeues.push(fn);
  27233. };
  27234. ETCp.offDequeue = function (fn) {
  27235. removeFromArray(this.onDequeues, fn);
  27236. };
  27237. ETCp.setupDequeueing = defs.setupDequeueing({
  27238. deqRedrawThreshold: deqRedrawThreshold$1,
  27239. deqCost: deqCost$1,
  27240. deqAvgCost: deqAvgCost$1,
  27241. deqNoDrawCost: deqNoDrawCost$1,
  27242. deqFastCost: deqFastCost$1,
  27243. deq: function deq(self, pxRatio, extent) {
  27244. return self.dequeue(pxRatio, extent);
  27245. },
  27246. onDeqd: function onDeqd(self, deqd) {
  27247. for (var i = 0; i < self.onDequeues.length; i++) {
  27248. var fn = self.onDequeues[i];
  27249. fn(deqd);
  27250. }
  27251. },
  27252. shouldRedraw: function shouldRedraw(self, deqd, pxRatio, extent) {
  27253. for (var i = 0; i < deqd.length; i++) {
  27254. var eles = deqd[i].eles;
  27255. for (var j = 0; j < eles.length; j++) {
  27256. var bb = eles[j].boundingBox();
  27257. if (boundingBoxesIntersect(bb, extent)) {
  27258. return true;
  27259. }
  27260. }
  27261. }
  27262. return false;
  27263. },
  27264. priority: function priority(self) {
  27265. return self.renderer.beforeRenderPriorities.eleTxrDeq;
  27266. }
  27267. });
  27268. var defNumLayers = 1; // default number of layers to use
  27269. var minLvl = -4; // when scaling smaller than that we don't need to re-render
  27270. var maxLvl = 2; // when larger than this scale just render directly (caching is not helpful)
  27271. var maxZoom = 3.99; // beyond this zoom level, layered textures are not used
  27272. var deqRedrawThreshold = 50; // time to batch redraws together from dequeueing to allow more dequeueing calcs to happen in the meanwhile
  27273. var refineEleDebounceTime = 50; // time to debounce sharper ele texture updates
  27274. var deqCost = 0.15; // % of add'l rendering cost allowed for dequeuing ele caches each frame
  27275. var deqAvgCost = 0.1; // % of add'l rendering cost compared to average overall redraw time
  27276. var deqNoDrawCost = 0.9; // % of avg frame time that can be used for dequeueing when not drawing
  27277. var deqFastCost = 0.9; // % of frame time to be used when >60fps
  27278. var maxDeqSize = 1; // number of eles to dequeue and render at higher texture in each batch
  27279. var invalidThreshold = 250; // time threshold for disabling b/c of invalidations
  27280. var maxLayerArea = 4000 * 4000; // layers can't be bigger than this
  27281. var maxLayerDim = 32767; // maximum size for the width/height of layer canvases
  27282. var useHighQualityEleTxrReqs = true; // whether to use high quality ele txr requests (generally faster and cheaper in the longterm)
  27283. // var log = function(){ console.log.apply( console, arguments ); };
  27284. var LayeredTextureCache = function LayeredTextureCache(renderer) {
  27285. var self = this;
  27286. var r = self.renderer = renderer;
  27287. var cy = r.cy;
  27288. self.layersByLevel = {}; // e.g. 2 => [ layer1, layer2, ..., layerN ]
  27289. self.firstGet = true;
  27290. self.lastInvalidationTime = performanceNow() - 2 * invalidThreshold;
  27291. self.skipping = false;
  27292. self.eleTxrDeqs = cy.collection();
  27293. self.scheduleElementRefinement = debounce(function () {
  27294. self.refineElementTextures(self.eleTxrDeqs);
  27295. self.eleTxrDeqs.unmerge(self.eleTxrDeqs);
  27296. }, refineEleDebounceTime);
  27297. r.beforeRender(function (willDraw, now) {
  27298. if (now - self.lastInvalidationTime <= invalidThreshold) {
  27299. self.skipping = true;
  27300. } else {
  27301. self.skipping = false;
  27302. }
  27303. }, r.beforeRenderPriorities.lyrTxrSkip);
  27304. var qSort = function qSort(a, b) {
  27305. return b.reqs - a.reqs;
  27306. };
  27307. self.layersQueue = new Heap(qSort);
  27308. self.setupDequeueing();
  27309. };
  27310. var LTCp = LayeredTextureCache.prototype;
  27311. var layerIdPool = 0;
  27312. var MAX_INT = Math.pow(2, 53) - 1;
  27313. LTCp.makeLayer = function (bb, lvl) {
  27314. var scale = Math.pow(2, lvl);
  27315. var w = Math.ceil(bb.w * scale);
  27316. var h = Math.ceil(bb.h * scale);
  27317. var canvas = this.renderer.makeOffscreenCanvas(w, h);
  27318. var layer = {
  27319. id: layerIdPool = ++layerIdPool % MAX_INT,
  27320. bb: bb,
  27321. level: lvl,
  27322. width: w,
  27323. height: h,
  27324. canvas: canvas,
  27325. context: canvas.getContext('2d'),
  27326. eles: [],
  27327. elesQueue: [],
  27328. reqs: 0
  27329. };
  27330. // log('make layer %s with w %s and h %s and lvl %s', layer.id, layer.width, layer.height, layer.level);
  27331. var cxt = layer.context;
  27332. var dx = -layer.bb.x1;
  27333. var dy = -layer.bb.y1;
  27334. // do the transform on creation to save cycles (it's the same for all eles)
  27335. cxt.scale(scale, scale);
  27336. cxt.translate(dx, dy);
  27337. return layer;
  27338. };
  27339. LTCp.getLayers = function (eles, pxRatio, lvl) {
  27340. var self = this;
  27341. var r = self.renderer;
  27342. var cy = r.cy;
  27343. var zoom = cy.zoom();
  27344. var firstGet = self.firstGet;
  27345. self.firstGet = false;
  27346. // log('--\nget layers with %s eles', eles.length);
  27347. //log eles.map(function(ele){ return ele.id() }) );
  27348. if (lvl == null) {
  27349. lvl = Math.ceil(log2(zoom * pxRatio));
  27350. if (lvl < minLvl) {
  27351. lvl = minLvl;
  27352. } else if (zoom >= maxZoom || lvl > maxLvl) {
  27353. return null;
  27354. }
  27355. }
  27356. self.validateLayersElesOrdering(lvl, eles);
  27357. var layersByLvl = self.layersByLevel;
  27358. var scale = Math.pow(2, lvl);
  27359. var layers = layersByLvl[lvl] = layersByLvl[lvl] || [];
  27360. var bb;
  27361. var lvlComplete = self.levelIsComplete(lvl, eles);
  27362. var tmpLayers;
  27363. var checkTempLevels = function checkTempLevels() {
  27364. var canUseAsTmpLvl = function canUseAsTmpLvl(l) {
  27365. self.validateLayersElesOrdering(l, eles);
  27366. if (self.levelIsComplete(l, eles)) {
  27367. tmpLayers = layersByLvl[l];
  27368. return true;
  27369. }
  27370. };
  27371. var checkLvls = function checkLvls(dir) {
  27372. if (tmpLayers) {
  27373. return;
  27374. }
  27375. for (var l = lvl + dir; minLvl <= l && l <= maxLvl; l += dir) {
  27376. if (canUseAsTmpLvl(l)) {
  27377. break;
  27378. }
  27379. }
  27380. };
  27381. checkLvls(1);
  27382. checkLvls(-1);
  27383. // remove the invalid layers; they will be replaced as needed later in this function
  27384. for (var i = layers.length - 1; i >= 0; i--) {
  27385. var layer = layers[i];
  27386. if (layer.invalid) {
  27387. removeFromArray(layers, layer);
  27388. }
  27389. }
  27390. };
  27391. if (!lvlComplete) {
  27392. // if the current level is incomplete, then use the closest, best quality layerset temporarily
  27393. // and later queue the current layerset so we can get the proper quality level soon
  27394. checkTempLevels();
  27395. } else {
  27396. // log('level complete, using existing layers\n--');
  27397. return layers;
  27398. }
  27399. var getBb = function getBb() {
  27400. if (!bb) {
  27401. bb = makeBoundingBox();
  27402. for (var i = 0; i < eles.length; i++) {
  27403. updateBoundingBox(bb, eles[i].boundingBox());
  27404. }
  27405. }
  27406. return bb;
  27407. };
  27408. var makeLayer = function makeLayer(opts) {
  27409. opts = opts || {};
  27410. var after = opts.after;
  27411. getBb();
  27412. var w = Math.ceil(bb.w * scale);
  27413. var h = Math.ceil(bb.h * scale);
  27414. if (w > maxLayerDim || h > maxLayerDim) {
  27415. return null;
  27416. }
  27417. var area = w * h;
  27418. if (area > maxLayerArea) {
  27419. return null;
  27420. }
  27421. var layer = self.makeLayer(bb, lvl);
  27422. if (after != null) {
  27423. var index = layers.indexOf(after) + 1;
  27424. layers.splice(index, 0, layer);
  27425. } else if (opts.insert === undefined || opts.insert) {
  27426. // no after specified => first layer made so put at start
  27427. layers.unshift(layer);
  27428. }
  27429. // if( tmpLayers ){
  27430. //self.queueLayer( layer );
  27431. // }
  27432. return layer;
  27433. };
  27434. if (self.skipping && !firstGet) {
  27435. // log('skip layers');
  27436. return null;
  27437. }
  27438. // log('do layers');
  27439. var layer = null;
  27440. var maxElesPerLayer = eles.length / defNumLayers;
  27441. var allowLazyQueueing = !firstGet;
  27442. for (var i = 0; i < eles.length; i++) {
  27443. var ele = eles[i];
  27444. var rs = ele._private.rscratch;
  27445. var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
  27446. // log('look at ele', ele.id());
  27447. var existingLayer = caches[lvl];
  27448. if (existingLayer) {
  27449. // reuse layer for later eles
  27450. // log('reuse layer for', ele.id());
  27451. layer = existingLayer;
  27452. continue;
  27453. }
  27454. if (!layer || layer.eles.length >= maxElesPerLayer || !boundingBoxInBoundingBox(layer.bb, ele.boundingBox())) {
  27455. // log('make new layer for ele %s', ele.id());
  27456. layer = makeLayer({
  27457. insert: true,
  27458. after: layer
  27459. });
  27460. // if now layer can be built then we can't use layers at this level
  27461. if (!layer) {
  27462. return null;
  27463. }
  27464. // log('new layer with id %s', layer.id);
  27465. }
  27466. if (tmpLayers || allowLazyQueueing) {
  27467. // log('queue ele %s in layer %s', ele.id(), layer.id);
  27468. self.queueLayer(layer, ele);
  27469. } else {
  27470. // log('draw ele %s in layer %s', ele.id(), layer.id);
  27471. self.drawEleInLayer(layer, ele, lvl, pxRatio);
  27472. }
  27473. layer.eles.push(ele);
  27474. caches[lvl] = layer;
  27475. }
  27476. // log('--');
  27477. if (tmpLayers) {
  27478. // then we only queued the current layerset and can't draw it yet
  27479. return tmpLayers;
  27480. }
  27481. if (allowLazyQueueing) {
  27482. // log('lazy queue level', lvl);
  27483. return null;
  27484. }
  27485. return layers;
  27486. };
  27487. // a layer may want to use an ele cache of a higher level to avoid blurriness
  27488. // so the layer level might not equal the ele level
  27489. LTCp.getEleLevelForLayerLevel = function (lvl, pxRatio) {
  27490. return lvl;
  27491. };
  27492. LTCp.drawEleInLayer = function (layer, ele, lvl, pxRatio) {
  27493. var self = this;
  27494. var r = this.renderer;
  27495. var context = layer.context;
  27496. var bb = ele.boundingBox();
  27497. if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
  27498. return;
  27499. }
  27500. lvl = self.getEleLevelForLayerLevel(lvl, pxRatio);
  27501. {
  27502. r.setImgSmoothing(context, false);
  27503. }
  27504. {
  27505. r.drawCachedElement(context, ele, null, null, lvl, useHighQualityEleTxrReqs);
  27506. }
  27507. {
  27508. r.setImgSmoothing(context, true);
  27509. }
  27510. };
  27511. LTCp.levelIsComplete = function (lvl, eles) {
  27512. var self = this;
  27513. var layers = self.layersByLevel[lvl];
  27514. if (!layers || layers.length === 0) {
  27515. return false;
  27516. }
  27517. var numElesInLayers = 0;
  27518. for (var i = 0; i < layers.length; i++) {
  27519. var layer = layers[i];
  27520. // if there are any eles needed to be drawn yet, the level is not complete
  27521. if (layer.reqs > 0) {
  27522. return false;
  27523. }
  27524. // if the layer is invalid, the level is not complete
  27525. if (layer.invalid) {
  27526. return false;
  27527. }
  27528. numElesInLayers += layer.eles.length;
  27529. }
  27530. // we should have exactly the number of eles passed in to be complete
  27531. if (numElesInLayers !== eles.length) {
  27532. return false;
  27533. }
  27534. return true;
  27535. };
  27536. LTCp.validateLayersElesOrdering = function (lvl, eles) {
  27537. var layers = this.layersByLevel[lvl];
  27538. if (!layers) {
  27539. return;
  27540. }
  27541. // if in a layer the eles are not in the same order, then the layer is invalid
  27542. // (i.e. there is an ele in between the eles in the layer)
  27543. for (var i = 0; i < layers.length; i++) {
  27544. var layer = layers[i];
  27545. var offset = -1;
  27546. // find the offset
  27547. for (var j = 0; j < eles.length; j++) {
  27548. if (layer.eles[0] === eles[j]) {
  27549. offset = j;
  27550. break;
  27551. }
  27552. }
  27553. if (offset < 0) {
  27554. // then the layer has nonexistent elements and is invalid
  27555. this.invalidateLayer(layer);
  27556. continue;
  27557. }
  27558. // the eles in the layer must be in the same continuous order, else the layer is invalid
  27559. var o = offset;
  27560. for (var j = 0; j < layer.eles.length; j++) {
  27561. if (layer.eles[j] !== eles[o + j]) {
  27562. // log('invalidate based on ordering', layer.id);
  27563. this.invalidateLayer(layer);
  27564. break;
  27565. }
  27566. }
  27567. }
  27568. };
  27569. LTCp.updateElementsInLayers = function (eles, update) {
  27570. var self = this;
  27571. var isEles = element(eles[0]);
  27572. // collect udpated elements (cascaded from the layers) and update each
  27573. // layer itself along the way
  27574. for (var i = 0; i < eles.length; i++) {
  27575. var req = isEles ? null : eles[i];
  27576. var ele = isEles ? eles[i] : eles[i].ele;
  27577. var rs = ele._private.rscratch;
  27578. var caches = rs.imgLayerCaches = rs.imgLayerCaches || {};
  27579. for (var l = minLvl; l <= maxLvl; l++) {
  27580. var layer = caches[l];
  27581. if (!layer) {
  27582. continue;
  27583. }
  27584. // if update is a request from the ele cache, then it affects only
  27585. // the matching level
  27586. if (req && self.getEleLevelForLayerLevel(layer.level) !== req.level) {
  27587. continue;
  27588. }
  27589. update(layer, ele, req);
  27590. }
  27591. }
  27592. };
  27593. LTCp.haveLayers = function () {
  27594. var self = this;
  27595. var haveLayers = false;
  27596. for (var l = minLvl; l <= maxLvl; l++) {
  27597. var layers = self.layersByLevel[l];
  27598. if (layers && layers.length > 0) {
  27599. haveLayers = true;
  27600. break;
  27601. }
  27602. }
  27603. return haveLayers;
  27604. };
  27605. LTCp.invalidateElements = function (eles) {
  27606. var self = this;
  27607. if (eles.length === 0) {
  27608. return;
  27609. }
  27610. self.lastInvalidationTime = performanceNow();
  27611. // log('update invalidate layer time from eles');
  27612. if (eles.length === 0 || !self.haveLayers()) {
  27613. return;
  27614. }
  27615. self.updateElementsInLayers(eles, function invalAssocLayers(layer, ele, req) {
  27616. self.invalidateLayer(layer);
  27617. });
  27618. };
  27619. LTCp.invalidateLayer = function (layer) {
  27620. // log('update invalidate layer time');
  27621. this.lastInvalidationTime = performanceNow();
  27622. if (layer.invalid) {
  27623. return;
  27624. } // save cycles
  27625. var lvl = layer.level;
  27626. var eles = layer.eles;
  27627. var layers = this.layersByLevel[lvl];
  27628. // log('invalidate layer', layer.id );
  27629. removeFromArray(layers, layer);
  27630. // layer.eles = [];
  27631. layer.elesQueue = [];
  27632. layer.invalid = true;
  27633. if (layer.replacement) {
  27634. layer.replacement.invalid = true;
  27635. }
  27636. for (var i = 0; i < eles.length; i++) {
  27637. var caches = eles[i]._private.rscratch.imgLayerCaches;
  27638. if (caches) {
  27639. caches[lvl] = null;
  27640. }
  27641. }
  27642. };
  27643. LTCp.refineElementTextures = function (eles) {
  27644. var self = this;
  27645. // log('refine', eles.length);
  27646. self.updateElementsInLayers(eles, function refineEachEle(layer, ele, req) {
  27647. var rLyr = layer.replacement;
  27648. if (!rLyr) {
  27649. rLyr = layer.replacement = self.makeLayer(layer.bb, layer.level);
  27650. rLyr.replaces = layer;
  27651. rLyr.eles = layer.eles;
  27652. // log('make replacement layer %s for %s with level %s', rLyr.id, layer.id, rLyr.level);
  27653. }
  27654. if (!rLyr.reqs) {
  27655. for (var i = 0; i < rLyr.eles.length; i++) {
  27656. self.queueLayer(rLyr, rLyr.eles[i]);
  27657. }
  27658. // log('queue replacement layer refinement', rLyr.id);
  27659. }
  27660. });
  27661. };
  27662. LTCp.enqueueElementRefinement = function (ele) {
  27663. this.eleTxrDeqs.merge(ele);
  27664. this.scheduleElementRefinement();
  27665. };
  27666. LTCp.queueLayer = function (layer, ele) {
  27667. var self = this;
  27668. var q = self.layersQueue;
  27669. var elesQ = layer.elesQueue;
  27670. var hasId = elesQ.hasId = elesQ.hasId || {};
  27671. // if a layer is going to be replaced, queuing is a waste of time
  27672. if (layer.replacement) {
  27673. return;
  27674. }
  27675. if (ele) {
  27676. if (hasId[ele.id()]) {
  27677. return;
  27678. }
  27679. elesQ.push(ele);
  27680. hasId[ele.id()] = true;
  27681. }
  27682. if (layer.reqs) {
  27683. layer.reqs++;
  27684. q.updateItem(layer);
  27685. } else {
  27686. layer.reqs = 1;
  27687. q.push(layer);
  27688. }
  27689. };
  27690. LTCp.dequeue = function (pxRatio) {
  27691. var self = this;
  27692. var q = self.layersQueue;
  27693. var deqd = [];
  27694. var eleDeqs = 0;
  27695. while (eleDeqs < maxDeqSize) {
  27696. if (q.size() === 0) {
  27697. break;
  27698. }
  27699. var layer = q.peek();
  27700. // if a layer has been or will be replaced, then don't waste time with it
  27701. if (layer.replacement) {
  27702. // log('layer %s in queue skipped b/c it already has a replacement', layer.id);
  27703. q.pop();
  27704. continue;
  27705. }
  27706. // if this is a replacement layer that has been superceded, then forget it
  27707. if (layer.replaces && layer !== layer.replaces.replacement) {
  27708. // log('layer is no longer the most uptodate replacement; dequeued', layer.id)
  27709. q.pop();
  27710. continue;
  27711. }
  27712. if (layer.invalid) {
  27713. // log('replacement layer %s is invalid; dequeued', layer.id);
  27714. q.pop();
  27715. continue;
  27716. }
  27717. var ele = layer.elesQueue.shift();
  27718. if (ele) {
  27719. // log('dequeue layer %s', layer.id);
  27720. self.drawEleInLayer(layer, ele, layer.level, pxRatio);
  27721. eleDeqs++;
  27722. }
  27723. if (deqd.length === 0) {
  27724. // we need only one entry in deqd to queue redrawing etc
  27725. deqd.push(true);
  27726. }
  27727. // if the layer has all its eles done, then remove from the queue
  27728. if (layer.elesQueue.length === 0) {
  27729. q.pop();
  27730. layer.reqs = 0;
  27731. // log('dequeue of layer %s complete', layer.id);
  27732. // when a replacement layer is dequeued, it replaces the old layer in the level
  27733. if (layer.replaces) {
  27734. self.applyLayerReplacement(layer);
  27735. }
  27736. self.requestRedraw();
  27737. }
  27738. }
  27739. return deqd;
  27740. };
  27741. LTCp.applyLayerReplacement = function (layer) {
  27742. var self = this;
  27743. var layersInLevel = self.layersByLevel[layer.level];
  27744. var replaced = layer.replaces;
  27745. var index = layersInLevel.indexOf(replaced);
  27746. // if the replaced layer is not in the active list for the level, then replacing
  27747. // refs would be a mistake (i.e. overwriting the true active layer)
  27748. if (index < 0 || replaced.invalid) {
  27749. // log('replacement layer would have no effect', layer.id);
  27750. return;
  27751. }
  27752. layersInLevel[index] = layer; // replace level ref
  27753. // replace refs in eles
  27754. for (var i = 0; i < layer.eles.length; i++) {
  27755. var _p = layer.eles[i]._private;
  27756. var cache = _p.imgLayerCaches = _p.imgLayerCaches || {};
  27757. if (cache) {
  27758. cache[layer.level] = layer;
  27759. }
  27760. }
  27761. // log('apply replacement layer %s over %s', layer.id, replaced.id);
  27762. self.requestRedraw();
  27763. };
  27764. LTCp.requestRedraw = debounce(function () {
  27765. var r = this.renderer;
  27766. r.redrawHint('eles', true);
  27767. r.redrawHint('drag', true);
  27768. r.redraw();
  27769. }, 100);
  27770. LTCp.setupDequeueing = defs.setupDequeueing({
  27771. deqRedrawThreshold: deqRedrawThreshold,
  27772. deqCost: deqCost,
  27773. deqAvgCost: deqAvgCost,
  27774. deqNoDrawCost: deqNoDrawCost,
  27775. deqFastCost: deqFastCost,
  27776. deq: function deq(self, pxRatio) {
  27777. return self.dequeue(pxRatio);
  27778. },
  27779. onDeqd: noop$1,
  27780. shouldRedraw: trueify,
  27781. priority: function priority(self) {
  27782. return self.renderer.beforeRenderPriorities.lyrTxrDeq;
  27783. }
  27784. });
  27785. var CRp$b = {};
  27786. var impl;
  27787. function polygon(context, points) {
  27788. for (var i = 0; i < points.length; i++) {
  27789. var pt = points[i];
  27790. context.lineTo(pt.x, pt.y);
  27791. }
  27792. }
  27793. function triangleBackcurve(context, points, controlPoint) {
  27794. var firstPt;
  27795. for (var i = 0; i < points.length; i++) {
  27796. var pt = points[i];
  27797. if (i === 0) {
  27798. firstPt = pt;
  27799. }
  27800. context.lineTo(pt.x, pt.y);
  27801. }
  27802. context.quadraticCurveTo(controlPoint.x, controlPoint.y, firstPt.x, firstPt.y);
  27803. }
  27804. function triangleTee(context, trianglePoints, teePoints) {
  27805. if (context.beginPath) {
  27806. context.beginPath();
  27807. }
  27808. var triPts = trianglePoints;
  27809. for (var i = 0; i < triPts.length; i++) {
  27810. var pt = triPts[i];
  27811. context.lineTo(pt.x, pt.y);
  27812. }
  27813. var teePts = teePoints;
  27814. var firstTeePt = teePoints[0];
  27815. context.moveTo(firstTeePt.x, firstTeePt.y);
  27816. for (var i = 1; i < teePts.length; i++) {
  27817. var pt = teePts[i];
  27818. context.lineTo(pt.x, pt.y);
  27819. }
  27820. if (context.closePath) {
  27821. context.closePath();
  27822. }
  27823. }
  27824. function circleTriangle(context, trianglePoints, rx, ry, r) {
  27825. if (context.beginPath) {
  27826. context.beginPath();
  27827. }
  27828. context.arc(rx, ry, r, 0, Math.PI * 2, false);
  27829. var triPts = trianglePoints;
  27830. var firstTrPt = triPts[0];
  27831. context.moveTo(firstTrPt.x, firstTrPt.y);
  27832. for (var i = 0; i < triPts.length; i++) {
  27833. var pt = triPts[i];
  27834. context.lineTo(pt.x, pt.y);
  27835. }
  27836. if (context.closePath) {
  27837. context.closePath();
  27838. }
  27839. }
  27840. function circle$1(context, rx, ry, r) {
  27841. context.arc(rx, ry, r, 0, Math.PI * 2, false);
  27842. }
  27843. CRp$b.arrowShapeImpl = function (name) {
  27844. return (impl || (impl = {
  27845. 'polygon': polygon,
  27846. 'triangle-backcurve': triangleBackcurve,
  27847. 'triangle-tee': triangleTee,
  27848. 'circle-triangle': circleTriangle,
  27849. 'triangle-cross': triangleTee,
  27850. 'circle': circle$1
  27851. }))[name];
  27852. };
  27853. var CRp$a = {};
  27854. CRp$a.drawElement = function (context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity) {
  27855. var r = this;
  27856. if (ele.isNode()) {
  27857. r.drawNode(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  27858. } else {
  27859. r.drawEdge(context, ele, shiftToOriginWithBb, showLabel, showOverlay, showOpacity);
  27860. }
  27861. };
  27862. CRp$a.drawElementOverlay = function (context, ele) {
  27863. var r = this;
  27864. if (ele.isNode()) {
  27865. r.drawNodeOverlay(context, ele);
  27866. } else {
  27867. r.drawEdgeOverlay(context, ele);
  27868. }
  27869. };
  27870. CRp$a.drawElementUnderlay = function (context, ele) {
  27871. var r = this;
  27872. if (ele.isNode()) {
  27873. r.drawNodeUnderlay(context, ele);
  27874. } else {
  27875. r.drawEdgeUnderlay(context, ele);
  27876. }
  27877. };
  27878. CRp$a.drawCachedElementPortion = function (context, ele, eleTxrCache, pxRatio, lvl, reason, getRotation, getOpacity) {
  27879. var r = this;
  27880. var bb = eleTxrCache.getBoundingBox(ele);
  27881. if (bb.w === 0 || bb.h === 0) {
  27882. return;
  27883. } // ignore zero size case
  27884. var eleCache = eleTxrCache.getElement(ele, bb, pxRatio, lvl, reason);
  27885. if (eleCache != null) {
  27886. var opacity = getOpacity(r, ele);
  27887. if (opacity === 0) {
  27888. return;
  27889. }
  27890. var theta = getRotation(r, ele);
  27891. var x1 = bb.x1,
  27892. y1 = bb.y1,
  27893. w = bb.w,
  27894. h = bb.h;
  27895. var x, y, sx, sy, smooth;
  27896. if (theta !== 0) {
  27897. var rotPt = eleTxrCache.getRotationPoint(ele);
  27898. sx = rotPt.x;
  27899. sy = rotPt.y;
  27900. context.translate(sx, sy);
  27901. context.rotate(theta);
  27902. smooth = r.getImgSmoothing(context);
  27903. if (!smooth) {
  27904. r.setImgSmoothing(context, true);
  27905. }
  27906. var off = eleTxrCache.getRotationOffset(ele);
  27907. x = off.x;
  27908. y = off.y;
  27909. } else {
  27910. x = x1;
  27911. y = y1;
  27912. }
  27913. var oldGlobalAlpha;
  27914. if (opacity !== 1) {
  27915. oldGlobalAlpha = context.globalAlpha;
  27916. context.globalAlpha = oldGlobalAlpha * opacity;
  27917. }
  27918. context.drawImage(eleCache.texture.canvas, eleCache.x, 0, eleCache.width, eleCache.height, x, y, w, h);
  27919. if (opacity !== 1) {
  27920. context.globalAlpha = oldGlobalAlpha;
  27921. }
  27922. if (theta !== 0) {
  27923. context.rotate(-theta);
  27924. context.translate(-sx, -sy);
  27925. if (!smooth) {
  27926. r.setImgSmoothing(context, false);
  27927. }
  27928. }
  27929. } else {
  27930. eleTxrCache.drawElement(context, ele); // direct draw fallback
  27931. }
  27932. };
  27933. var getZeroRotation = function getZeroRotation() {
  27934. return 0;
  27935. };
  27936. var getLabelRotation = function getLabelRotation(r, ele) {
  27937. return r.getTextAngle(ele, null);
  27938. };
  27939. var getSourceLabelRotation = function getSourceLabelRotation(r, ele) {
  27940. return r.getTextAngle(ele, 'source');
  27941. };
  27942. var getTargetLabelRotation = function getTargetLabelRotation(r, ele) {
  27943. return r.getTextAngle(ele, 'target');
  27944. };
  27945. var getOpacity = function getOpacity(r, ele) {
  27946. return ele.effectiveOpacity();
  27947. };
  27948. var getTextOpacity = function getTextOpacity(e, ele) {
  27949. return ele.pstyle('text-opacity').pfValue * ele.effectiveOpacity();
  27950. };
  27951. CRp$a.drawCachedElement = function (context, ele, pxRatio, extent, lvl, requestHighQuality) {
  27952. var r = this;
  27953. var _r$data = r.data,
  27954. eleTxrCache = _r$data.eleTxrCache,
  27955. lblTxrCache = _r$data.lblTxrCache,
  27956. slbTxrCache = _r$data.slbTxrCache,
  27957. tlbTxrCache = _r$data.tlbTxrCache;
  27958. var bb = ele.boundingBox();
  27959. var reason = requestHighQuality === true ? eleTxrCache.reasons.highQuality : null;
  27960. if (bb.w === 0 || bb.h === 0 || !ele.visible()) {
  27961. return;
  27962. }
  27963. if (!extent || boundingBoxesIntersect(bb, extent)) {
  27964. var isEdge = ele.isEdge();
  27965. var badLine = ele.element()._private.rscratch.badLine;
  27966. r.drawElementUnderlay(context, ele);
  27967. r.drawCachedElementPortion(context, ele, eleTxrCache, pxRatio, lvl, reason, getZeroRotation, getOpacity);
  27968. if (!isEdge || !badLine) {
  27969. r.drawCachedElementPortion(context, ele, lblTxrCache, pxRatio, lvl, reason, getLabelRotation, getTextOpacity);
  27970. }
  27971. if (isEdge && !badLine) {
  27972. r.drawCachedElementPortion(context, ele, slbTxrCache, pxRatio, lvl, reason, getSourceLabelRotation, getTextOpacity);
  27973. r.drawCachedElementPortion(context, ele, tlbTxrCache, pxRatio, lvl, reason, getTargetLabelRotation, getTextOpacity);
  27974. }
  27975. r.drawElementOverlay(context, ele);
  27976. }
  27977. };
  27978. CRp$a.drawElements = function (context, eles) {
  27979. var r = this;
  27980. for (var i = 0; i < eles.length; i++) {
  27981. var ele = eles[i];
  27982. r.drawElement(context, ele);
  27983. }
  27984. };
  27985. CRp$a.drawCachedElements = function (context, eles, pxRatio, extent) {
  27986. var r = this;
  27987. for (var i = 0; i < eles.length; i++) {
  27988. var ele = eles[i];
  27989. r.drawCachedElement(context, ele, pxRatio, extent);
  27990. }
  27991. };
  27992. CRp$a.drawCachedNodes = function (context, eles, pxRatio, extent) {
  27993. var r = this;
  27994. for (var i = 0; i < eles.length; i++) {
  27995. var ele = eles[i];
  27996. if (!ele.isNode()) {
  27997. continue;
  27998. }
  27999. r.drawCachedElement(context, ele, pxRatio, extent);
  28000. }
  28001. };
  28002. CRp$a.drawLayeredElements = function (context, eles, pxRatio, extent) {
  28003. var r = this;
  28004. var layers = r.data.lyrTxrCache.getLayers(eles, pxRatio);
  28005. if (layers) {
  28006. for (var i = 0; i < layers.length; i++) {
  28007. var layer = layers[i];
  28008. var bb = layer.bb;
  28009. if (bb.w === 0 || bb.h === 0) {
  28010. continue;
  28011. }
  28012. context.drawImage(layer.canvas, bb.x1, bb.y1, bb.w, bb.h);
  28013. }
  28014. } else {
  28015. // fall back on plain caching if no layers
  28016. r.drawCachedElements(context, eles, pxRatio, extent);
  28017. }
  28018. };
  28019. var CRp$9 = {};
  28020. CRp$9.drawEdge = function (context, edge, shiftToOriginWithBb) {
  28021. var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28022. var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28023. var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28024. var r = this;
  28025. var rs = edge._private.rscratch;
  28026. if (shouldDrawOpacity && !edge.visible()) {
  28027. return;
  28028. }
  28029. // if bezier ctrl pts can not be calculated, then die
  28030. if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
  28031. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  28032. return;
  28033. }
  28034. var bb;
  28035. if (shiftToOriginWithBb) {
  28036. bb = shiftToOriginWithBb;
  28037. context.translate(-bb.x1, -bb.y1);
  28038. }
  28039. var opacity = shouldDrawOpacity ? edge.pstyle('opacity').value : 1;
  28040. var lineOpacity = shouldDrawOpacity ? edge.pstyle('line-opacity').value : 1;
  28041. var curveStyle = edge.pstyle('curve-style').value;
  28042. var lineStyle = edge.pstyle('line-style').value;
  28043. var edgeWidth = edge.pstyle('width').pfValue;
  28044. var lineCap = edge.pstyle('line-cap').value;
  28045. var lineOutlineWidth = edge.pstyle('line-outline-width').value;
  28046. var lineOutlineColor = edge.pstyle('line-outline-color').value;
  28047. var effectiveLineOpacity = opacity * lineOpacity;
  28048. // separate arrow opacity would require arrow-opacity property
  28049. var effectiveArrowOpacity = opacity * lineOpacity;
  28050. var drawLine = function drawLine() {
  28051. var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
  28052. if (curveStyle === 'straight-triangle') {
  28053. r.eleStrokeStyle(context, edge, strokeOpacity);
  28054. r.drawEdgeTrianglePath(edge, context, rs.allpts);
  28055. } else {
  28056. context.lineWidth = edgeWidth;
  28057. context.lineCap = lineCap;
  28058. r.eleStrokeStyle(context, edge, strokeOpacity);
  28059. r.drawEdgePath(edge, context, rs.allpts, lineStyle);
  28060. context.lineCap = 'butt'; // reset for other drawing functions
  28061. }
  28062. };
  28063. var drawLineOutline = function drawLineOutline() {
  28064. var strokeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveLineOpacity;
  28065. context.lineWidth = edgeWidth + lineOutlineWidth;
  28066. context.lineCap = lineCap;
  28067. if (lineOutlineWidth > 0) {
  28068. r.colorStrokeStyle(context, lineOutlineColor[0], lineOutlineColor[1], lineOutlineColor[2], strokeOpacity);
  28069. } else {
  28070. // do not draw any lineOutline
  28071. context.lineCap = 'butt'; // reset for other drawing functions
  28072. return;
  28073. }
  28074. if (curveStyle === 'straight-triangle') {
  28075. r.drawEdgeTrianglePath(edge, context, rs.allpts);
  28076. } else {
  28077. r.drawEdgePath(edge, context, rs.allpts, lineStyle);
  28078. context.lineCap = 'butt'; // reset for other drawing functions
  28079. }
  28080. };
  28081. var drawOverlay = function drawOverlay() {
  28082. if (!shouldDrawOverlay) {
  28083. return;
  28084. }
  28085. r.drawEdgeOverlay(context, edge);
  28086. };
  28087. var drawUnderlay = function drawUnderlay() {
  28088. if (!shouldDrawOverlay) {
  28089. return;
  28090. }
  28091. r.drawEdgeUnderlay(context, edge);
  28092. };
  28093. var drawArrows = function drawArrows() {
  28094. var arrowOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : effectiveArrowOpacity;
  28095. r.drawArrowheads(context, edge, arrowOpacity);
  28096. };
  28097. var drawText = function drawText() {
  28098. r.drawElementText(context, edge, null, drawLabel);
  28099. };
  28100. context.lineJoin = 'round';
  28101. var ghost = edge.pstyle('ghost').value === 'yes';
  28102. if (ghost) {
  28103. var gx = edge.pstyle('ghost-offset-x').pfValue;
  28104. var gy = edge.pstyle('ghost-offset-y').pfValue;
  28105. var ghostOpacity = edge.pstyle('ghost-opacity').value;
  28106. var effectiveGhostOpacity = effectiveLineOpacity * ghostOpacity;
  28107. context.translate(gx, gy);
  28108. drawLine(effectiveGhostOpacity);
  28109. drawArrows(effectiveGhostOpacity);
  28110. context.translate(-gx, -gy);
  28111. } else {
  28112. drawLineOutline();
  28113. }
  28114. drawUnderlay();
  28115. drawLine();
  28116. drawArrows();
  28117. drawOverlay();
  28118. drawText();
  28119. if (shiftToOriginWithBb) {
  28120. context.translate(bb.x1, bb.y1);
  28121. }
  28122. };
  28123. var drawEdgeOverlayUnderlay = function drawEdgeOverlayUnderlay(overlayOrUnderlay) {
  28124. if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
  28125. throw new Error('Invalid state');
  28126. }
  28127. return function (context, edge) {
  28128. if (!edge.visible()) {
  28129. return;
  28130. }
  28131. var opacity = edge.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
  28132. if (opacity === 0) {
  28133. return;
  28134. }
  28135. var r = this;
  28136. var usePaths = r.usePaths();
  28137. var rs = edge._private.rscratch;
  28138. var padding = edge.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
  28139. var width = 2 * padding;
  28140. var color = edge.pstyle("".concat(overlayOrUnderlay, "-color")).value;
  28141. context.lineWidth = width;
  28142. if (rs.edgeType === 'self' && !usePaths) {
  28143. context.lineCap = 'butt';
  28144. } else {
  28145. context.lineCap = 'round';
  28146. }
  28147. r.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  28148. r.drawEdgePath(edge, context, rs.allpts, 'solid');
  28149. };
  28150. };
  28151. CRp$9.drawEdgeOverlay = drawEdgeOverlayUnderlay('overlay');
  28152. CRp$9.drawEdgeUnderlay = drawEdgeOverlayUnderlay('underlay');
  28153. CRp$9.drawEdgePath = function (edge, context, pts, type) {
  28154. var rs = edge._private.rscratch;
  28155. var canvasCxt = context;
  28156. var path;
  28157. var pathCacheHit = false;
  28158. var usePaths = this.usePaths();
  28159. var lineDashPattern = edge.pstyle('line-dash-pattern').pfValue;
  28160. var lineDashOffset = edge.pstyle('line-dash-offset').pfValue;
  28161. if (usePaths) {
  28162. var pathCacheKey = pts.join('$');
  28163. var keyMatches = rs.pathCacheKey && rs.pathCacheKey === pathCacheKey;
  28164. if (keyMatches) {
  28165. path = context = rs.pathCache;
  28166. pathCacheHit = true;
  28167. } else {
  28168. path = context = new Path2D();
  28169. rs.pathCacheKey = pathCacheKey;
  28170. rs.pathCache = path;
  28171. }
  28172. }
  28173. if (canvasCxt.setLineDash) {
  28174. // for very outofdate browsers
  28175. switch (type) {
  28176. case 'dotted':
  28177. canvasCxt.setLineDash([1, 1]);
  28178. break;
  28179. case 'dashed':
  28180. canvasCxt.setLineDash(lineDashPattern);
  28181. canvasCxt.lineDashOffset = lineDashOffset;
  28182. break;
  28183. case 'solid':
  28184. canvasCxt.setLineDash([]);
  28185. break;
  28186. }
  28187. }
  28188. if (!pathCacheHit && !rs.badLine) {
  28189. if (context.beginPath) {
  28190. context.beginPath();
  28191. }
  28192. context.moveTo(pts[0], pts[1]);
  28193. switch (rs.edgeType) {
  28194. case 'bezier':
  28195. case 'self':
  28196. case 'compound':
  28197. case 'multibezier':
  28198. for (var i = 2; i + 3 < pts.length; i += 4) {
  28199. context.quadraticCurveTo(pts[i], pts[i + 1], pts[i + 2], pts[i + 3]);
  28200. }
  28201. break;
  28202. case 'straight':
  28203. case 'haystack':
  28204. for (var _i = 2; _i + 1 < pts.length; _i += 2) {
  28205. context.lineTo(pts[_i], pts[_i + 1]);
  28206. }
  28207. break;
  28208. case 'segments':
  28209. if (rs.isRound) {
  28210. var _iterator = _createForOfIteratorHelper(rs.roundCorners),
  28211. _step;
  28212. try {
  28213. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  28214. var corner = _step.value;
  28215. drawPreparedRoundCorner(context, corner);
  28216. }
  28217. } catch (err) {
  28218. _iterator.e(err);
  28219. } finally {
  28220. _iterator.f();
  28221. }
  28222. context.lineTo(pts[pts.length - 2], pts[pts.length - 1]);
  28223. } else {
  28224. for (var _i2 = 2; _i2 + 1 < pts.length; _i2 += 2) {
  28225. context.lineTo(pts[_i2], pts[_i2 + 1]);
  28226. }
  28227. }
  28228. break;
  28229. }
  28230. }
  28231. context = canvasCxt;
  28232. if (usePaths) {
  28233. context.stroke(path);
  28234. } else {
  28235. context.stroke();
  28236. }
  28237. // reset any line dashes
  28238. if (context.setLineDash) {
  28239. // for very outofdate browsers
  28240. context.setLineDash([]);
  28241. }
  28242. };
  28243. CRp$9.drawEdgeTrianglePath = function (edge, context, pts) {
  28244. // use line stroke style for triangle fill style
  28245. context.fillStyle = context.strokeStyle;
  28246. var edgeWidth = edge.pstyle('width').pfValue;
  28247. for (var i = 0; i + 1 < pts.length; i += 2) {
  28248. var vector = [pts[i + 2] - pts[i], pts[i + 3] - pts[i + 1]];
  28249. var length = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);
  28250. var normal = [vector[1] / length, -vector[0] / length];
  28251. var triangleHead = [normal[0] * edgeWidth / 2, normal[1] * edgeWidth / 2];
  28252. context.beginPath();
  28253. context.moveTo(pts[i] - triangleHead[0], pts[i + 1] - triangleHead[1]);
  28254. context.lineTo(pts[i] + triangleHead[0], pts[i + 1] + triangleHead[1]);
  28255. context.lineTo(pts[i + 2], pts[i + 3]);
  28256. context.closePath();
  28257. context.fill();
  28258. }
  28259. };
  28260. CRp$9.drawArrowheads = function (context, edge, opacity) {
  28261. var rs = edge._private.rscratch;
  28262. var isHaystack = rs.edgeType === 'haystack';
  28263. if (!isHaystack) {
  28264. this.drawArrowhead(context, edge, 'source', rs.arrowStartX, rs.arrowStartY, rs.srcArrowAngle, opacity);
  28265. }
  28266. this.drawArrowhead(context, edge, 'mid-target', rs.midX, rs.midY, rs.midtgtArrowAngle, opacity);
  28267. this.drawArrowhead(context, edge, 'mid-source', rs.midX, rs.midY, rs.midsrcArrowAngle, opacity);
  28268. if (!isHaystack) {
  28269. this.drawArrowhead(context, edge, 'target', rs.arrowEndX, rs.arrowEndY, rs.tgtArrowAngle, opacity);
  28270. }
  28271. };
  28272. CRp$9.drawArrowhead = function (context, edge, prefix, x, y, angle, opacity) {
  28273. if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
  28274. return;
  28275. }
  28276. var self = this;
  28277. var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  28278. if (arrowShape === 'none') {
  28279. return;
  28280. }
  28281. var arrowClearFill = edge.pstyle(prefix + '-arrow-fill').value === 'hollow' ? 'both' : 'filled';
  28282. var arrowFill = edge.pstyle(prefix + '-arrow-fill').value;
  28283. var edgeWidth = edge.pstyle('width').pfValue;
  28284. var pArrowWidth = edge.pstyle(prefix + '-arrow-width');
  28285. var arrowWidth = pArrowWidth.value === 'match-line' ? edgeWidth : pArrowWidth.pfValue;
  28286. if (pArrowWidth.units === '%') arrowWidth *= edgeWidth;
  28287. var edgeOpacity = edge.pstyle('opacity').value;
  28288. if (opacity === undefined) {
  28289. opacity = edgeOpacity;
  28290. }
  28291. var gco = context.globalCompositeOperation;
  28292. if (opacity !== 1 || arrowFill === 'hollow') {
  28293. // then extra clear is needed
  28294. context.globalCompositeOperation = 'destination-out';
  28295. self.colorFillStyle(context, 255, 255, 255, 1);
  28296. self.colorStrokeStyle(context, 255, 255, 255, 1);
  28297. self.drawArrowShape(edge, context, arrowClearFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
  28298. context.globalCompositeOperation = gco;
  28299. } // otherwise, the opaque arrow clears it for free :)
  28300. var color = edge.pstyle(prefix + '-arrow-color').value;
  28301. self.colorFillStyle(context, color[0], color[1], color[2], opacity);
  28302. self.colorStrokeStyle(context, color[0], color[1], color[2], opacity);
  28303. self.drawArrowShape(edge, context, arrowFill, edgeWidth, arrowShape, arrowWidth, x, y, angle);
  28304. };
  28305. CRp$9.drawArrowShape = function (edge, context, fill, edgeWidth, shape, shapeWidth, x, y, angle) {
  28306. var r = this;
  28307. var usePaths = this.usePaths() && shape !== 'triangle-cross';
  28308. var pathCacheHit = false;
  28309. var path;
  28310. var canvasContext = context;
  28311. var translation = {
  28312. x: x,
  28313. y: y
  28314. };
  28315. var scale = edge.pstyle('arrow-scale').value;
  28316. var size = this.getArrowWidth(edgeWidth, scale);
  28317. var shapeImpl = r.arrowShapes[shape];
  28318. if (usePaths) {
  28319. var cache = r.arrowPathCache = r.arrowPathCache || [];
  28320. var key = hashString(shape);
  28321. var cachedPath = cache[key];
  28322. if (cachedPath != null) {
  28323. path = context = cachedPath;
  28324. pathCacheHit = true;
  28325. } else {
  28326. path = context = new Path2D();
  28327. cache[key] = path;
  28328. }
  28329. }
  28330. if (!pathCacheHit) {
  28331. if (context.beginPath) {
  28332. context.beginPath();
  28333. }
  28334. if (usePaths) {
  28335. // store in the path cache with values easily manipulated later
  28336. shapeImpl.draw(context, 1, 0, {
  28337. x: 0,
  28338. y: 0
  28339. }, 1);
  28340. } else {
  28341. shapeImpl.draw(context, size, angle, translation, edgeWidth);
  28342. }
  28343. if (context.closePath) {
  28344. context.closePath();
  28345. }
  28346. }
  28347. context = canvasContext;
  28348. if (usePaths) {
  28349. // set transform to arrow position/orientation
  28350. context.translate(x, y);
  28351. context.rotate(angle);
  28352. context.scale(size, size);
  28353. }
  28354. if (fill === 'filled' || fill === 'both') {
  28355. if (usePaths) {
  28356. context.fill(path);
  28357. } else {
  28358. context.fill();
  28359. }
  28360. }
  28361. if (fill === 'hollow' || fill === 'both') {
  28362. context.lineWidth = shapeWidth / (usePaths ? size : 1);
  28363. context.lineJoin = 'miter';
  28364. if (usePaths) {
  28365. context.stroke(path);
  28366. } else {
  28367. context.stroke();
  28368. }
  28369. }
  28370. if (usePaths) {
  28371. // reset transform by applying inverse
  28372. context.scale(1 / size, 1 / size);
  28373. context.rotate(-angle);
  28374. context.translate(-x, -y);
  28375. }
  28376. };
  28377. var CRp$8 = {};
  28378. CRp$8.safeDrawImage = function (context, img, ix, iy, iw, ih, x, y, w, h) {
  28379. // detect problematic cases for old browsers with bad images (cheaper than try-catch)
  28380. if (iw <= 0 || ih <= 0 || w <= 0 || h <= 0) {
  28381. return;
  28382. }
  28383. try {
  28384. context.drawImage(img, ix, iy, iw, ih, x, y, w, h);
  28385. } catch (e) {
  28386. warn(e);
  28387. }
  28388. };
  28389. CRp$8.drawInscribedImage = function (context, img, node, index, nodeOpacity) {
  28390. var r = this;
  28391. var pos = node.position();
  28392. var nodeX = pos.x;
  28393. var nodeY = pos.y;
  28394. var styleObj = node.cy().style();
  28395. var getIndexedStyle = styleObj.getIndexedStyle.bind(styleObj);
  28396. var fit = getIndexedStyle(node, 'background-fit', 'value', index);
  28397. var repeat = getIndexedStyle(node, 'background-repeat', 'value', index);
  28398. var nodeW = node.width();
  28399. var nodeH = node.height();
  28400. var paddingX2 = node.padding() * 2;
  28401. var nodeTW = nodeW + (getIndexedStyle(node, 'background-width-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  28402. var nodeTH = nodeH + (getIndexedStyle(node, 'background-height-relative-to', 'value', index) === 'inner' ? 0 : paddingX2);
  28403. var rs = node._private.rscratch;
  28404. var clip = getIndexedStyle(node, 'background-clip', 'value', index);
  28405. var shouldClip = clip === 'node';
  28406. var imgOpacity = getIndexedStyle(node, 'background-image-opacity', 'value', index) * nodeOpacity;
  28407. var smooth = getIndexedStyle(node, 'background-image-smoothing', 'value', index);
  28408. var cornerRadius = node.pstyle('corner-radius').value;
  28409. if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  28410. var imgW = img.width || img.cachedW;
  28411. var imgH = img.height || img.cachedH;
  28412. // workaround for broken browsers like ie
  28413. if (null == imgW || null == imgH) {
  28414. document.body.appendChild(img); // eslint-disable-line no-undef
  28415. imgW = img.cachedW = img.width || img.offsetWidth;
  28416. imgH = img.cachedH = img.height || img.offsetHeight;
  28417. document.body.removeChild(img); // eslint-disable-line no-undef
  28418. }
  28419. var w = imgW;
  28420. var h = imgH;
  28421. if (getIndexedStyle(node, 'background-width', 'value', index) !== 'auto') {
  28422. if (getIndexedStyle(node, 'background-width', 'units', index) === '%') {
  28423. w = getIndexedStyle(node, 'background-width', 'pfValue', index) * nodeTW;
  28424. } else {
  28425. w = getIndexedStyle(node, 'background-width', 'pfValue', index);
  28426. }
  28427. }
  28428. if (getIndexedStyle(node, 'background-height', 'value', index) !== 'auto') {
  28429. if (getIndexedStyle(node, 'background-height', 'units', index) === '%') {
  28430. h = getIndexedStyle(node, 'background-height', 'pfValue', index) * nodeTH;
  28431. } else {
  28432. h = getIndexedStyle(node, 'background-height', 'pfValue', index);
  28433. }
  28434. }
  28435. if (w === 0 || h === 0) {
  28436. return; // no point in drawing empty image (and chrome is broken in this case)
  28437. }
  28438. if (fit === 'contain') {
  28439. var scale = Math.min(nodeTW / w, nodeTH / h);
  28440. w *= scale;
  28441. h *= scale;
  28442. } else if (fit === 'cover') {
  28443. var scale = Math.max(nodeTW / w, nodeTH / h);
  28444. w *= scale;
  28445. h *= scale;
  28446. }
  28447. var x = nodeX - nodeTW / 2; // left
  28448. var posXUnits = getIndexedStyle(node, 'background-position-x', 'units', index);
  28449. var posXPfVal = getIndexedStyle(node, 'background-position-x', 'pfValue', index);
  28450. if (posXUnits === '%') {
  28451. x += (nodeTW - w) * posXPfVal;
  28452. } else {
  28453. x += posXPfVal;
  28454. }
  28455. var offXUnits = getIndexedStyle(node, 'background-offset-x', 'units', index);
  28456. var offXPfVal = getIndexedStyle(node, 'background-offset-x', 'pfValue', index);
  28457. if (offXUnits === '%') {
  28458. x += (nodeTW - w) * offXPfVal;
  28459. } else {
  28460. x += offXPfVal;
  28461. }
  28462. var y = nodeY - nodeTH / 2; // top
  28463. var posYUnits = getIndexedStyle(node, 'background-position-y', 'units', index);
  28464. var posYPfVal = getIndexedStyle(node, 'background-position-y', 'pfValue', index);
  28465. if (posYUnits === '%') {
  28466. y += (nodeTH - h) * posYPfVal;
  28467. } else {
  28468. y += posYPfVal;
  28469. }
  28470. var offYUnits = getIndexedStyle(node, 'background-offset-y', 'units', index);
  28471. var offYPfVal = getIndexedStyle(node, 'background-offset-y', 'pfValue', index);
  28472. if (offYUnits === '%') {
  28473. y += (nodeTH - h) * offYPfVal;
  28474. } else {
  28475. y += offYPfVal;
  28476. }
  28477. if (rs.pathCache) {
  28478. x -= nodeX;
  28479. y -= nodeY;
  28480. nodeX = 0;
  28481. nodeY = 0;
  28482. }
  28483. var gAlpha = context.globalAlpha;
  28484. context.globalAlpha = imgOpacity;
  28485. var smoothingEnabled = r.getImgSmoothing(context);
  28486. var isSmoothingSwitched = false;
  28487. if (smooth === 'no' && smoothingEnabled) {
  28488. r.setImgSmoothing(context, false);
  28489. isSmoothingSwitched = true;
  28490. } else if (smooth === 'yes' && !smoothingEnabled) {
  28491. r.setImgSmoothing(context, true);
  28492. isSmoothingSwitched = true;
  28493. }
  28494. if (repeat === 'no-repeat') {
  28495. if (shouldClip) {
  28496. context.save();
  28497. if (rs.pathCache) {
  28498. context.clip(rs.pathCache);
  28499. } else {
  28500. r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
  28501. context.clip();
  28502. }
  28503. }
  28504. r.safeDrawImage(context, img, 0, 0, imgW, imgH, x, y, w, h);
  28505. if (shouldClip) {
  28506. context.restore();
  28507. }
  28508. } else {
  28509. var pattern = context.createPattern(img, repeat);
  28510. context.fillStyle = pattern;
  28511. r.nodeShapes[r.getNodeShape(node)].draw(context, nodeX, nodeY, nodeTW, nodeTH, cornerRadius, rs);
  28512. context.translate(x, y);
  28513. context.fill();
  28514. context.translate(-x, -y);
  28515. }
  28516. context.globalAlpha = gAlpha;
  28517. if (isSmoothingSwitched) {
  28518. r.setImgSmoothing(context, smoothingEnabled);
  28519. }
  28520. };
  28521. var CRp$7 = {};
  28522. CRp$7.eleTextBiggerThanMin = function (ele, scale) {
  28523. if (!scale) {
  28524. var zoom = ele.cy().zoom();
  28525. var pxRatio = this.getPixelRatio();
  28526. var lvl = Math.ceil(log2(zoom * pxRatio)); // the effective texture level
  28527. scale = Math.pow(2, lvl);
  28528. }
  28529. var computedSize = ele.pstyle('font-size').pfValue * scale;
  28530. var minSize = ele.pstyle('min-zoomed-font-size').pfValue;
  28531. if (computedSize < minSize) {
  28532. return false;
  28533. }
  28534. return true;
  28535. };
  28536. CRp$7.drawElementText = function (context, ele, shiftToOriginWithBb, force, prefix) {
  28537. var useEleOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28538. var r = this;
  28539. if (force == null) {
  28540. if (useEleOpacity && !r.eleTextBiggerThanMin(ele)) {
  28541. return;
  28542. }
  28543. } else if (force === false) {
  28544. return;
  28545. }
  28546. if (ele.isNode()) {
  28547. var label = ele.pstyle('label');
  28548. if (!label || !label.value) {
  28549. return;
  28550. }
  28551. var justification = r.getLabelJustification(ele);
  28552. context.textAlign = justification;
  28553. context.textBaseline = 'bottom';
  28554. } else {
  28555. var badLine = ele.element()._private.rscratch.badLine;
  28556. var _label = ele.pstyle('label');
  28557. var srcLabel = ele.pstyle('source-label');
  28558. var tgtLabel = ele.pstyle('target-label');
  28559. if (badLine || (!_label || !_label.value) && (!srcLabel || !srcLabel.value) && (!tgtLabel || !tgtLabel.value)) {
  28560. return;
  28561. }
  28562. context.textAlign = 'center';
  28563. context.textBaseline = 'bottom';
  28564. }
  28565. var applyRotation = !shiftToOriginWithBb;
  28566. var bb;
  28567. if (shiftToOriginWithBb) {
  28568. bb = shiftToOriginWithBb;
  28569. context.translate(-bb.x1, -bb.y1);
  28570. }
  28571. if (prefix == null) {
  28572. r.drawText(context, ele, null, applyRotation, useEleOpacity);
  28573. if (ele.isEdge()) {
  28574. r.drawText(context, ele, 'source', applyRotation, useEleOpacity);
  28575. r.drawText(context, ele, 'target', applyRotation, useEleOpacity);
  28576. }
  28577. } else {
  28578. r.drawText(context, ele, prefix, applyRotation, useEleOpacity);
  28579. }
  28580. if (shiftToOriginWithBb) {
  28581. context.translate(bb.x1, bb.y1);
  28582. }
  28583. };
  28584. CRp$7.getFontCache = function (context) {
  28585. var cache;
  28586. this.fontCaches = this.fontCaches || [];
  28587. for (var i = 0; i < this.fontCaches.length; i++) {
  28588. cache = this.fontCaches[i];
  28589. if (cache.context === context) {
  28590. return cache;
  28591. }
  28592. }
  28593. cache = {
  28594. context: context
  28595. };
  28596. this.fontCaches.push(cache);
  28597. return cache;
  28598. };
  28599. // set up canvas context with font
  28600. // returns transformed text string
  28601. CRp$7.setupTextStyle = function (context, ele) {
  28602. var useEleOpacity = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  28603. // Font style
  28604. var labelStyle = ele.pstyle('font-style').strValue;
  28605. var labelSize = ele.pstyle('font-size').pfValue + 'px';
  28606. var labelFamily = ele.pstyle('font-family').strValue;
  28607. var labelWeight = ele.pstyle('font-weight').strValue;
  28608. var opacity = useEleOpacity ? ele.effectiveOpacity() * ele.pstyle('text-opacity').value : 1;
  28609. var outlineOpacity = ele.pstyle('text-outline-opacity').value * opacity;
  28610. var color = ele.pstyle('color').value;
  28611. var outlineColor = ele.pstyle('text-outline-color').value;
  28612. context.font = labelStyle + ' ' + labelWeight + ' ' + labelSize + ' ' + labelFamily;
  28613. context.lineJoin = 'round'; // so text outlines aren't jagged
  28614. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  28615. this.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], outlineOpacity);
  28616. };
  28617. function circle(ctx, x, y, width, height) {
  28618. var diameter = Math.min(width, height);
  28619. var radius = diameter / 2;
  28620. var centerX = x + width / 2;
  28621. var centerY = y + height / 2;
  28622. ctx.beginPath();
  28623. ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  28624. ctx.closePath();
  28625. }
  28626. function roundRect(ctx, x, y, width, height) {
  28627. var radius = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 5;
  28628. var r = Math.min(radius, width / 2, height / 2); // prevent overflow
  28629. ctx.beginPath();
  28630. ctx.moveTo(x + r, y);
  28631. ctx.lineTo(x + width - r, y);
  28632. ctx.quadraticCurveTo(x + width, y, x + width, y + r);
  28633. ctx.lineTo(x + width, y + height - r);
  28634. ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
  28635. ctx.lineTo(x + r, y + height);
  28636. ctx.quadraticCurveTo(x, y + height, x, y + height - r);
  28637. ctx.lineTo(x, y + r);
  28638. ctx.quadraticCurveTo(x, y, x + r, y);
  28639. ctx.closePath();
  28640. }
  28641. CRp$7.getTextAngle = function (ele, prefix) {
  28642. var theta;
  28643. var _p = ele._private;
  28644. var rscratch = _p.rscratch;
  28645. var pdash = prefix ? prefix + '-' : '';
  28646. var rotation = ele.pstyle(pdash + 'text-rotation');
  28647. if (rotation.strValue === 'autorotate') {
  28648. var textAngle = getPrefixedProperty(rscratch, 'labelAngle', prefix);
  28649. theta = ele.isEdge() ? textAngle : 0;
  28650. } else if (rotation.strValue === 'none') {
  28651. theta = 0;
  28652. } else {
  28653. theta = rotation.pfValue;
  28654. }
  28655. return theta;
  28656. };
  28657. CRp$7.drawText = function (context, ele, prefix) {
  28658. var applyRotation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28659. var useEleOpacity = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28660. var _p = ele._private;
  28661. var rscratch = _p.rscratch;
  28662. var parentOpacity = useEleOpacity ? ele.effectiveOpacity() : 1;
  28663. if (useEleOpacity && (parentOpacity === 0 || ele.pstyle('text-opacity').value === 0)) {
  28664. return;
  28665. }
  28666. // use 'main' as an alias for the main label (i.e. null prefix)
  28667. if (prefix === 'main') {
  28668. prefix = null;
  28669. }
  28670. var textX = getPrefixedProperty(rscratch, 'labelX', prefix);
  28671. var textY = getPrefixedProperty(rscratch, 'labelY', prefix);
  28672. var orgTextX, orgTextY; // used for rotation
  28673. var text = this.getLabelText(ele, prefix);
  28674. if (text != null && text !== '' && !isNaN(textX) && !isNaN(textY)) {
  28675. this.setupTextStyle(context, ele, useEleOpacity);
  28676. var pdash = prefix ? prefix + '-' : '';
  28677. var textW = getPrefixedProperty(rscratch, 'labelWidth', prefix);
  28678. var textH = getPrefixedProperty(rscratch, 'labelHeight', prefix);
  28679. var marginX = ele.pstyle(pdash + 'text-margin-x').pfValue;
  28680. var marginY = ele.pstyle(pdash + 'text-margin-y').pfValue;
  28681. var isEdge = ele.isEdge();
  28682. var halign = ele.pstyle('text-halign').value;
  28683. var valign = ele.pstyle('text-valign').value;
  28684. if (isEdge) {
  28685. halign = 'center';
  28686. valign = 'center';
  28687. }
  28688. textX += marginX;
  28689. textY += marginY;
  28690. var theta;
  28691. if (!applyRotation) {
  28692. theta = 0;
  28693. } else {
  28694. theta = this.getTextAngle(ele, prefix);
  28695. }
  28696. if (theta !== 0) {
  28697. orgTextX = textX;
  28698. orgTextY = textY;
  28699. context.translate(orgTextX, orgTextY);
  28700. context.rotate(theta);
  28701. textX = 0;
  28702. textY = 0;
  28703. }
  28704. switch (valign) {
  28705. case 'top':
  28706. break;
  28707. case 'center':
  28708. textY += textH / 2;
  28709. break;
  28710. case 'bottom':
  28711. textY += textH;
  28712. break;
  28713. }
  28714. var backgroundOpacity = ele.pstyle('text-background-opacity').value;
  28715. var borderOpacity = ele.pstyle('text-border-opacity').value;
  28716. var textBorderWidth = ele.pstyle('text-border-width').pfValue;
  28717. var backgroundPadding = ele.pstyle('text-background-padding').pfValue;
  28718. var styleShape = ele.pstyle('text-background-shape').strValue;
  28719. var rounded = styleShape === 'round-rectangle' || styleShape === 'roundrectangle';
  28720. var circled = styleShape === 'circle';
  28721. var roundRadius = 2;
  28722. if (backgroundOpacity > 0 || textBorderWidth > 0 && borderOpacity > 0) {
  28723. var textFill = context.fillStyle;
  28724. var textStroke = context.strokeStyle;
  28725. var textLineWidth = context.lineWidth;
  28726. var textBackgroundColor = ele.pstyle('text-background-color').value;
  28727. var textBorderColor = ele.pstyle('text-border-color').value;
  28728. var textBorderStyle = ele.pstyle('text-border-style').value;
  28729. var doFill = backgroundOpacity > 0;
  28730. var doStroke = textBorderWidth > 0 && borderOpacity > 0;
  28731. var bgX = textX - backgroundPadding;
  28732. switch (halign) {
  28733. case 'left':
  28734. bgX -= textW;
  28735. break;
  28736. case 'center':
  28737. bgX -= textW / 2;
  28738. break;
  28739. }
  28740. var bgY = textY - textH - backgroundPadding;
  28741. var bgW = textW + 2 * backgroundPadding;
  28742. var bgH = textH + 2 * backgroundPadding;
  28743. if (doFill) {
  28744. context.fillStyle = "rgba(".concat(textBackgroundColor[0], ",").concat(textBackgroundColor[1], ",").concat(textBackgroundColor[2], ",").concat(backgroundOpacity * parentOpacity, ")");
  28745. }
  28746. if (doStroke) {
  28747. context.strokeStyle = "rgba(".concat(textBorderColor[0], ",").concat(textBorderColor[1], ",").concat(textBorderColor[2], ",").concat(borderOpacity * parentOpacity, ")");
  28748. context.lineWidth = textBorderWidth;
  28749. if (context.setLineDash) {
  28750. switch (textBorderStyle) {
  28751. case 'dotted':
  28752. context.setLineDash([1, 1]);
  28753. break;
  28754. case 'dashed':
  28755. context.setLineDash([4, 2]);
  28756. break;
  28757. case 'double':
  28758. context.lineWidth = textBorderWidth / 4;
  28759. context.setLineDash([]);
  28760. break;
  28761. case 'solid':
  28762. default:
  28763. context.setLineDash([]);
  28764. break;
  28765. }
  28766. }
  28767. }
  28768. if (rounded) {
  28769. context.beginPath();
  28770. roundRect(context, bgX, bgY, bgW, bgH, roundRadius);
  28771. } else if (circled) {
  28772. context.beginPath();
  28773. circle(context, bgX, bgY, bgW, bgH);
  28774. } else {
  28775. context.beginPath();
  28776. context.rect(bgX, bgY, bgW, bgH);
  28777. }
  28778. if (doFill) context.fill();
  28779. if (doStroke) context.stroke();
  28780. // Double border pass for 'double' style
  28781. if (doStroke && textBorderStyle === 'double') {
  28782. var whiteWidth = textBorderWidth / 2;
  28783. context.beginPath();
  28784. if (rounded) {
  28785. roundRect(context, bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth, roundRadius);
  28786. } else {
  28787. context.rect(bgX + whiteWidth, bgY + whiteWidth, bgW - 2 * whiteWidth, bgH - 2 * whiteWidth);
  28788. }
  28789. context.stroke();
  28790. }
  28791. context.fillStyle = textFill;
  28792. context.strokeStyle = textStroke;
  28793. context.lineWidth = textLineWidth;
  28794. if (context.setLineDash) context.setLineDash([]);
  28795. }
  28796. var lineWidth = 2 * ele.pstyle('text-outline-width').pfValue; // *2 b/c the stroke is drawn centred on the middle
  28797. if (lineWidth > 0) {
  28798. context.lineWidth = lineWidth;
  28799. }
  28800. if (ele.pstyle('text-wrap').value === 'wrap') {
  28801. var lines = getPrefixedProperty(rscratch, 'labelWrapCachedLines', prefix);
  28802. var lineHeight = getPrefixedProperty(rscratch, 'labelLineHeight', prefix);
  28803. var halfTextW = textW / 2;
  28804. var justification = this.getLabelJustification(ele);
  28805. if (justification === 'auto') ; else if (halign === 'left') {
  28806. // auto justification : right
  28807. if (justification === 'left') {
  28808. textX += -textW;
  28809. } else if (justification === 'center') {
  28810. textX += -halfTextW;
  28811. } // else same as auto
  28812. } else if (halign === 'center') {
  28813. // auto justfication : center
  28814. if (justification === 'left') {
  28815. textX += -halfTextW;
  28816. } else if (justification === 'right') {
  28817. textX += halfTextW;
  28818. } // else same as auto
  28819. } else if (halign === 'right') {
  28820. // auto justification : left
  28821. if (justification === 'center') {
  28822. textX += halfTextW;
  28823. } else if (justification === 'right') {
  28824. textX += textW;
  28825. } // else same as auto
  28826. }
  28827. switch (valign) {
  28828. case 'top':
  28829. textY -= (lines.length - 1) * lineHeight;
  28830. break;
  28831. case 'center':
  28832. case 'bottom':
  28833. textY -= (lines.length - 1) * lineHeight;
  28834. break;
  28835. }
  28836. for (var l = 0; l < lines.length; l++) {
  28837. if (lineWidth > 0) {
  28838. context.strokeText(lines[l], textX, textY);
  28839. }
  28840. context.fillText(lines[l], textX, textY);
  28841. textY += lineHeight;
  28842. }
  28843. } else {
  28844. if (lineWidth > 0) {
  28845. context.strokeText(text, textX, textY);
  28846. }
  28847. context.fillText(text, textX, textY);
  28848. }
  28849. if (theta !== 0) {
  28850. context.rotate(-theta);
  28851. context.translate(-orgTextX, -orgTextY);
  28852. }
  28853. }
  28854. };
  28855. /* global Path2D */
  28856. var CRp$6 = {};
  28857. CRp$6.drawNode = function (context, node, shiftToOriginWithBb) {
  28858. var drawLabel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  28859. var shouldDrawOverlay = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  28860. var shouldDrawOpacity = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
  28861. var r = this;
  28862. var nodeWidth, nodeHeight;
  28863. var _p = node._private;
  28864. var rs = _p.rscratch;
  28865. var pos = node.position();
  28866. if (!number$1(pos.x) || !number$1(pos.y)) {
  28867. return; // can't draw node with undefined position
  28868. }
  28869. if (shouldDrawOpacity && !node.visible()) {
  28870. return;
  28871. }
  28872. var eleOpacity = shouldDrawOpacity ? node.effectiveOpacity() : 1;
  28873. var usePaths = r.usePaths();
  28874. var path;
  28875. var pathCacheHit = false;
  28876. var padding = node.padding();
  28877. nodeWidth = node.width() + 2 * padding;
  28878. nodeHeight = node.height() + 2 * padding;
  28879. //
  28880. // setup shift
  28881. var bb;
  28882. if (shiftToOriginWithBb) {
  28883. bb = shiftToOriginWithBb;
  28884. context.translate(-bb.x1, -bb.y1);
  28885. }
  28886. //
  28887. // load bg image
  28888. var bgImgProp = node.pstyle('background-image');
  28889. var urls = bgImgProp.value;
  28890. var urlDefined = new Array(urls.length);
  28891. var image = new Array(urls.length);
  28892. var numImages = 0;
  28893. for (var i = 0; i < urls.length; i++) {
  28894. var url = urls[i];
  28895. var defd = urlDefined[i] = url != null && url !== 'none';
  28896. if (defd) {
  28897. var bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i);
  28898. numImages++;
  28899. // get image, and if not loaded then ask to redraw when later loaded
  28900. image[i] = r.getCachedImage(url, bgImgCrossOrigin, function () {
  28901. _p.backgroundTimestamp = Date.now();
  28902. node.emitAndNotify('background');
  28903. });
  28904. }
  28905. }
  28906. //
  28907. // setup styles
  28908. var darkness = node.pstyle('background-blacken').value;
  28909. var borderWidth = node.pstyle('border-width').pfValue;
  28910. var bgOpacity = node.pstyle('background-opacity').value * eleOpacity;
  28911. var borderColor = node.pstyle('border-color').value;
  28912. var borderStyle = node.pstyle('border-style').value;
  28913. var borderJoin = node.pstyle('border-join').value;
  28914. var borderCap = node.pstyle('border-cap').value;
  28915. var borderPosition = node.pstyle('border-position').value;
  28916. var borderPattern = node.pstyle('border-dash-pattern').pfValue;
  28917. var borderOffset = node.pstyle('border-dash-offset').pfValue;
  28918. var borderOpacity = node.pstyle('border-opacity').value * eleOpacity;
  28919. var outlineWidth = node.pstyle('outline-width').pfValue;
  28920. var outlineColor = node.pstyle('outline-color').value;
  28921. var outlineStyle = node.pstyle('outline-style').value;
  28922. var outlineOpacity = node.pstyle('outline-opacity').value * eleOpacity;
  28923. var outlineOffset = node.pstyle('outline-offset').value;
  28924. var cornerRadius = node.pstyle('corner-radius').value;
  28925. if (cornerRadius !== 'auto') cornerRadius = node.pstyle('corner-radius').pfValue;
  28926. var setupShapeColor = function setupShapeColor() {
  28927. var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity;
  28928. r.eleFillStyle(context, node, bgOpy);
  28929. };
  28930. var setupBorderColor = function setupBorderColor() {
  28931. var bdrOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : borderOpacity;
  28932. r.colorStrokeStyle(context, borderColor[0], borderColor[1], borderColor[2], bdrOpy);
  28933. };
  28934. var setupOutlineColor = function setupOutlineColor() {
  28935. var otlnOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : outlineOpacity;
  28936. r.colorStrokeStyle(context, outlineColor[0], outlineColor[1], outlineColor[2], otlnOpy);
  28937. };
  28938. //
  28939. // setup shape
  28940. var getPath = function getPath(width, height, shape, points) {
  28941. var pathCache = r.nodePathCache = r.nodePathCache || [];
  28942. var key = hashStrings(shape === 'polygon' ? shape + ',' + points.join(',') : shape, '' + height, '' + width, '' + cornerRadius);
  28943. var cachedPath = pathCache[key];
  28944. var path;
  28945. var cacheHit = false;
  28946. if (cachedPath != null) {
  28947. path = cachedPath;
  28948. cacheHit = true;
  28949. rs.pathCache = path;
  28950. } else {
  28951. path = new Path2D();
  28952. pathCache[key] = rs.pathCache = path;
  28953. }
  28954. return {
  28955. path: path,
  28956. cacheHit: cacheHit
  28957. };
  28958. };
  28959. var styleShape = node.pstyle('shape').strValue;
  28960. var shapePts = node.pstyle('shape-polygon-points').pfValue;
  28961. if (usePaths) {
  28962. context.translate(pos.x, pos.y);
  28963. var shapePath = getPath(nodeWidth, nodeHeight, styleShape, shapePts);
  28964. path = shapePath.path;
  28965. pathCacheHit = shapePath.cacheHit;
  28966. }
  28967. var drawShape = function drawShape() {
  28968. if (!pathCacheHit) {
  28969. var npos = pos;
  28970. if (usePaths) {
  28971. npos = {
  28972. x: 0,
  28973. y: 0
  28974. };
  28975. }
  28976. r.nodeShapes[r.getNodeShape(node)].draw(path || context, npos.x, npos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  28977. }
  28978. if (usePaths) {
  28979. context.fill(path);
  28980. } else {
  28981. context.fill();
  28982. }
  28983. };
  28984. var drawImages = function drawImages() {
  28985. var nodeOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
  28986. var inside = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  28987. var prevBging = _p.backgrounding;
  28988. var totalCompleted = 0;
  28989. for (var _i = 0; _i < image.length; _i++) {
  28990. var bgContainment = node.cy().style().getIndexedStyle(node, 'background-image-containment', 'value', _i);
  28991. if (inside && bgContainment === 'over' || !inside && bgContainment === 'inside') {
  28992. totalCompleted++;
  28993. continue;
  28994. }
  28995. if (urlDefined[_i] && image[_i].complete && !image[_i].error) {
  28996. totalCompleted++;
  28997. r.drawInscribedImage(context, image[_i], node, _i, nodeOpacity);
  28998. }
  28999. }
  29000. _p.backgrounding = !(totalCompleted === numImages);
  29001. if (prevBging !== _p.backgrounding) {
  29002. // update style b/c :backgrounding state changed
  29003. node.updateStyle(false);
  29004. }
  29005. };
  29006. var drawPie = function drawPie() {
  29007. var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  29008. var pieOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
  29009. if (r.hasPie(node)) {
  29010. r.drawPie(context, node, pieOpacity);
  29011. // redraw/restore path if steps after pie need it
  29012. if (redrawShape) {
  29013. if (!usePaths) {
  29014. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29015. }
  29016. }
  29017. }
  29018. };
  29019. var drawStripe = function drawStripe() {
  29020. var redrawShape = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  29021. var stripeOpacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : eleOpacity;
  29022. if (r.hasStripe(node)) {
  29023. context.save();
  29024. if (usePaths) {
  29025. context.clip(rs.pathCache);
  29026. } else {
  29027. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29028. context.clip();
  29029. }
  29030. r.drawStripe(context, node, stripeOpacity);
  29031. context.restore();
  29032. // redraw/restore path if steps after stripes need it
  29033. if (redrawShape) {
  29034. if (!usePaths) {
  29035. r.nodeShapes[r.getNodeShape(node)].draw(context, pos.x, pos.y, nodeWidth, nodeHeight, cornerRadius, rs);
  29036. }
  29037. }
  29038. }
  29039. };
  29040. var darken = function darken() {
  29041. var darkenOpacity = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : eleOpacity;
  29042. var opacity = (darkness > 0 ? darkness : -darkness) * darkenOpacity;
  29043. var c = darkness > 0 ? 0 : 255;
  29044. if (darkness !== 0) {
  29045. r.colorFillStyle(context, c, c, c, opacity);
  29046. if (usePaths) {
  29047. context.fill(path);
  29048. } else {
  29049. context.fill();
  29050. }
  29051. }
  29052. };
  29053. var drawBorder = function drawBorder() {
  29054. if (borderWidth > 0) {
  29055. context.lineWidth = borderWidth;
  29056. context.lineCap = borderCap;
  29057. context.lineJoin = borderJoin;
  29058. if (context.setLineDash) {
  29059. // for very outofdate browsers
  29060. switch (borderStyle) {
  29061. case 'dotted':
  29062. context.setLineDash([1, 1]);
  29063. break;
  29064. case 'dashed':
  29065. context.setLineDash(borderPattern);
  29066. context.lineDashOffset = borderOffset;
  29067. break;
  29068. case 'solid':
  29069. case 'double':
  29070. context.setLineDash([]);
  29071. break;
  29072. }
  29073. }
  29074. if (borderPosition !== 'center') {
  29075. context.save();
  29076. context.lineWidth *= 2;
  29077. if (borderPosition === 'inside') {
  29078. usePaths ? context.clip(path) : context.clip();
  29079. } else {
  29080. var region = new Path2D();
  29081. region.rect(-nodeWidth / 2 - borderWidth, -nodeHeight / 2 - borderWidth, nodeWidth + 2 * borderWidth, nodeHeight + 2 * borderWidth);
  29082. region.addPath(path);
  29083. context.clip(region, 'evenodd');
  29084. }
  29085. usePaths ? context.stroke(path) : context.stroke();
  29086. context.restore();
  29087. } else {
  29088. usePaths ? context.stroke(path) : context.stroke();
  29089. }
  29090. if (borderStyle === 'double') {
  29091. context.lineWidth = borderWidth / 3;
  29092. var gco = context.globalCompositeOperation;
  29093. context.globalCompositeOperation = 'destination-out';
  29094. if (usePaths) {
  29095. context.stroke(path);
  29096. } else {
  29097. context.stroke();
  29098. }
  29099. context.globalCompositeOperation = gco;
  29100. }
  29101. // reset in case we changed the border style
  29102. if (context.setLineDash) {
  29103. // for very outofdate browsers
  29104. context.setLineDash([]);
  29105. }
  29106. }
  29107. };
  29108. var drawOutline = function drawOutline() {
  29109. if (outlineWidth > 0) {
  29110. context.lineWidth = outlineWidth;
  29111. context.lineCap = 'butt';
  29112. if (context.setLineDash) {
  29113. // for very outofdate browsers
  29114. switch (outlineStyle) {
  29115. case 'dotted':
  29116. context.setLineDash([1, 1]);
  29117. break;
  29118. case 'dashed':
  29119. context.setLineDash([4, 2]);
  29120. break;
  29121. case 'solid':
  29122. case 'double':
  29123. context.setLineDash([]);
  29124. break;
  29125. }
  29126. }
  29127. var npos = pos;
  29128. if (usePaths) {
  29129. npos = {
  29130. x: 0,
  29131. y: 0
  29132. };
  29133. }
  29134. var shape = r.getNodeShape(node);
  29135. var bWidth = borderWidth;
  29136. if (borderPosition === 'inside') bWidth = 0;
  29137. if (borderPosition === 'outside') bWidth *= 2;
  29138. var scaleX = (nodeWidth + bWidth + (outlineWidth + outlineOffset)) / nodeWidth;
  29139. var scaleY = (nodeHeight + bWidth + (outlineWidth + outlineOffset)) / nodeHeight;
  29140. var sWidth = nodeWidth * scaleX;
  29141. var sHeight = nodeHeight * scaleY;
  29142. var points = r.nodeShapes[shape].points;
  29143. var _path;
  29144. if (usePaths) {
  29145. var outlinePath = getPath(sWidth, sHeight, shape, points);
  29146. _path = outlinePath.path;
  29147. }
  29148. // draw the outline path, either by using expanded points or by scaling
  29149. // the dimensions, depending on shape
  29150. if (shape === "ellipse") {
  29151. r.drawEllipsePath(_path || context, npos.x, npos.y, sWidth, sHeight);
  29152. } else if (['round-diamond', 'round-heptagon', 'round-hexagon', 'round-octagon', 'round-pentagon', 'round-polygon', 'round-triangle', 'round-tag'].includes(shape)) {
  29153. var sMult = 0;
  29154. var offsetX = 0;
  29155. var offsetY = 0;
  29156. if (shape === 'round-diamond') {
  29157. sMult = (bWidth + outlineOffset + outlineWidth) * 1.4;
  29158. } else if (shape === 'round-heptagon') {
  29159. sMult = (bWidth + outlineOffset + outlineWidth) * 1.075;
  29160. offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 35;
  29161. } else if (shape === 'round-hexagon') {
  29162. sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
  29163. } else if (shape === 'round-pentagon') {
  29164. sMult = (bWidth + outlineOffset + outlineWidth) * 1.13;
  29165. offsetY = -(bWidth / 2 + outlineOffset + outlineWidth) / 15;
  29166. } else if (shape === 'round-tag') {
  29167. sMult = (bWidth + outlineOffset + outlineWidth) * 1.12;
  29168. offsetX = (bWidth / 2 + outlineWidth + outlineOffset) * .07;
  29169. } else if (shape === 'round-triangle') {
  29170. sMult = (bWidth + outlineOffset + outlineWidth) * (Math.PI / 2);
  29171. offsetY = -(bWidth + outlineOffset / 2 + outlineWidth) / Math.PI;
  29172. }
  29173. if (sMult !== 0) {
  29174. scaleX = (nodeWidth + sMult) / nodeWidth;
  29175. sWidth = nodeWidth * scaleX;
  29176. if (!['round-hexagon', 'round-tag'].includes(shape)) {
  29177. scaleY = (nodeHeight + sMult) / nodeHeight;
  29178. sHeight = nodeHeight * scaleY;
  29179. }
  29180. }
  29181. cornerRadius = cornerRadius === 'auto' ? getRoundPolygonRadius(sWidth, sHeight) : cornerRadius;
  29182. var halfW = sWidth / 2;
  29183. var halfH = sHeight / 2;
  29184. var radius = cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2;
  29185. var p = new Array(points.length / 2);
  29186. var corners = new Array(points.length / 2);
  29187. for (var _i2 = 0; _i2 < points.length / 2; _i2++) {
  29188. p[_i2] = {
  29189. x: npos.x + offsetX + halfW * points[_i2 * 2],
  29190. y: npos.y + offsetY + halfH * points[_i2 * 2 + 1]
  29191. };
  29192. }
  29193. var _i3,
  29194. p1,
  29195. p2,
  29196. p3,
  29197. len = p.length;
  29198. p1 = p[len - 1];
  29199. // for each point
  29200. for (_i3 = 0; _i3 < len; _i3++) {
  29201. p2 = p[_i3 % len];
  29202. p3 = p[(_i3 + 1) % len];
  29203. corners[_i3] = getRoundCorner(p1, p2, p3, radius);
  29204. p1 = p2;
  29205. p2 = p3;
  29206. }
  29207. r.drawRoundPolygonPath(_path || context, npos.x + offsetX, npos.y + offsetY, nodeWidth * scaleX, nodeHeight * scaleY, points, corners);
  29208. } else if (['roundrectangle', 'round-rectangle'].includes(shape)) {
  29209. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
  29210. r.drawRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
  29211. } else if (['cutrectangle', 'cut-rectangle'].includes(shape)) {
  29212. cornerRadius = cornerRadius === 'auto' ? getCutRectangleCornerLength() : cornerRadius;
  29213. r.drawCutRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, null, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 4);
  29214. } else if (['bottomroundrectangle', 'bottom-round-rectangle'].includes(shape)) {
  29215. cornerRadius = cornerRadius === 'auto' ? getRoundRectangleRadius(sWidth, sHeight) : cornerRadius;
  29216. r.drawBottomRoundRectanglePath(_path || context, npos.x, npos.y, sWidth, sHeight, cornerRadius + (bWidth + outlineWidth + outlineOffset) / 2);
  29217. } else if (shape === "barrel") {
  29218. r.drawBarrelPath(_path || context, npos.x, npos.y, sWidth, sHeight);
  29219. } else if (shape.startsWith("polygon") || ['rhomboid', 'right-rhomboid', 'round-tag', 'tag', 'vee'].includes(shape)) {
  29220. var pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
  29221. points = joinLines(expandPolygon(points, pad));
  29222. r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
  29223. } else {
  29224. var _pad = (bWidth + outlineWidth + outlineOffset) / nodeWidth;
  29225. points = joinLines(expandPolygon(points, -_pad));
  29226. r.drawPolygonPath(_path || context, npos.x, npos.y, nodeWidth, nodeHeight, points);
  29227. }
  29228. if (usePaths) {
  29229. context.stroke(_path);
  29230. } else {
  29231. context.stroke();
  29232. }
  29233. if (outlineStyle === 'double') {
  29234. context.lineWidth = bWidth / 3;
  29235. var gco = context.globalCompositeOperation;
  29236. context.globalCompositeOperation = 'destination-out';
  29237. if (usePaths) {
  29238. context.stroke(_path);
  29239. } else {
  29240. context.stroke();
  29241. }
  29242. context.globalCompositeOperation = gco;
  29243. }
  29244. // reset in case we changed the border style
  29245. if (context.setLineDash) {
  29246. // for very outofdate browsers
  29247. context.setLineDash([]);
  29248. }
  29249. }
  29250. };
  29251. var drawOverlay = function drawOverlay() {
  29252. if (shouldDrawOverlay) {
  29253. r.drawNodeOverlay(context, node, pos, nodeWidth, nodeHeight);
  29254. }
  29255. };
  29256. var drawUnderlay = function drawUnderlay() {
  29257. if (shouldDrawOverlay) {
  29258. r.drawNodeUnderlay(context, node, pos, nodeWidth, nodeHeight);
  29259. }
  29260. };
  29261. var drawText = function drawText() {
  29262. r.drawElementText(context, node, null, drawLabel);
  29263. };
  29264. var ghost = node.pstyle('ghost').value === 'yes';
  29265. if (ghost) {
  29266. var gx = node.pstyle('ghost-offset-x').pfValue;
  29267. var gy = node.pstyle('ghost-offset-y').pfValue;
  29268. var ghostOpacity = node.pstyle('ghost-opacity').value;
  29269. var effGhostOpacity = ghostOpacity * eleOpacity;
  29270. context.translate(gx, gy);
  29271. setupOutlineColor();
  29272. drawOutline();
  29273. setupShapeColor(ghostOpacity * bgOpacity);
  29274. drawShape();
  29275. drawImages(effGhostOpacity, true);
  29276. setupBorderColor(ghostOpacity * borderOpacity);
  29277. drawBorder();
  29278. drawPie(darkness !== 0 || borderWidth !== 0);
  29279. drawStripe(darkness !== 0 || borderWidth !== 0);
  29280. drawImages(effGhostOpacity, false);
  29281. darken(effGhostOpacity);
  29282. context.translate(-gx, -gy);
  29283. }
  29284. if (usePaths) {
  29285. context.translate(-pos.x, -pos.y);
  29286. }
  29287. drawUnderlay();
  29288. if (usePaths) {
  29289. context.translate(pos.x, pos.y);
  29290. }
  29291. setupOutlineColor();
  29292. drawOutline();
  29293. setupShapeColor();
  29294. drawShape();
  29295. drawImages(eleOpacity, true);
  29296. setupBorderColor();
  29297. drawBorder();
  29298. drawPie(darkness !== 0 || borderWidth !== 0);
  29299. drawStripe(darkness !== 0 || borderWidth !== 0);
  29300. drawImages(eleOpacity, false);
  29301. darken();
  29302. if (usePaths) {
  29303. context.translate(-pos.x, -pos.y);
  29304. }
  29305. drawText();
  29306. drawOverlay();
  29307. //
  29308. // clean up shift
  29309. if (shiftToOriginWithBb) {
  29310. context.translate(bb.x1, bb.y1);
  29311. }
  29312. };
  29313. var drawNodeOverlayUnderlay = function drawNodeOverlayUnderlay(overlayOrUnderlay) {
  29314. if (!['overlay', 'underlay'].includes(overlayOrUnderlay)) {
  29315. throw new Error('Invalid state');
  29316. }
  29317. return function (context, node, pos, nodeWidth, nodeHeight) {
  29318. var r = this;
  29319. if (!node.visible()) {
  29320. return;
  29321. }
  29322. var padding = node.pstyle("".concat(overlayOrUnderlay, "-padding")).pfValue;
  29323. var opacity = node.pstyle("".concat(overlayOrUnderlay, "-opacity")).value;
  29324. var color = node.pstyle("".concat(overlayOrUnderlay, "-color")).value;
  29325. var shape = node.pstyle("".concat(overlayOrUnderlay, "-shape")).value;
  29326. var radius = node.pstyle("".concat(overlayOrUnderlay, "-corner-radius")).value;
  29327. if (opacity > 0) {
  29328. pos = pos || node.position();
  29329. if (nodeWidth == null || nodeHeight == null) {
  29330. var _padding = node.padding();
  29331. nodeWidth = node.width() + 2 * _padding;
  29332. nodeHeight = node.height() + 2 * _padding;
  29333. }
  29334. r.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29335. r.nodeShapes[shape].draw(context, pos.x, pos.y, nodeWidth + padding * 2, nodeHeight + padding * 2, radius);
  29336. context.fill();
  29337. }
  29338. };
  29339. };
  29340. CRp$6.drawNodeOverlay = drawNodeOverlayUnderlay('overlay');
  29341. CRp$6.drawNodeUnderlay = drawNodeOverlayUnderlay('underlay');
  29342. // does the node have at least one pie piece?
  29343. CRp$6.hasPie = function (node) {
  29344. node = node[0]; // ensure ele ref
  29345. return node._private.hasPie;
  29346. };
  29347. CRp$6.hasStripe = function (node) {
  29348. node = node[0]; // ensure ele ref
  29349. return node._private.hasStripe;
  29350. };
  29351. CRp$6.drawPie = function (context, node, nodeOpacity, pos) {
  29352. node = node[0]; // ensure ele ref
  29353. pos = pos || node.position();
  29354. var cyStyle = node.cy().style();
  29355. var pieSize = node.pstyle('pie-size');
  29356. var hole = node.pstyle('pie-hole');
  29357. var overallStartAngle = node.pstyle('pie-start-angle').pfValue;
  29358. var x = pos.x;
  29359. var y = pos.y;
  29360. var nodeW = node.width();
  29361. var nodeH = node.height();
  29362. var radius = Math.min(nodeW, nodeH) / 2; // must fit in node
  29363. var holeRadius;
  29364. var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  29365. var usePaths = this.usePaths();
  29366. if (usePaths) {
  29367. x = 0;
  29368. y = 0;
  29369. }
  29370. if (pieSize.units === '%') {
  29371. radius = radius * pieSize.pfValue;
  29372. } else if (pieSize.pfValue !== undefined) {
  29373. radius = pieSize.pfValue / 2; // diameter in pixels => radius
  29374. }
  29375. if (hole.units === '%') {
  29376. holeRadius = radius * hole.pfValue;
  29377. } else if (hole.pfValue !== undefined) {
  29378. holeRadius = hole.pfValue / 2; // diameter in pixels => radius
  29379. }
  29380. if (holeRadius >= radius) {
  29381. return; // the pie would be invisible anyway
  29382. }
  29383. for (var i = 1; i <= cyStyle.pieBackgroundN; i++) {
  29384. // 1..N
  29385. var size = node.pstyle('pie-' + i + '-background-size').value;
  29386. var color = node.pstyle('pie-' + i + '-background-color').value;
  29387. var opacity = node.pstyle('pie-' + i + '-background-opacity').value * nodeOpacity;
  29388. var percent = size / 100; // map integer range [0, 100] to [0, 1]
  29389. // percent can't push beyond 1
  29390. if (percent + lastPercent > 1) {
  29391. percent = 1 - lastPercent;
  29392. }
  29393. var angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise
  29394. angleStart += overallStartAngle; // shift by the overall pie start angle
  29395. var angleDelta = 2 * Math.PI * percent;
  29396. var angleEnd = angleStart + angleDelta;
  29397. // ignore if
  29398. // - zero size
  29399. // - we're already beyond the full circle
  29400. // - adding the current slice would go beyond the full circle
  29401. if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
  29402. continue;
  29403. }
  29404. if (holeRadius === 0) {
  29405. // make a pie slice
  29406. context.beginPath();
  29407. context.moveTo(x, y);
  29408. context.arc(x, y, radius, angleStart, angleEnd);
  29409. context.closePath();
  29410. } else {
  29411. // make a pie slice that's like the above but with a hole in the middle
  29412. context.beginPath();
  29413. context.arc(x, y, radius, angleStart, angleEnd);
  29414. context.arc(x, y, holeRadius, angleEnd, angleStart, true); // true for anticlockwise
  29415. context.closePath();
  29416. }
  29417. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29418. context.fill();
  29419. lastPercent += percent;
  29420. }
  29421. };
  29422. CRp$6.drawStripe = function (context, node, nodeOpacity, pos) {
  29423. node = node[0]; // ensure ele ref
  29424. pos = pos || node.position();
  29425. var cyStyle = node.cy().style();
  29426. var x = pos.x;
  29427. var y = pos.y;
  29428. var nodeW = node.width();
  29429. var nodeH = node.height();
  29430. var lastPercent = 0; // what % to continue drawing pie slices from on [0, 1]
  29431. var usePaths = this.usePaths();
  29432. context.save();
  29433. var direction = node.pstyle('stripe-direction').value;
  29434. var stripeSize = node.pstyle('stripe-size');
  29435. switch (direction) {
  29436. case 'vertical':
  29437. break;
  29438. // default
  29439. case 'righward':
  29440. context.rotate(-Math.PI / 2);
  29441. break;
  29442. }
  29443. var stripeW = nodeW;
  29444. var stripeH = nodeH;
  29445. if (stripeSize.units === '%') {
  29446. stripeW = stripeW * stripeSize.pfValue;
  29447. stripeH = stripeH * stripeSize.pfValue;
  29448. } else if (stripeSize.pfValue !== undefined) {
  29449. stripeW = stripeSize.pfValue;
  29450. stripeH = stripeSize.pfValue;
  29451. }
  29452. if (usePaths) {
  29453. x = 0;
  29454. y = 0;
  29455. }
  29456. // shift up from the centre of the node to the top-left corner
  29457. y -= stripeW / 2;
  29458. x -= stripeH / 2;
  29459. for (var i = 1; i <= cyStyle.stripeBackgroundN; i++) {
  29460. // 1..N
  29461. var size = node.pstyle('stripe-' + i + '-background-size').value;
  29462. var color = node.pstyle('stripe-' + i + '-background-color').value;
  29463. var opacity = node.pstyle('stripe-' + i + '-background-opacity').value * nodeOpacity;
  29464. var percent = size / 100; // map integer range [0, 100] to [0, 1]
  29465. // percent can't push beyond 1
  29466. if (percent + lastPercent > 1) {
  29467. percent = 1 - lastPercent;
  29468. }
  29469. // ignore if
  29470. // - zero size
  29471. // - we're already beyond the full chart
  29472. // - adding the current slice would go beyond the full chart
  29473. if (size === 0 || lastPercent >= 1 || lastPercent + percent > 1) {
  29474. continue;
  29475. }
  29476. // draw rect for the current stripe
  29477. context.beginPath();
  29478. context.rect(x, y + stripeH * lastPercent, stripeW, stripeH * percent);
  29479. context.closePath();
  29480. this.colorFillStyle(context, color[0], color[1], color[2], opacity);
  29481. context.fill();
  29482. lastPercent += percent;
  29483. }
  29484. context.restore();
  29485. };
  29486. var CRp$5 = {};
  29487. var motionBlurDelay = 100;
  29488. // var isFirefox = typeof InstallTrigger !== 'undefined';
  29489. CRp$5.getPixelRatio = function () {
  29490. var context = this.data.contexts[0];
  29491. if (this.forcedPixelRatio != null) {
  29492. return this.forcedPixelRatio;
  29493. }
  29494. var containerWindow = this.cy.window();
  29495. var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29496. return (containerWindow.devicePixelRatio || 1) / backingStore; // eslint-disable-line no-undef
  29497. };
  29498. CRp$5.paintCache = function (context) {
  29499. var caches = this.paintCaches = this.paintCaches || [];
  29500. var needToCreateCache = true;
  29501. var cache;
  29502. for (var i = 0; i < caches.length; i++) {
  29503. cache = caches[i];
  29504. if (cache.context === context) {
  29505. needToCreateCache = false;
  29506. break;
  29507. }
  29508. }
  29509. if (needToCreateCache) {
  29510. cache = {
  29511. context: context
  29512. };
  29513. caches.push(cache);
  29514. }
  29515. return cache;
  29516. };
  29517. CRp$5.createGradientStyleFor = function (context, shapeStyleName, ele, fill, opacity) {
  29518. var gradientStyle;
  29519. var usePaths = this.usePaths();
  29520. var colors = ele.pstyle(shapeStyleName + '-gradient-stop-colors').value,
  29521. positions = ele.pstyle(shapeStyleName + '-gradient-stop-positions').pfValue;
  29522. if (fill === 'radial-gradient') {
  29523. if (ele.isEdge()) {
  29524. var start = ele.sourceEndpoint(),
  29525. end = ele.targetEndpoint(),
  29526. mid = ele.midpoint();
  29527. var d1 = dist(start, mid);
  29528. var d2 = dist(end, mid);
  29529. gradientStyle = context.createRadialGradient(mid.x, mid.y, 0, mid.x, mid.y, Math.max(d1, d2));
  29530. } else {
  29531. var pos = usePaths ? {
  29532. x: 0,
  29533. y: 0
  29534. } : ele.position(),
  29535. width = ele.paddedWidth(),
  29536. height = ele.paddedHeight();
  29537. gradientStyle = context.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, Math.max(width, height));
  29538. }
  29539. } else {
  29540. if (ele.isEdge()) {
  29541. var _start = ele.sourceEndpoint(),
  29542. _end = ele.targetEndpoint();
  29543. gradientStyle = context.createLinearGradient(_start.x, _start.y, _end.x, _end.y);
  29544. } else {
  29545. var _pos = usePaths ? {
  29546. x: 0,
  29547. y: 0
  29548. } : ele.position(),
  29549. _width = ele.paddedWidth(),
  29550. _height = ele.paddedHeight(),
  29551. halfWidth = _width / 2,
  29552. halfHeight = _height / 2;
  29553. var direction = ele.pstyle('background-gradient-direction').value;
  29554. switch (direction) {
  29555. case 'to-bottom':
  29556. gradientStyle = context.createLinearGradient(_pos.x, _pos.y - halfHeight, _pos.x, _pos.y + halfHeight);
  29557. break;
  29558. case 'to-top':
  29559. gradientStyle = context.createLinearGradient(_pos.x, _pos.y + halfHeight, _pos.x, _pos.y - halfHeight);
  29560. break;
  29561. case 'to-left':
  29562. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y, _pos.x - halfWidth, _pos.y);
  29563. break;
  29564. case 'to-right':
  29565. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y, _pos.x + halfWidth, _pos.y);
  29566. break;
  29567. case 'to-bottom-right':
  29568. case 'to-right-bottom':
  29569. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y - halfHeight, _pos.x + halfWidth, _pos.y + halfHeight);
  29570. break;
  29571. case 'to-top-right':
  29572. case 'to-right-top':
  29573. gradientStyle = context.createLinearGradient(_pos.x - halfWidth, _pos.y + halfHeight, _pos.x + halfWidth, _pos.y - halfHeight);
  29574. break;
  29575. case 'to-bottom-left':
  29576. case 'to-left-bottom':
  29577. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y - halfHeight, _pos.x - halfWidth, _pos.y + halfHeight);
  29578. break;
  29579. case 'to-top-left':
  29580. case 'to-left-top':
  29581. gradientStyle = context.createLinearGradient(_pos.x + halfWidth, _pos.y + halfHeight, _pos.x - halfWidth, _pos.y - halfHeight);
  29582. break;
  29583. }
  29584. }
  29585. }
  29586. if (!gradientStyle) return null; // invalid gradient style
  29587. var hasPositions = positions.length === colors.length;
  29588. var length = colors.length;
  29589. for (var i = 0; i < length; i++) {
  29590. gradientStyle.addColorStop(hasPositions ? positions[i] : i / (length - 1), 'rgba(' + colors[i][0] + ',' + colors[i][1] + ',' + colors[i][2] + ',' + opacity + ')');
  29591. }
  29592. return gradientStyle;
  29593. };
  29594. CRp$5.gradientFillStyle = function (context, ele, fill, opacity) {
  29595. var gradientStyle = this.createGradientStyleFor(context, 'background', ele, fill, opacity);
  29596. if (!gradientStyle) return null; // error
  29597. context.fillStyle = gradientStyle;
  29598. };
  29599. CRp$5.colorFillStyle = function (context, r, g, b, a) {
  29600. context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29601. // turn off for now, seems context does its own caching
  29602. // var cache = this.paintCache(context);
  29603. // var fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29604. // if( cache.fillStyle !== fillStyle ){
  29605. // context.fillStyle = cache.fillStyle = fillStyle;
  29606. // }
  29607. };
  29608. CRp$5.eleFillStyle = function (context, ele, opacity) {
  29609. var backgroundFill = ele.pstyle('background-fill').value;
  29610. if (backgroundFill === 'linear-gradient' || backgroundFill === 'radial-gradient') {
  29611. this.gradientFillStyle(context, ele, backgroundFill, opacity);
  29612. } else {
  29613. var backgroundColor = ele.pstyle('background-color').value;
  29614. this.colorFillStyle(context, backgroundColor[0], backgroundColor[1], backgroundColor[2], opacity);
  29615. }
  29616. };
  29617. CRp$5.gradientStrokeStyle = function (context, ele, fill, opacity) {
  29618. var gradientStyle = this.createGradientStyleFor(context, 'line', ele, fill, opacity);
  29619. if (!gradientStyle) return null; // error
  29620. context.strokeStyle = gradientStyle;
  29621. };
  29622. CRp$5.colorStrokeStyle = function (context, r, g, b, a) {
  29623. context.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29624. // turn off for now, seems context does its own caching
  29625. // var cache = this.paintCache(context);
  29626. // var strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  29627. // if( cache.strokeStyle !== strokeStyle ){
  29628. // context.strokeStyle = cache.strokeStyle = strokeStyle;
  29629. // }
  29630. };
  29631. CRp$5.eleStrokeStyle = function (context, ele, opacity) {
  29632. var lineFill = ele.pstyle('line-fill').value;
  29633. if (lineFill === 'linear-gradient' || lineFill === 'radial-gradient') {
  29634. this.gradientStrokeStyle(context, ele, lineFill, opacity);
  29635. } else {
  29636. var lineColor = ele.pstyle('line-color').value;
  29637. this.colorStrokeStyle(context, lineColor[0], lineColor[1], lineColor[2], opacity);
  29638. }
  29639. };
  29640. // Resize canvas
  29641. CRp$5.matchCanvasSize = function (container) {
  29642. var r = this;
  29643. var data = r.data;
  29644. var bb = r.findContainerClientCoords();
  29645. var width = bb[2];
  29646. var height = bb[3];
  29647. var pixelRatio = r.getPixelRatio();
  29648. var mbPxRatio = r.motionBlurPxRatio;
  29649. if (container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE] || container === r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG]) {
  29650. pixelRatio = mbPxRatio;
  29651. }
  29652. var canvasWidth = width * pixelRatio;
  29653. var canvasHeight = height * pixelRatio;
  29654. var canvas;
  29655. if (canvasWidth === r.canvasWidth && canvasHeight === r.canvasHeight) {
  29656. return; // save cycles if same
  29657. }
  29658. r.fontCaches = null; // resizing resets the style
  29659. var canvasContainer = data.canvasContainer;
  29660. canvasContainer.style.width = width + 'px';
  29661. canvasContainer.style.height = height + 'px';
  29662. for (var i = 0; i < r.CANVAS_LAYERS; i++) {
  29663. canvas = data.canvases[i];
  29664. canvas.width = canvasWidth;
  29665. canvas.height = canvasHeight;
  29666. canvas.style.width = width + 'px';
  29667. canvas.style.height = height + 'px';
  29668. }
  29669. for (var i = 0; i < r.BUFFER_COUNT; i++) {
  29670. canvas = data.bufferCanvases[i];
  29671. canvas.width = canvasWidth;
  29672. canvas.height = canvasHeight;
  29673. canvas.style.width = width + 'px';
  29674. canvas.style.height = height + 'px';
  29675. }
  29676. r.textureMult = 1;
  29677. if (pixelRatio <= 1) {
  29678. canvas = data.bufferCanvases[r.TEXTURE_BUFFER];
  29679. r.textureMult = 2;
  29680. canvas.width = canvasWidth * r.textureMult;
  29681. canvas.height = canvasHeight * r.textureMult;
  29682. }
  29683. r.canvasWidth = canvasWidth;
  29684. r.canvasHeight = canvasHeight;
  29685. r.pixelRatio = pixelRatio;
  29686. };
  29687. CRp$5.renderTo = function (cxt, zoom, pan, pxRatio) {
  29688. this.render({
  29689. forcedContext: cxt,
  29690. forcedZoom: zoom,
  29691. forcedPan: pan,
  29692. drawAllLayers: true,
  29693. forcedPxRatio: pxRatio
  29694. });
  29695. };
  29696. CRp$5.clearCanvas = function () {
  29697. var r = this;
  29698. var data = r.data;
  29699. function clear(context) {
  29700. context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  29701. }
  29702. clear(data.contexts[r.NODE]);
  29703. clear(data.contexts[r.DRAG]);
  29704. };
  29705. CRp$5.render = function (options) {
  29706. var r = this;
  29707. options = options || staticEmptyObject();
  29708. var cy = r.cy;
  29709. var forcedContext = options.forcedContext;
  29710. var drawAllLayers = options.drawAllLayers;
  29711. var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  29712. var forcedZoom = options.forcedZoom;
  29713. var forcedPan = options.forcedPan;
  29714. var pixelRatio = options.forcedPxRatio === undefined ? this.getPixelRatio() : options.forcedPxRatio;
  29715. var data = r.data;
  29716. var needDraw = data.canvasNeedsRedraw;
  29717. var textureDraw = r.textureOnViewport && !forcedContext && (r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming);
  29718. var motionBlur = options.motionBlur !== undefined ? options.motionBlur : r.motionBlur;
  29719. var mbPxRatio = r.motionBlurPxRatio;
  29720. var hasCompoundNodes = cy.hasCompoundNodes();
  29721. var inNodeDragGesture = r.hoverData.draggingEles;
  29722. var inBoxSelection = r.hoverData.selecting || r.touchData.selecting ? true : false;
  29723. motionBlur = motionBlur && !forcedContext && r.motionBlurEnabled && !inBoxSelection;
  29724. var motionBlurFadeEffect = motionBlur;
  29725. if (!forcedContext) {
  29726. if (r.prevPxRatio !== pixelRatio) {
  29727. r.invalidateContainerClientCoordsCache();
  29728. r.matchCanvasSize(r.container);
  29729. r.redrawHint('eles', true);
  29730. r.redrawHint('drag', true);
  29731. }
  29732. r.prevPxRatio = pixelRatio;
  29733. }
  29734. if (!forcedContext && r.motionBlurTimeout) {
  29735. clearTimeout(r.motionBlurTimeout);
  29736. }
  29737. if (motionBlur) {
  29738. if (r.mbFrames == null) {
  29739. r.mbFrames = 0;
  29740. }
  29741. r.mbFrames++;
  29742. if (r.mbFrames < 3) {
  29743. // need several frames before even high quality motionblur
  29744. motionBlurFadeEffect = false;
  29745. }
  29746. // go to lower quality blurry frames when several m/b frames have been rendered (avoids flashing)
  29747. if (r.mbFrames > r.minMbLowQualFrames) {
  29748. //r.fullQualityMb = false;
  29749. r.motionBlurPxRatio = r.mbPxRBlurry;
  29750. }
  29751. }
  29752. if (r.clearingMotionBlur) {
  29753. r.motionBlurPxRatio = 1;
  29754. }
  29755. // b/c drawToContext() may be async w.r.t. redraw(), keep track of last texture frame
  29756. // because a rogue async texture frame would clear needDraw
  29757. if (r.textureDrawLastFrame && !textureDraw) {
  29758. needDraw[r.NODE] = true;
  29759. needDraw[r.SELECT_BOX] = true;
  29760. }
  29761. var style = cy.style();
  29762. var zoom = cy.zoom();
  29763. var effectiveZoom = forcedZoom !== undefined ? forcedZoom : zoom;
  29764. var pan = cy.pan();
  29765. var effectivePan = {
  29766. x: pan.x,
  29767. y: pan.y
  29768. };
  29769. var vp = {
  29770. zoom: zoom,
  29771. pan: {
  29772. x: pan.x,
  29773. y: pan.y
  29774. }
  29775. };
  29776. var prevVp = r.prevViewport;
  29777. var viewportIsDiff = prevVp === undefined || vp.zoom !== prevVp.zoom || vp.pan.x !== prevVp.pan.x || vp.pan.y !== prevVp.pan.y;
  29778. // we want the low quality motionblur only when the viewport is being manipulated etc (where it's not noticed)
  29779. if (!viewportIsDiff && !(inNodeDragGesture && !hasCompoundNodes)) {
  29780. r.motionBlurPxRatio = 1;
  29781. }
  29782. if (forcedPan) {
  29783. effectivePan = forcedPan;
  29784. }
  29785. // apply pixel ratio
  29786. effectiveZoom *= pixelRatio;
  29787. effectivePan.x *= pixelRatio;
  29788. effectivePan.y *= pixelRatio;
  29789. var eles = r.getCachedZSortedEles();
  29790. function mbclear(context, x, y, w, h) {
  29791. var gco = context.globalCompositeOperation;
  29792. context.globalCompositeOperation = 'destination-out';
  29793. r.colorFillStyle(context, 255, 255, 255, r.motionBlurTransparency);
  29794. context.fillRect(x, y, w, h);
  29795. context.globalCompositeOperation = gco;
  29796. }
  29797. function setContextTransform(context, clear) {
  29798. var ePan, eZoom, w, h;
  29799. if (!r.clearingMotionBlur && (context === data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] || context === data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG])) {
  29800. ePan = {
  29801. x: pan.x * mbPxRatio,
  29802. y: pan.y * mbPxRatio
  29803. };
  29804. eZoom = zoom * mbPxRatio;
  29805. w = r.canvasWidth * mbPxRatio;
  29806. h = r.canvasHeight * mbPxRatio;
  29807. } else {
  29808. ePan = effectivePan;
  29809. eZoom = effectiveZoom;
  29810. w = r.canvasWidth;
  29811. h = r.canvasHeight;
  29812. }
  29813. context.setTransform(1, 0, 0, 1, 0, 0);
  29814. if (clear === 'motionBlur') {
  29815. mbclear(context, 0, 0, w, h);
  29816. } else if (!forcedContext && (clear === undefined || clear)) {
  29817. context.clearRect(0, 0, w, h);
  29818. }
  29819. if (!drawAllLayers) {
  29820. context.translate(ePan.x, ePan.y);
  29821. context.scale(eZoom, eZoom);
  29822. }
  29823. if (forcedPan) {
  29824. context.translate(forcedPan.x, forcedPan.y);
  29825. }
  29826. if (forcedZoom) {
  29827. context.scale(forcedZoom, forcedZoom);
  29828. }
  29829. }
  29830. if (!textureDraw) {
  29831. r.textureDrawLastFrame = false;
  29832. }
  29833. if (textureDraw) {
  29834. r.textureDrawLastFrame = true;
  29835. if (!r.textureCache) {
  29836. r.textureCache = {};
  29837. r.textureCache.bb = cy.mutableElements().boundingBox();
  29838. r.textureCache.texture = r.data.bufferCanvases[r.TEXTURE_BUFFER];
  29839. var cxt = r.data.bufferContexts[r.TEXTURE_BUFFER];
  29840. cxt.setTransform(1, 0, 0, 1, 0, 0);
  29841. cxt.clearRect(0, 0, r.canvasWidth * r.textureMult, r.canvasHeight * r.textureMult);
  29842. r.render({
  29843. forcedContext: cxt,
  29844. drawOnlyNodeLayer: true,
  29845. forcedPxRatio: pixelRatio * r.textureMult
  29846. });
  29847. var vp = r.textureCache.viewport = {
  29848. zoom: cy.zoom(),
  29849. pan: cy.pan(),
  29850. width: r.canvasWidth,
  29851. height: r.canvasHeight
  29852. };
  29853. vp.mpan = {
  29854. x: (0 - vp.pan.x) / vp.zoom,
  29855. y: (0 - vp.pan.y) / vp.zoom
  29856. };
  29857. }
  29858. needDraw[r.DRAG] = false;
  29859. needDraw[r.NODE] = false;
  29860. var context = data.contexts[r.NODE];
  29861. var texture = r.textureCache.texture;
  29862. var vp = r.textureCache.viewport;
  29863. context.setTransform(1, 0, 0, 1, 0, 0);
  29864. if (motionBlur) {
  29865. mbclear(context, 0, 0, vp.width, vp.height);
  29866. } else {
  29867. context.clearRect(0, 0, vp.width, vp.height);
  29868. }
  29869. var outsideBgColor = style.core('outside-texture-bg-color').value;
  29870. var outsideBgOpacity = style.core('outside-texture-bg-opacity').value;
  29871. r.colorFillStyle(context, outsideBgColor[0], outsideBgColor[1], outsideBgColor[2], outsideBgOpacity);
  29872. context.fillRect(0, 0, vp.width, vp.height);
  29873. var zoom = cy.zoom();
  29874. setContextTransform(context, false);
  29875. context.clearRect(vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  29876. context.drawImage(texture, vp.mpan.x, vp.mpan.y, vp.width / vp.zoom / pixelRatio, vp.height / vp.zoom / pixelRatio);
  29877. } else if (r.textureOnViewport && !forcedContext) {
  29878. // clear the cache since we don't need it
  29879. r.textureCache = null;
  29880. }
  29881. var extent = cy.extent();
  29882. var vpManip = r.pinching || r.hoverData.dragging || r.swipePanning || r.data.wheelZooming || r.hoverData.draggingEles || r.cy.animated();
  29883. var hideEdges = r.hideEdgesOnViewport && vpManip;
  29884. var needMbClear = [];
  29885. needMbClear[r.NODE] = !needDraw[r.NODE] && motionBlur && !r.clearedForMotionBlur[r.NODE] || r.clearingMotionBlur;
  29886. if (needMbClear[r.NODE]) {
  29887. r.clearedForMotionBlur[r.NODE] = true;
  29888. }
  29889. needMbClear[r.DRAG] = !needDraw[r.DRAG] && motionBlur && !r.clearedForMotionBlur[r.DRAG] || r.clearingMotionBlur;
  29890. if (needMbClear[r.DRAG]) {
  29891. r.clearedForMotionBlur[r.DRAG] = true;
  29892. }
  29893. if (needDraw[r.NODE] || drawAllLayers || drawOnlyNodeLayer || needMbClear[r.NODE]) {
  29894. var useBuffer = motionBlur && !needMbClear[r.NODE] && mbPxRatio !== 1;
  29895. var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_NODE] : data.contexts[r.NODE]);
  29896. var clear = motionBlur && !useBuffer ? 'motionBlur' : undefined;
  29897. setContextTransform(context, clear);
  29898. if (hideEdges) {
  29899. r.drawCachedNodes(context, eles.nondrag, pixelRatio, extent);
  29900. } else {
  29901. r.drawLayeredElements(context, eles.nondrag, pixelRatio, extent);
  29902. }
  29903. if (r.debug) {
  29904. r.drawDebugPoints(context, eles.nondrag);
  29905. }
  29906. if (!drawAllLayers && !motionBlur) {
  29907. needDraw[r.NODE] = false;
  29908. }
  29909. }
  29910. if (!drawOnlyNodeLayer && (needDraw[r.DRAG] || drawAllLayers || needMbClear[r.DRAG])) {
  29911. var useBuffer = motionBlur && !needMbClear[r.DRAG] && mbPxRatio !== 1;
  29912. var context = forcedContext || (useBuffer ? r.data.bufferContexts[r.MOTIONBLUR_BUFFER_DRAG] : data.contexts[r.DRAG]);
  29913. setContextTransform(context, motionBlur && !useBuffer ? 'motionBlur' : undefined);
  29914. if (hideEdges) {
  29915. r.drawCachedNodes(context, eles.drag, pixelRatio, extent);
  29916. } else {
  29917. r.drawCachedElements(context, eles.drag, pixelRatio, extent);
  29918. }
  29919. if (r.debug) {
  29920. r.drawDebugPoints(context, eles.drag);
  29921. }
  29922. if (!drawAllLayers && !motionBlur) {
  29923. needDraw[r.DRAG] = false;
  29924. }
  29925. }
  29926. this.drawSelectionRectangle(options, setContextTransform);
  29927. // motionblur: blit rendered blurry frames
  29928. if (motionBlur && mbPxRatio !== 1) {
  29929. var cxtNode = data.contexts[r.NODE];
  29930. var txtNode = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_NODE];
  29931. var cxtDrag = data.contexts[r.DRAG];
  29932. var txtDrag = r.data.bufferCanvases[r.MOTIONBLUR_BUFFER_DRAG];
  29933. var drawMotionBlur = function drawMotionBlur(cxt, txt, needClear) {
  29934. cxt.setTransform(1, 0, 0, 1, 0, 0);
  29935. if (needClear || !motionBlurFadeEffect) {
  29936. cxt.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  29937. } else {
  29938. mbclear(cxt, 0, 0, r.canvasWidth, r.canvasHeight);
  29939. }
  29940. var pxr = mbPxRatio;
  29941. cxt.drawImage(txt,
  29942. // img
  29943. 0, 0,
  29944. // sx, sy
  29945. r.canvasWidth * pxr, r.canvasHeight * pxr,
  29946. // sw, sh
  29947. 0, 0,
  29948. // x, y
  29949. r.canvasWidth, r.canvasHeight // w, h
  29950. );
  29951. };
  29952. if (needDraw[r.NODE] || needMbClear[r.NODE]) {
  29953. drawMotionBlur(cxtNode, txtNode, needMbClear[r.NODE]);
  29954. needDraw[r.NODE] = false;
  29955. }
  29956. if (needDraw[r.DRAG] || needMbClear[r.DRAG]) {
  29957. drawMotionBlur(cxtDrag, txtDrag, needMbClear[r.DRAG]);
  29958. needDraw[r.DRAG] = false;
  29959. }
  29960. }
  29961. r.prevViewport = vp;
  29962. if (r.clearingMotionBlur) {
  29963. r.clearingMotionBlur = false;
  29964. r.motionBlurCleared = true;
  29965. r.motionBlur = true;
  29966. }
  29967. if (motionBlur) {
  29968. r.motionBlurTimeout = setTimeout(function () {
  29969. r.motionBlurTimeout = null;
  29970. r.clearedForMotionBlur[r.NODE] = false;
  29971. r.clearedForMotionBlur[r.DRAG] = false;
  29972. r.motionBlur = false;
  29973. r.clearingMotionBlur = !textureDraw;
  29974. r.mbFrames = 0;
  29975. needDraw[r.NODE] = true;
  29976. needDraw[r.DRAG] = true;
  29977. r.redraw();
  29978. }, motionBlurDelay);
  29979. }
  29980. if (!forcedContext) {
  29981. cy.emit('render');
  29982. }
  29983. };
  29984. var fpsHeight;
  29985. CRp$5.drawSelectionRectangle = function (options, setContextTransform) {
  29986. var r = this;
  29987. var cy = r.cy;
  29988. var data = r.data;
  29989. var style = cy.style();
  29990. var drawOnlyNodeLayer = options.drawOnlyNodeLayer;
  29991. var drawAllLayers = options.drawAllLayers;
  29992. var needDraw = data.canvasNeedsRedraw;
  29993. var forcedContext = options.forcedContext;
  29994. if (r.showFps || !drawOnlyNodeLayer && needDraw[r.SELECT_BOX] && !drawAllLayers) {
  29995. var context = forcedContext || data.contexts[r.SELECT_BOX];
  29996. setContextTransform(context);
  29997. if (r.selection[4] == 1 && (r.hoverData.selecting || r.touchData.selecting)) {
  29998. var zoom = r.cy.zoom();
  29999. var borderWidth = style.core('selection-box-border-width').value / zoom;
  30000. context.lineWidth = borderWidth;
  30001. 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 + ')';
  30002. context.fillRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
  30003. if (borderWidth > 0) {
  30004. 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 + ')';
  30005. context.strokeRect(r.selection[0], r.selection[1], r.selection[2] - r.selection[0], r.selection[3] - r.selection[1]);
  30006. }
  30007. }
  30008. if (data.bgActivePosistion && !r.hoverData.selecting) {
  30009. var zoom = r.cy.zoom();
  30010. var pos = data.bgActivePosistion;
  30011. 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 + ')';
  30012. context.beginPath();
  30013. context.arc(pos.x, pos.y, style.core('active-bg-size').pfValue / zoom, 0, 2 * Math.PI);
  30014. context.fill();
  30015. }
  30016. var timeToRender = r.lastRedrawTime;
  30017. if (r.showFps && timeToRender) {
  30018. timeToRender = Math.round(timeToRender);
  30019. var fps = Math.round(1000 / timeToRender);
  30020. var text = '1 frame = ' + timeToRender + ' ms = ' + fps + ' fps';
  30021. context.setTransform(1, 0, 0, 1, 0, 0);
  30022. context.fillStyle = 'rgba(255, 0, 0, 0.75)';
  30023. context.strokeStyle = 'rgba(255, 0, 0, 0.75)';
  30024. // context.lineWidth = 1;
  30025. context.font = '30px Arial';
  30026. if (!fpsHeight) {
  30027. var dims = context.measureText(text);
  30028. fpsHeight = dims.actualBoundingBoxAscent;
  30029. }
  30030. context.fillText(text, 0, fpsHeight);
  30031. var maxFps = 60;
  30032. context.strokeRect(0, fpsHeight + 10, 250, 20);
  30033. context.fillRect(0, fpsHeight + 10, 250 * Math.min(fps / maxFps, 1), 20);
  30034. }
  30035. if (!drawAllLayers) {
  30036. needDraw[r.SELECT_BOX] = false;
  30037. }
  30038. }
  30039. };
  30040. /**
  30041. * Notes:
  30042. * - All colors have premultiplied alpha. Very important for textues and
  30043. * blending to work correctly.
  30044. */
  30045. function compileShader(gl, type, source) {
  30046. var shader = gl.createShader(type);
  30047. gl.shaderSource(shader, source);
  30048. gl.compileShader(shader);
  30049. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  30050. throw new Error(gl.getShaderInfoLog(shader));
  30051. }
  30052. // console.log(gl.getShaderInfoLog(shader));
  30053. return shader;
  30054. }
  30055. function createProgram(gl, vertexSource, fragementSource) {
  30056. var vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertexSource);
  30057. var fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragementSource);
  30058. var program = gl.createProgram();
  30059. gl.attachShader(program, vertexShader);
  30060. gl.attachShader(program, fragmentShader);
  30061. gl.linkProgram(program);
  30062. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  30063. throw new Error('Could not initialize shaders');
  30064. }
  30065. return program;
  30066. }
  30067. /**
  30068. * Creates an offscren canvas with a 2D context, for the
  30069. * canvas renderer to use for drawing textures.
  30070. */
  30071. function createTextureCanvas(r, width, height) {
  30072. if (height === undefined) {
  30073. height = width;
  30074. }
  30075. var canvas = r.makeOffscreenCanvas(width, height);
  30076. var ctx = canvas.context = canvas.getContext('2d');
  30077. canvas.clear = function () {
  30078. return ctx.clearRect(0, 0, canvas.width, canvas.height);
  30079. };
  30080. canvas.clear();
  30081. return canvas;
  30082. }
  30083. /**
  30084. * Returns the current pan & zoom values, scaled by the pixel ratio.
  30085. */
  30086. function getEffectivePanZoom(r) {
  30087. var pixelRatio = r.pixelRatio;
  30088. var zoom = r.cy.zoom();
  30089. var pan = r.cy.pan();
  30090. return {
  30091. zoom: zoom * pixelRatio,
  30092. pan: {
  30093. x: pan.x * pixelRatio,
  30094. y: pan.y * pixelRatio
  30095. }
  30096. };
  30097. }
  30098. /**
  30099. * Returns the zoom value, scaled by the pixel ratio.
  30100. */
  30101. function getEffectiveZoom(r) {
  30102. var pixelRatio = r.pixelRatio;
  30103. var zoom = r.cy.zoom();
  30104. return zoom * pixelRatio;
  30105. }
  30106. function modelToRenderedPosition(r, pan, zoom, x, y) {
  30107. var rx = x * zoom + pan.x;
  30108. var ry = y * zoom + pan.y;
  30109. ry = Math.round(r.canvasHeight - ry); // adjust for webgl
  30110. return [rx, ry];
  30111. }
  30112. function isSimpleShape(node, renderTarget) {
  30113. // the actual shape is checked in ElementDrawingWebGL._getVertTypeForShape()
  30114. // no need to check it twice, this just checks other visual properties
  30115. if (renderTarget.picking) {
  30116. // We don't care about the border or background style for picking
  30117. return true;
  30118. } else {
  30119. if (node.pstyle('background-fill').value !== 'solid') return false;
  30120. if (node.pstyle('background-image').strValue !== 'none') return false;
  30121. if (node.pstyle('border-width').value === 0) return true;
  30122. if (node.pstyle('border-opacity').value === 0) return true;
  30123. // we have a border but it must be simple
  30124. if (node.pstyle('border-style').value !== 'solid') return false;
  30125. // TODO ignoring 'border-cap', 'border-join' and 'border-position' for now
  30126. return true;
  30127. }
  30128. }
  30129. function arrayEqual(a1, a2) {
  30130. if (a1.length !== a2.length) {
  30131. return false;
  30132. }
  30133. for (var i = 0; i < a1.length; i++) {
  30134. if (a1[i] !== a2[i]) {
  30135. return false;
  30136. }
  30137. }
  30138. return true;
  30139. }
  30140. /**
  30141. * Takes color & opacity style values and converts them to WebGL format.
  30142. * Alpha is premultiplied.
  30143. */
  30144. function toWebGLColor(color, opacity, outArray) {
  30145. var r = color[0] / 255;
  30146. var g = color[1] / 255;
  30147. var b = color[2] / 255;
  30148. var a = opacity;
  30149. var arr = outArray || new Array(4);
  30150. arr[0] = r * a;
  30151. arr[1] = g * a;
  30152. arr[2] = b * a;
  30153. arr[3] = a;
  30154. return arr;
  30155. }
  30156. function indexToVec4(index, outArray) {
  30157. var arr = outArray || new Array(4);
  30158. arr[0] = (index >> 0 & 0xFF) / 0xFF;
  30159. arr[1] = (index >> 8 & 0xFF) / 0xFF;
  30160. arr[2] = (index >> 16 & 0xFF) / 0xFF;
  30161. arr[3] = (index >> 24 & 0xFF) / 0xFF;
  30162. return arr;
  30163. }
  30164. function vec4ToIndex(vec4) {
  30165. return vec4[0] + (vec4[1] << 8) + (vec4[2] << 16) + (vec4[3] << 24);
  30166. }
  30167. function createTexture(gl, debugID) {
  30168. var texture = gl.createTexture();
  30169. texture.buffer = function (offscreenCanvas) {
  30170. gl.bindTexture(gl.TEXTURE_2D, texture);
  30171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  30172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  30173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  30174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
  30175. // very important, this tells webgl to premultiply colors by the alpha channel
  30176. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
  30177. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offscreenCanvas);
  30178. gl.generateMipmap(gl.TEXTURE_2D);
  30179. gl.bindTexture(gl.TEXTURE_2D, null);
  30180. };
  30181. texture.deleteTexture = function () {
  30182. gl.deleteTexture(texture);
  30183. };
  30184. return texture;
  30185. }
  30186. function getTypeInfo(gl, glslType) {
  30187. switch (glslType) {
  30188. case 'float':
  30189. return [1, gl.FLOAT, 4];
  30190. case 'vec2':
  30191. return [2, gl.FLOAT, 4];
  30192. case 'vec3':
  30193. return [3, gl.FLOAT, 4];
  30194. case 'vec4':
  30195. return [4, gl.FLOAT, 4];
  30196. case 'int':
  30197. return [1, gl.INT, 4];
  30198. case 'ivec2':
  30199. return [2, gl.INT, 4];
  30200. }
  30201. }
  30202. function createTypedArray(gl, glType, dataOrSize) {
  30203. switch (glType) {
  30204. case gl.FLOAT:
  30205. return new Float32Array(dataOrSize);
  30206. case gl.INT:
  30207. return new Int32Array(dataOrSize);
  30208. }
  30209. }
  30210. function createTypedArrayView(gl, glType, array, stride, size, i) {
  30211. switch (glType) {
  30212. case gl.FLOAT:
  30213. return new Float32Array(array.buffer, i * stride, size);
  30214. case gl.INT:
  30215. return new Int32Array(array.buffer, i * stride, size);
  30216. }
  30217. }
  30218. /** @param {WebGLRenderingContext} gl */
  30219. function createBufferStaticDraw(gl, type, attributeLoc, dataArray) {
  30220. var _getTypeInfo = getTypeInfo(gl, type),
  30221. _getTypeInfo2 = _slicedToArray(_getTypeInfo, 2),
  30222. size = _getTypeInfo2[0],
  30223. glType = _getTypeInfo2[1];
  30224. var data = createTypedArray(gl, glType, dataArray);
  30225. var buffer = gl.createBuffer();
  30226. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30227. gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
  30228. if (glType === gl.FLOAT) {
  30229. gl.vertexAttribPointer(attributeLoc, size, glType, false, 0, 0);
  30230. } else if (glType === gl.INT) {
  30231. gl.vertexAttribIPointer(attributeLoc, size, glType, 0, 0);
  30232. }
  30233. gl.enableVertexAttribArray(attributeLoc);
  30234. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30235. return buffer;
  30236. }
  30237. /**
  30238. * Creates a float buffer with gl.DYNAMIC_DRAW.
  30239. * The returned buffer object contains functions to easily set instance data and buffer the data before a draw call.
  30240. * @param {WebGLRenderingContext} gl
  30241. */
  30242. function createBufferDynamicDraw(gl, instances, type, attributeLoc) {
  30243. var _getTypeInfo3 = getTypeInfo(gl, type),
  30244. _getTypeInfo4 = _slicedToArray(_getTypeInfo3, 3),
  30245. size = _getTypeInfo4[0],
  30246. glType = _getTypeInfo4[1],
  30247. bytes = _getTypeInfo4[2];
  30248. var dataArray = createTypedArray(gl, glType, instances * size);
  30249. var stride = size * bytes;
  30250. var buffer = gl.createBuffer();
  30251. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30252. gl.bufferData(gl.ARRAY_BUFFER, instances * stride, gl.DYNAMIC_DRAW);
  30253. gl.enableVertexAttribArray(attributeLoc);
  30254. if (glType === gl.FLOAT) {
  30255. gl.vertexAttribPointer(attributeLoc, size, glType, false, stride, 0);
  30256. } else if (glType === gl.INT) {
  30257. gl.vertexAttribIPointer(attributeLoc, size, glType, stride, 0);
  30258. }
  30259. gl.vertexAttribDivisor(attributeLoc, 1);
  30260. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30261. // use array views to set values directly into the buffer array
  30262. var views = new Array(instances);
  30263. for (var i = 0; i < instances; i++) {
  30264. views[i] = createTypedArrayView(gl, glType, dataArray, stride, size, i);
  30265. }
  30266. buffer.dataArray = dataArray;
  30267. buffer.stride = stride;
  30268. buffer.size = size;
  30269. buffer.getView = function (i) {
  30270. return views[i];
  30271. };
  30272. buffer.setPoint = function (i, x, y) {
  30273. var view = views[i];
  30274. view[0] = x;
  30275. view[1] = y;
  30276. };
  30277. buffer.bufferSubData = function (count) {
  30278. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30279. if (count) {
  30280. gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray, 0, count * size);
  30281. } else {
  30282. gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataArray);
  30283. }
  30284. };
  30285. return buffer;
  30286. }
  30287. /**
  30288. * Creates a buffer of 3x3 matrix data for use as attribute data.
  30289. * @param {WebGLRenderingContext} gl
  30290. */
  30291. function create3x3MatrixBufferDynamicDraw(gl, instances, attributeLoc) {
  30292. var matrixSize = 9; // 3x3 matrix
  30293. var matrixData = new Float32Array(instances * matrixSize);
  30294. // use matrix views to set values directly into the matrixData array
  30295. var matrixViews = new Array(instances);
  30296. for (var i = 0; i < instances; i++) {
  30297. var byteOffset = i * matrixSize * 4; // 4 bytes per float
  30298. matrixViews[i] = new Float32Array(matrixData.buffer, byteOffset, matrixSize); // array view
  30299. }
  30300. var buffer = gl.createBuffer();
  30301. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30302. gl.bufferData(gl.ARRAY_BUFFER, matrixData.byteLength, gl.DYNAMIC_DRAW);
  30303. // each row of the matrix needs to be a separate attribute
  30304. for (var _i = 0; _i < 3; _i++) {
  30305. var loc = attributeLoc + _i;
  30306. gl.enableVertexAttribArray(loc);
  30307. gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 3 * 12, _i * 12);
  30308. gl.vertexAttribDivisor(loc, 1);
  30309. }
  30310. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  30311. buffer.getMatrixView = function (i) {
  30312. return matrixViews[i];
  30313. };
  30314. // TODO this is too slow, use getMatrixView and pass the view directly to the glmatrix library
  30315. buffer.setData = function (matrix, i) {
  30316. matrixViews[i].set(matrix, 0);
  30317. };
  30318. buffer.bufferSubData = function () {
  30319. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  30320. gl.bufferSubData(gl.ARRAY_BUFFER, 0, matrixData);
  30321. };
  30322. return buffer;
  30323. }
  30324. /**
  30325. * Creates a Frame Buffer to use for offscreen rendering.
  30326. * @param {WebGLRenderingContext} gl
  30327. */
  30328. function createPickingFrameBuffer(gl) {
  30329. // Create and bind the framebuffer
  30330. var fb = gl.createFramebuffer();
  30331. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  30332. // Create a texture to render to
  30333. var targetTexture = gl.createTexture();
  30334. gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  30335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  30336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  30337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  30338. // attach the texture as the first color attachment
  30339. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, targetTexture, 0);
  30340. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  30341. fb.setFramebufferAttachmentSizes = function (width, height) {
  30342. gl.bindTexture(gl.TEXTURE_2D, targetTexture);
  30343. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  30344. };
  30345. return fb;
  30346. }
  30347. /**
  30348. * Common utilities
  30349. * @module glMatrix
  30350. */
  30351. // Configuration Constants
  30352. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  30353. if (!Math.hypot) Math.hypot = function () {
  30354. var y = 0,
  30355. i = arguments.length;
  30356. while (i--) {
  30357. y += arguments[i] * arguments[i];
  30358. }
  30359. return Math.sqrt(y);
  30360. };
  30361. /**
  30362. * 3x3 Matrix
  30363. * @module mat3
  30364. */
  30365. /**
  30366. * Creates a new identity mat3
  30367. *
  30368. * @returns {mat3} a new 3x3 matrix
  30369. */
  30370. function create() {
  30371. var out = new ARRAY_TYPE(9);
  30372. if (ARRAY_TYPE != Float32Array) {
  30373. out[1] = 0;
  30374. out[2] = 0;
  30375. out[3] = 0;
  30376. out[5] = 0;
  30377. out[6] = 0;
  30378. out[7] = 0;
  30379. }
  30380. out[0] = 1;
  30381. out[4] = 1;
  30382. out[8] = 1;
  30383. return out;
  30384. }
  30385. /**
  30386. * Set a mat3 to the identity matrix
  30387. *
  30388. * @param {mat3} out the receiving matrix
  30389. * @returns {mat3} out
  30390. */
  30391. function identity(out) {
  30392. out[0] = 1;
  30393. out[1] = 0;
  30394. out[2] = 0;
  30395. out[3] = 0;
  30396. out[4] = 1;
  30397. out[5] = 0;
  30398. out[6] = 0;
  30399. out[7] = 0;
  30400. out[8] = 1;
  30401. return out;
  30402. }
  30403. /**
  30404. * Multiplies two mat3's
  30405. *
  30406. * @param {mat3} out the receiving matrix
  30407. * @param {ReadonlyMat3} a the first operand
  30408. * @param {ReadonlyMat3} b the second operand
  30409. * @returns {mat3} out
  30410. */
  30411. function multiply(out, a, b) {
  30412. var a00 = a[0],
  30413. a01 = a[1],
  30414. a02 = a[2];
  30415. var a10 = a[3],
  30416. a11 = a[4],
  30417. a12 = a[5];
  30418. var a20 = a[6],
  30419. a21 = a[7],
  30420. a22 = a[8];
  30421. var b00 = b[0],
  30422. b01 = b[1],
  30423. b02 = b[2];
  30424. var b10 = b[3],
  30425. b11 = b[4],
  30426. b12 = b[5];
  30427. var b20 = b[6],
  30428. b21 = b[7],
  30429. b22 = b[8];
  30430. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  30431. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  30432. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  30433. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  30434. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  30435. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  30436. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  30437. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  30438. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  30439. return out;
  30440. }
  30441. /**
  30442. * Translate a mat3 by the given vector
  30443. *
  30444. * @param {mat3} out the receiving matrix
  30445. * @param {ReadonlyMat3} a the matrix to translate
  30446. * @param {ReadonlyVec2} v vector to translate by
  30447. * @returns {mat3} out
  30448. */
  30449. function translate(out, a, v) {
  30450. var a00 = a[0],
  30451. a01 = a[1],
  30452. a02 = a[2],
  30453. a10 = a[3],
  30454. a11 = a[4],
  30455. a12 = a[5],
  30456. a20 = a[6],
  30457. a21 = a[7],
  30458. a22 = a[8],
  30459. x = v[0],
  30460. y = v[1];
  30461. out[0] = a00;
  30462. out[1] = a01;
  30463. out[2] = a02;
  30464. out[3] = a10;
  30465. out[4] = a11;
  30466. out[5] = a12;
  30467. out[6] = x * a00 + y * a10 + a20;
  30468. out[7] = x * a01 + y * a11 + a21;
  30469. out[8] = x * a02 + y * a12 + a22;
  30470. return out;
  30471. }
  30472. /**
  30473. * Rotates a mat3 by the given angle
  30474. *
  30475. * @param {mat3} out the receiving matrix
  30476. * @param {ReadonlyMat3} a the matrix to rotate
  30477. * @param {Number} rad the angle to rotate the matrix by
  30478. * @returns {mat3} out
  30479. */
  30480. function rotate(out, a, rad) {
  30481. var a00 = a[0],
  30482. a01 = a[1],
  30483. a02 = a[2],
  30484. a10 = a[3],
  30485. a11 = a[4],
  30486. a12 = a[5],
  30487. a20 = a[6],
  30488. a21 = a[7],
  30489. a22 = a[8],
  30490. s = Math.sin(rad),
  30491. c = Math.cos(rad);
  30492. out[0] = c * a00 + s * a10;
  30493. out[1] = c * a01 + s * a11;
  30494. out[2] = c * a02 + s * a12;
  30495. out[3] = c * a10 - s * a00;
  30496. out[4] = c * a11 - s * a01;
  30497. out[5] = c * a12 - s * a02;
  30498. out[6] = a20;
  30499. out[7] = a21;
  30500. out[8] = a22;
  30501. return out;
  30502. }
  30503. /**
  30504. * Scales the mat3 by the dimensions in the given vec2
  30505. *
  30506. * @param {mat3} out the receiving matrix
  30507. * @param {ReadonlyMat3} a the matrix to rotate
  30508. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  30509. * @returns {mat3} out
  30510. **/
  30511. function scale(out, a, v) {
  30512. var x = v[0],
  30513. y = v[1];
  30514. out[0] = x * a[0];
  30515. out[1] = x * a[1];
  30516. out[2] = x * a[2];
  30517. out[3] = y * a[3];
  30518. out[4] = y * a[4];
  30519. out[5] = y * a[5];
  30520. out[6] = a[6];
  30521. out[7] = a[7];
  30522. out[8] = a[8];
  30523. return out;
  30524. }
  30525. /**
  30526. * Generates a 2D projection matrix with the given bounds
  30527. *
  30528. * @param {mat3} out mat3 frustum matrix will be written into
  30529. * @param {number} width Width of your gl context
  30530. * @param {number} height Height of gl context
  30531. * @returns {mat3} out
  30532. */
  30533. function projection(out, width, height) {
  30534. out[0] = 2 / width;
  30535. out[1] = 0;
  30536. out[2] = 0;
  30537. out[3] = 0;
  30538. out[4] = -2 / height;
  30539. out[5] = 0;
  30540. out[6] = -1;
  30541. out[7] = 1;
  30542. out[8] = 1;
  30543. return out;
  30544. }
  30545. // A "texture atlas" is a big canvas, and sections of it are used as textures for nodes/labels.
  30546. /**
  30547. * A single square texture atlas (also known as a "sprite sheet").
  30548. */
  30549. var Atlas = /*#__PURE__*/function () {
  30550. function Atlas(r, texSize, texRows, createTextureCanvas) {
  30551. _classCallCheck(this, Atlas);
  30552. this.debugID = Math.floor(Math.random() * 10000);
  30553. this.r = r;
  30554. this.texSize = texSize;
  30555. this.texRows = texRows;
  30556. this.texHeight = Math.floor(texSize / texRows);
  30557. this.enableWrapping = true; // hardcoded for now, can be made an option
  30558. this.locked = false; // once an atlas is locked it can no longer be drawn to
  30559. this.texture = null; // WebGLTexture object
  30560. this.needsBuffer = true;
  30561. // a "location" is an pointer into the atlas with a 'row' and 'x' fields
  30562. this.freePointer = {
  30563. x: 0,
  30564. row: 0
  30565. };
  30566. // map from the style key to the row/x where the texture starts
  30567. // if the texture wraps then there's a second location
  30568. this.keyToLocation = new Map(); // styleKey -> [ location, location ]
  30569. this.canvas = createTextureCanvas(r, texSize, texSize);
  30570. this.scratch = createTextureCanvas(r, texSize, this.texHeight, 'scratch');
  30571. }
  30572. return _createClass(Atlas, [{
  30573. key: "lock",
  30574. value: function lock() {
  30575. this.locked = true;
  30576. }
  30577. }, {
  30578. key: "getKeys",
  30579. value: function getKeys() {
  30580. return new Set(this.keyToLocation.keys());
  30581. }
  30582. }, {
  30583. key: "getScale",
  30584. value: function getScale(_ref) {
  30585. var w = _ref.w,
  30586. h = _ref.h;
  30587. var texHeight = this.texHeight,
  30588. maxTexWidth = this.texSize;
  30589. // try to fit to the height of a row
  30590. var scale = texHeight / h; // TODO what about pixelRatio?
  30591. var texW = w * scale;
  30592. var texH = h * scale;
  30593. // if the scaled width is too wide then scale to fit max width instead
  30594. if (texW > maxTexWidth) {
  30595. scale = maxTexWidth / w;
  30596. texW = w * scale;
  30597. texH = h * scale;
  30598. }
  30599. return {
  30600. scale: scale,
  30601. texW: texW,
  30602. texH: texH
  30603. };
  30604. }
  30605. }, {
  30606. key: "draw",
  30607. value: function draw(key, bb, doDrawing) {
  30608. var _this = this;
  30609. if (this.locked) throw new Error('can\'t draw, atlas is locked');
  30610. var texSize = this.texSize,
  30611. texRows = this.texRows,
  30612. texHeight = this.texHeight;
  30613. var _this$getScale = this.getScale(bb),
  30614. scale = _this$getScale.scale,
  30615. texW = _this$getScale.texW,
  30616. texH = _this$getScale.texH;
  30617. var drawAt = function drawAt(location, canvas) {
  30618. if (doDrawing && canvas) {
  30619. var context = canvas.context;
  30620. var x = location.x,
  30621. row = location.row;
  30622. var xOffset = x;
  30623. var yOffset = texHeight * row;
  30624. context.save();
  30625. context.translate(xOffset, yOffset);
  30626. context.scale(scale, scale);
  30627. doDrawing(context, bb);
  30628. context.restore();
  30629. }
  30630. };
  30631. var locations = [null, null];
  30632. var drawNormal = function drawNormal() {
  30633. // don't need to wrap, draw directly on the canvas
  30634. drawAt(_this.freePointer, _this.canvas);
  30635. locations[0] = {
  30636. x: _this.freePointer.x,
  30637. y: _this.freePointer.row * texHeight,
  30638. w: texW,
  30639. h: texH
  30640. };
  30641. locations[1] = {
  30642. // create a second location with a width of 0, for convenience
  30643. x: _this.freePointer.x + texW,
  30644. y: _this.freePointer.row * texHeight,
  30645. w: 0,
  30646. h: texH
  30647. };
  30648. // move the pointer to the end of the texture
  30649. _this.freePointer.x += texW;
  30650. if (_this.freePointer.x == texSize) {
  30651. _this.freePointer.x = 0;
  30652. _this.freePointer.row++;
  30653. }
  30654. };
  30655. var drawWrapped = function drawWrapped() {
  30656. var scratch = _this.scratch,
  30657. canvas = _this.canvas;
  30658. // Draw to the scratch canvas
  30659. scratch.clear();
  30660. drawAt({
  30661. x: 0,
  30662. row: 0
  30663. }, scratch);
  30664. var firstTexW = texSize - _this.freePointer.x;
  30665. var secondTexW = texW - firstTexW;
  30666. var h = texHeight;
  30667. {
  30668. // copy first part of scratch to the first texture
  30669. var dx = _this.freePointer.x;
  30670. var dy = _this.freePointer.row * texHeight;
  30671. var w = firstTexW;
  30672. canvas.context.drawImage(scratch, 0, 0, w, h, dx, dy, w, h);
  30673. locations[0] = {
  30674. x: dx,
  30675. y: dy,
  30676. w: w,
  30677. h: texH
  30678. };
  30679. }
  30680. {
  30681. // copy second part of scratch to the second texture
  30682. var sx = firstTexW;
  30683. var _dy = (_this.freePointer.row + 1) * texHeight;
  30684. var _w = secondTexW;
  30685. if (canvas) {
  30686. canvas.context.drawImage(scratch, sx, 0, _w, h, 0, _dy, _w, h);
  30687. }
  30688. locations[1] = {
  30689. x: 0,
  30690. y: _dy,
  30691. w: _w,
  30692. h: texH
  30693. };
  30694. }
  30695. _this.freePointer.x = secondTexW;
  30696. _this.freePointer.row++;
  30697. };
  30698. var moveToStartOfNextRow = function moveToStartOfNextRow() {
  30699. _this.freePointer.x = 0;
  30700. _this.freePointer.row++;
  30701. };
  30702. if (this.freePointer.x + texW <= texSize) {
  30703. // There's enough space in the current row
  30704. drawNormal();
  30705. } else if (this.freePointer.row >= texRows - 1) {
  30706. // Need to move to the next row, but there are no more rows, atlas is full.
  30707. return false;
  30708. } else if (this.freePointer.x === texSize) {
  30709. // happen to be right at end of current row
  30710. moveToStartOfNextRow();
  30711. drawNormal();
  30712. } else if (this.enableWrapping) {
  30713. // draw part of the texture to the end of the curent row, then wrap to the next row
  30714. drawWrapped();
  30715. } else {
  30716. // move to the start of the next row, then draw normally
  30717. moveToStartOfNextRow();
  30718. drawNormal();
  30719. }
  30720. this.keyToLocation.set(key, locations);
  30721. this.needsBuffer = true;
  30722. return locations;
  30723. }
  30724. }, {
  30725. key: "getOffsets",
  30726. value: function getOffsets(key) {
  30727. return this.keyToLocation.get(key);
  30728. }
  30729. }, {
  30730. key: "isEmpty",
  30731. value: function isEmpty() {
  30732. return this.freePointer.x === 0 && this.freePointer.row === 0;
  30733. }
  30734. }, {
  30735. key: "canFit",
  30736. value: function canFit(bb) {
  30737. if (this.locked) return false;
  30738. var texSize = this.texSize,
  30739. texRows = this.texRows;
  30740. var _this$getScale2 = this.getScale(bb),
  30741. texW = _this$getScale2.texW;
  30742. if (this.freePointer.x + texW > texSize) {
  30743. // need to wrap
  30744. return this.freePointer.row < texRows - 1; // return true if there's a row to wrap to
  30745. }
  30746. return true;
  30747. }
  30748. // called on every frame
  30749. }, {
  30750. key: "bufferIfNeeded",
  30751. value: function bufferIfNeeded(gl) {
  30752. if (!this.texture) {
  30753. this.texture = createTexture(gl, this.debugID);
  30754. }
  30755. if (this.needsBuffer) {
  30756. this.texture.buffer(this.canvas);
  30757. this.needsBuffer = false;
  30758. if (this.locked) {
  30759. this.canvas = null;
  30760. this.scratch = null;
  30761. }
  30762. }
  30763. }
  30764. }, {
  30765. key: "dispose",
  30766. value: function dispose() {
  30767. if (this.texture) {
  30768. this.texture.deleteTexture();
  30769. this.texture = null;
  30770. }
  30771. this.canvas = null;
  30772. this.scratch = null;
  30773. this.locked = true;
  30774. }
  30775. }]);
  30776. }();
  30777. /**
  30778. * A collection of texture atlases, all of the same "render type".
  30779. * ('node-body' is an example of a render type.)
  30780. * An AtlasCollection can also be notified when a texture is no longer needed,
  30781. * and it can garbage collect the unused textures.
  30782. */
  30783. var AtlasCollection = /*#__PURE__*/function () {
  30784. function AtlasCollection(r, texSize, texRows, createTextureCanvas) {
  30785. _classCallCheck(this, AtlasCollection);
  30786. this.r = r;
  30787. this.texSize = texSize;
  30788. this.texRows = texRows;
  30789. this.createTextureCanvas = createTextureCanvas;
  30790. this.atlases = [];
  30791. this.styleKeyToAtlas = new Map();
  30792. this.markedKeys = new Set(); // marked for garbage collection
  30793. }
  30794. return _createClass(AtlasCollection, [{
  30795. key: "getKeys",
  30796. value: function getKeys() {
  30797. return new Set(this.styleKeyToAtlas.keys());
  30798. }
  30799. }, {
  30800. key: "_createAtlas",
  30801. value: function _createAtlas() {
  30802. var r = this.r,
  30803. texSize = this.texSize,
  30804. texRows = this.texRows,
  30805. createTextureCanvas = this.createTextureCanvas;
  30806. return new Atlas(r, texSize, texRows, createTextureCanvas);
  30807. }
  30808. }, {
  30809. key: "_getScratchCanvas",
  30810. value: function _getScratchCanvas() {
  30811. if (!this.scratch) {
  30812. var r = this.r,
  30813. texSize = this.texSize,
  30814. texRows = this.texRows,
  30815. createTextureCanvas = this.createTextureCanvas;
  30816. var texHeight = Math.floor(texSize / texRows);
  30817. this.scratch = createTextureCanvas(r, texSize, texHeight, 'scratch');
  30818. }
  30819. return this.scratch;
  30820. }
  30821. }, {
  30822. key: "draw",
  30823. value: function draw(key, bb, doDrawing) {
  30824. var atlas = this.styleKeyToAtlas.get(key);
  30825. if (!atlas) {
  30826. // check for space at the end of the last atlas
  30827. atlas = this.atlases[this.atlases.length - 1];
  30828. if (!atlas || !atlas.canFit(bb)) {
  30829. if (atlas) atlas.lock();
  30830. // create a new atlas
  30831. atlas = this._createAtlas();
  30832. this.atlases.push(atlas);
  30833. }
  30834. atlas.draw(key, bb, doDrawing);
  30835. this.styleKeyToAtlas.set(key, atlas);
  30836. }
  30837. return atlas;
  30838. }
  30839. }, {
  30840. key: "getAtlas",
  30841. value: function getAtlas(key) {
  30842. return this.styleKeyToAtlas.get(key);
  30843. }
  30844. }, {
  30845. key: "hasAtlas",
  30846. value: function hasAtlas(key) {
  30847. return this.styleKeyToAtlas.has(key);
  30848. }
  30849. }, {
  30850. key: "markKeyForGC",
  30851. value: function markKeyForGC(key) {
  30852. this.markedKeys.add(key);
  30853. }
  30854. }, {
  30855. key: "gc",
  30856. value: function gc() {
  30857. var _this2 = this;
  30858. var markedKeys = this.markedKeys;
  30859. if (markedKeys.size === 0) {
  30860. console.log('nothing to garbage collect');
  30861. return;
  30862. }
  30863. var newAtlases = [];
  30864. var newStyleKeyToAtlas = new Map();
  30865. var newAtlas = null;
  30866. var _iterator = _createForOfIteratorHelper(this.atlases),
  30867. _step;
  30868. try {
  30869. var _loop = function _loop() {
  30870. var atlas = _step.value;
  30871. var keys = atlas.getKeys();
  30872. var keysToCollect = intersection(markedKeys, keys);
  30873. if (keysToCollect.size === 0) {
  30874. // this atlas can still be used
  30875. newAtlases.push(atlas);
  30876. keys.forEach(function (k) {
  30877. return newStyleKeyToAtlas.set(k, atlas);
  30878. });
  30879. return 1; // continue
  30880. }
  30881. if (!newAtlas) {
  30882. newAtlas = _this2._createAtlas();
  30883. newAtlases.push(newAtlas);
  30884. }
  30885. var _iterator2 = _createForOfIteratorHelper(keys),
  30886. _step2;
  30887. try {
  30888. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  30889. var key = _step2.value;
  30890. if (!keysToCollect.has(key)) {
  30891. var _atlas$getOffsets = atlas.getOffsets(key),
  30892. _atlas$getOffsets2 = _slicedToArray(_atlas$getOffsets, 2),
  30893. s1 = _atlas$getOffsets2[0],
  30894. s2 = _atlas$getOffsets2[1];
  30895. if (!newAtlas.canFit({
  30896. w: s1.w + s2.w,
  30897. h: s1.h
  30898. })) {
  30899. newAtlas.lock();
  30900. newAtlas = _this2._createAtlas();
  30901. newAtlases.push(newAtlas);
  30902. }
  30903. if (atlas.canvas) {
  30904. // if the texture can't be copied then it will have to be redrawn on the next frame
  30905. _this2._copyTextureToNewAtlas(key, atlas, newAtlas);
  30906. newStyleKeyToAtlas.set(key, newAtlas);
  30907. }
  30908. }
  30909. }
  30910. } catch (err) {
  30911. _iterator2.e(err);
  30912. } finally {
  30913. _iterator2.f();
  30914. }
  30915. atlas.dispose();
  30916. };
  30917. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  30918. if (_loop()) continue;
  30919. }
  30920. } catch (err) {
  30921. _iterator.e(err);
  30922. } finally {
  30923. _iterator.f();
  30924. }
  30925. this.atlases = newAtlases;
  30926. this.styleKeyToAtlas = newStyleKeyToAtlas;
  30927. this.markedKeys = new Set();
  30928. }
  30929. }, {
  30930. key: "_copyTextureToNewAtlas",
  30931. value: function _copyTextureToNewAtlas(key, oldAtlas, newAtlas) {
  30932. var _oldAtlas$getOffsets = oldAtlas.getOffsets(key),
  30933. _oldAtlas$getOffsets2 = _slicedToArray(_oldAtlas$getOffsets, 2),
  30934. s1 = _oldAtlas$getOffsets2[0],
  30935. s2 = _oldAtlas$getOffsets2[1];
  30936. if (s2.w === 0) {
  30937. // the texture does not wrap, draw directly to new atlas
  30938. newAtlas.draw(key, s1, function (context) {
  30939. context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
  30940. });
  30941. } else {
  30942. // the texture wraps, first draw both parts to a scratch canvas
  30943. var scratch = this._getScratchCanvas();
  30944. scratch.clear();
  30945. scratch.context.drawImage(oldAtlas.canvas, s1.x, s1.y, s1.w, s1.h, 0, 0, s1.w, s1.h);
  30946. scratch.context.drawImage(oldAtlas.canvas, s2.x, s2.y, s2.w, s2.h, s1.w, 0, s2.w, s2.h);
  30947. // now draw the scratch to the new atlas
  30948. var w = s1.w + s2.w;
  30949. var h = s1.h;
  30950. newAtlas.draw(key, {
  30951. w: w,
  30952. h: h
  30953. }, function (context) {
  30954. context.drawImage(scratch, 0, 0, w, h, 0, 0, w, h // the destination context has already been translated to the correct position
  30955. );
  30956. });
  30957. }
  30958. }
  30959. }, {
  30960. key: "getCounts",
  30961. value: function getCounts() {
  30962. return {
  30963. keyCount: this.styleKeyToAtlas.size,
  30964. atlasCount: new Set(this.styleKeyToAtlas.values()).size
  30965. };
  30966. }
  30967. }]);
  30968. }();
  30969. function intersection(set1, set2) {
  30970. // TODO why no Set.intersection in node 16???
  30971. if (set1.intersection) return set1.intersection(set2);else return new Set(_toConsumableArray(set1).filter(function (x) {
  30972. return set2.has(x);
  30973. }));
  30974. }
  30975. /**
  30976. * Used to manage batches of Atlases for drawing nodes and labels.
  30977. * Supports different types of AtlasCollections for different render types,
  30978. * for example 'node-body' and 'node-label' would be different render types.
  30979. * Render types are kept separate because they will likely need to be garbage collected
  30980. * separately and its not entierly guaranteed that their style keys won't collide.
  30981. */
  30982. var AtlasManager = /*#__PURE__*/function () {
  30983. function AtlasManager(r, globalOptions) {
  30984. _classCallCheck(this, AtlasManager);
  30985. this.r = r;
  30986. this.globalOptions = globalOptions;
  30987. this.atlasSize = globalOptions.webglTexSize;
  30988. this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
  30989. this.renderTypes = new Map(); // renderType:string -> renderTypeOptions
  30990. this.collections = new Map(); // collectionName:string -> AtlasCollection
  30991. this.typeAndIdToKey = new Map(); // [renderType,id] => Array<style key>
  30992. }
  30993. return _createClass(AtlasManager, [{
  30994. key: "getAtlasSize",
  30995. value: function getAtlasSize() {
  30996. return this.atlasSize;
  30997. }
  30998. }, {
  30999. key: "addAtlasCollection",
  31000. value: function addAtlasCollection(collectionName, atlasCollectionOptions) {
  31001. var _this$globalOptions = this.globalOptions,
  31002. webglTexSize = _this$globalOptions.webglTexSize,
  31003. createTextureCanvas = _this$globalOptions.createTextureCanvas;
  31004. var texRows = atlasCollectionOptions.texRows;
  31005. var cachedCreateTextureCanvas = this._cacheScratchCanvas(createTextureCanvas);
  31006. var atlasCollection = new AtlasCollection(this.r, webglTexSize, texRows, cachedCreateTextureCanvas);
  31007. this.collections.set(collectionName, atlasCollection);
  31008. }
  31009. }, {
  31010. key: "addRenderType",
  31011. value: function addRenderType(type, renderTypeOptions) {
  31012. var collection = renderTypeOptions.collection;
  31013. if (!this.collections.has(collection)) throw new Error("invalid atlas collection name '".concat(collection, "'"));
  31014. var atlasCollection = this.collections.get(collection);
  31015. var opts = extend({
  31016. type: type,
  31017. atlasCollection: atlasCollection
  31018. }, renderTypeOptions);
  31019. this.renderTypes.set(type, opts);
  31020. }
  31021. }, {
  31022. key: "getRenderTypeOpts",
  31023. value: function getRenderTypeOpts(type) {
  31024. return this.renderTypes.get(type);
  31025. }
  31026. }, {
  31027. key: "getAtlasCollection",
  31028. value: function getAtlasCollection(name) {
  31029. return this.collections.get(name);
  31030. }
  31031. }, {
  31032. key: "_cacheScratchCanvas",
  31033. value: function _cacheScratchCanvas(createTextureCanvas) {
  31034. // all scratch canvases for the same render type will have the same width and height (ie webglTexRows option)
  31035. // but we'll keep track of the width and height just to be safe
  31036. var prevW = -1;
  31037. var prevH = -1;
  31038. var scratchCanvas = null;
  31039. return function (r, w, h, scratch) {
  31040. if (scratch) {
  31041. if (!scratchCanvas || w != prevW || h != prevH) {
  31042. prevW = w;
  31043. prevH = h;
  31044. scratchCanvas = createTextureCanvas(r, w, h);
  31045. }
  31046. return scratchCanvas;
  31047. } else {
  31048. return createTextureCanvas(r, w, h);
  31049. }
  31050. };
  31051. }
  31052. }, {
  31053. key: "_key",
  31054. value: function _key(renderType, id) {
  31055. return "".concat(renderType, "-").concat(id); // TODO not very efficient
  31056. }
  31057. /** Marks textues associated with the element for garbage collection. */
  31058. }, {
  31059. key: "invalidate",
  31060. value: function invalidate(eles) {
  31061. var _this3 = this;
  31062. var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  31063. _ref2$forceRedraw = _ref2.forceRedraw,
  31064. forceRedraw = _ref2$forceRedraw === undefined ? false : _ref2$forceRedraw,
  31065. _ref2$filterEle = _ref2.filterEle,
  31066. filterEle = _ref2$filterEle === undefined ? function () {
  31067. return true;
  31068. } : _ref2$filterEle,
  31069. _ref2$filterType = _ref2.filterType,
  31070. filterType = _ref2$filterType === undefined ? function () {
  31071. return true;
  31072. } : _ref2$filterType;
  31073. var needGC = false;
  31074. var runGCNow = false;
  31075. var _iterator3 = _createForOfIteratorHelper(eles),
  31076. _step3;
  31077. try {
  31078. for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
  31079. var ele = _step3.value;
  31080. if (filterEle(ele)) {
  31081. var _iterator4 = _createForOfIteratorHelper(this.renderTypes.values()),
  31082. _step4;
  31083. try {
  31084. var _loop2 = function _loop2() {
  31085. var opts = _step4.value;
  31086. var renderType = opts.type;
  31087. if (filterType(renderType)) {
  31088. var atlasCollection = _this3.collections.get(opts.collection);
  31089. var key = opts.getKey(ele);
  31090. var keyArray = Array.isArray(key) ? key : [key];
  31091. // when a node's background image finishes loading, the style key doesn't change but still needs to be redrawn
  31092. if (forceRedraw) {
  31093. keyArray.forEach(function (key) {
  31094. return atlasCollection.markKeyForGC(key);
  31095. });
  31096. runGCNow = true; // run GC to remove the old texture right now, that way we don't need to remember for the next gc
  31097. } else {
  31098. var id = opts.getID ? opts.getID(ele) : ele.id();
  31099. var mapKey = _this3._key(renderType, id);
  31100. var oldKeyArray = _this3.typeAndIdToKey.get(mapKey);
  31101. if (oldKeyArray !== undefined && !arrayEqual(keyArray, oldKeyArray)) {
  31102. // conservative approach, if any of the keys don't match then throw them all away
  31103. needGC = true;
  31104. _this3.typeAndIdToKey["delete"](mapKey);
  31105. oldKeyArray.forEach(function (oldKey) {
  31106. return atlasCollection.markKeyForGC(oldKey);
  31107. });
  31108. }
  31109. }
  31110. }
  31111. };
  31112. for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
  31113. _loop2();
  31114. }
  31115. } catch (err) {
  31116. _iterator4.e(err);
  31117. } finally {
  31118. _iterator4.f();
  31119. }
  31120. }
  31121. }
  31122. } catch (err) {
  31123. _iterator3.e(err);
  31124. } finally {
  31125. _iterator3.f();
  31126. }
  31127. if (runGCNow) {
  31128. this.gc();
  31129. needGC = false;
  31130. }
  31131. return needGC;
  31132. }
  31133. /** Garbage collect */
  31134. }, {
  31135. key: "gc",
  31136. value: function gc() {
  31137. var _iterator5 = _createForOfIteratorHelper(this.collections.values()),
  31138. _step5;
  31139. try {
  31140. for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
  31141. var collection = _step5.value;
  31142. collection.gc();
  31143. }
  31144. } catch (err) {
  31145. _iterator5.e(err);
  31146. } finally {
  31147. _iterator5.f();
  31148. }
  31149. }
  31150. }, {
  31151. key: "getOrCreateAtlas",
  31152. value: function getOrCreateAtlas(ele, type, bb, styleKey) {
  31153. // styleKey is not an array here
  31154. var opts = this.renderTypes.get(type);
  31155. var atlasCollection = this.collections.get(opts.collection);
  31156. // draws the texture only if needed
  31157. var drawn = false;
  31158. var atlas = atlasCollection.draw(styleKey, bb, function (context) {
  31159. if (opts.drawClipped) {
  31160. context.save();
  31161. context.beginPath();
  31162. context.rect(0, 0, bb.w, bb.h);
  31163. context.clip();
  31164. opts.drawElement(context, ele, bb, true, true);
  31165. context.restore();
  31166. } else {
  31167. opts.drawElement(context, ele, bb, true, true);
  31168. }
  31169. drawn = true;
  31170. });
  31171. if (drawn) {
  31172. var id = opts.getID ? opts.getID(ele) : ele.id(); // for testing
  31173. var mapKey = this._key(type, id);
  31174. if (this.typeAndIdToKey.has(mapKey)) {
  31175. this.typeAndIdToKey.get(mapKey).push(styleKey);
  31176. } else {
  31177. this.typeAndIdToKey.set(mapKey, [styleKey]);
  31178. }
  31179. }
  31180. return atlas;
  31181. }
  31182. }, {
  31183. key: "getAtlasInfo",
  31184. value: function getAtlasInfo(ele, type) {
  31185. var _this4 = this;
  31186. var opts = this.renderTypes.get(type);
  31187. var key = opts.getKey(ele);
  31188. var keyArray = Array.isArray(key) ? key : [key];
  31189. return keyArray.map(function (styleKey) {
  31190. var bb = opts.getBoundingBox(ele, styleKey); // pass the key back to the getBoundingBox method
  31191. var atlas = _this4.getOrCreateAtlas(ele, type, bb, styleKey);
  31192. var _atlas$getOffsets3 = atlas.getOffsets(styleKey),
  31193. _atlas$getOffsets4 = _slicedToArray(_atlas$getOffsets3, 2),
  31194. tex1 = _atlas$getOffsets4[0],
  31195. tex2 = _atlas$getOffsets4[1];
  31196. return {
  31197. atlas: atlas,
  31198. tex: tex1,
  31199. tex1: tex1,
  31200. tex2: tex2,
  31201. bb: bb
  31202. };
  31203. });
  31204. }
  31205. }, {
  31206. key: "getDebugInfo",
  31207. value: function getDebugInfo() {
  31208. var debugInfo = [];
  31209. var _iterator6 = _createForOfIteratorHelper(this.collections),
  31210. _step6;
  31211. try {
  31212. for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
  31213. var _step6$value = _slicedToArray(_step6.value, 2),
  31214. name = _step6$value[0],
  31215. collection = _step6$value[1];
  31216. var _collection$getCounts = collection.getCounts(),
  31217. keyCount = _collection$getCounts.keyCount,
  31218. atlasCount = _collection$getCounts.atlasCount;
  31219. debugInfo.push({
  31220. type: name,
  31221. keyCount: keyCount,
  31222. atlasCount: atlasCount
  31223. });
  31224. }
  31225. } catch (err) {
  31226. _iterator6.e(err);
  31227. } finally {
  31228. _iterator6.f();
  31229. }
  31230. return debugInfo;
  31231. }
  31232. }]);
  31233. }();
  31234. var AtlasBatchManager = /*#__PURE__*/function () {
  31235. function AtlasBatchManager(globalOptions) {
  31236. _classCallCheck(this, AtlasBatchManager);
  31237. this.globalOptions = globalOptions;
  31238. this.atlasSize = globalOptions.webglTexSize;
  31239. this.maxAtlasesPerBatch = globalOptions.webglTexPerBatch;
  31240. this.batchAtlases = [];
  31241. }
  31242. return _createClass(AtlasBatchManager, [{
  31243. key: "getMaxAtlasesPerBatch",
  31244. value: function getMaxAtlasesPerBatch() {
  31245. return this.maxAtlasesPerBatch;
  31246. }
  31247. }, {
  31248. key: "getAtlasSize",
  31249. value: function getAtlasSize() {
  31250. return this.atlasSize;
  31251. }
  31252. }, {
  31253. key: "getIndexArray",
  31254. value: function getIndexArray() {
  31255. return Array.from({
  31256. length: this.maxAtlasesPerBatch
  31257. }, function (v, i) {
  31258. return i;
  31259. });
  31260. }
  31261. }, {
  31262. key: "startBatch",
  31263. value: function startBatch() {
  31264. this.batchAtlases = [];
  31265. }
  31266. }, {
  31267. key: "getAtlasCount",
  31268. value: function getAtlasCount() {
  31269. return this.batchAtlases.length;
  31270. }
  31271. }, {
  31272. key: "getAtlases",
  31273. value: function getAtlases() {
  31274. return this.batchAtlases;
  31275. }
  31276. }, {
  31277. key: "canAddToCurrentBatch",
  31278. value: function canAddToCurrentBatch(atlas) {
  31279. if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
  31280. return this.batchAtlases.includes(atlas);
  31281. }
  31282. return true; // not full
  31283. }
  31284. }, {
  31285. key: "getAtlasIndexForBatch",
  31286. value: function getAtlasIndexForBatch(atlas) {
  31287. var atlasID = this.batchAtlases.indexOf(atlas);
  31288. if (atlasID < 0) {
  31289. if (this.batchAtlases.length === this.maxAtlasesPerBatch) {
  31290. throw new Error('cannot add more atlases to batch');
  31291. }
  31292. this.batchAtlases.push(atlas);
  31293. atlasID = this.batchAtlases.length - 1;
  31294. }
  31295. return atlasID;
  31296. }
  31297. }]);
  31298. }();
  31299. // Fragment shader functions to calculate signed distance
  31300. // https://iquilezles.org/articles/distfunctions2d/
  31301. // ellipse: https://www.shadertoy.com/view/4lsXDN
  31302. /**
  31303. * param p - point
  31304. * float r - circle radius, eg 0.5 for unit circle
  31305. */
  31306. var circleSD = "\n float circleSD(vec2 p, float r) {\n return distance(vec2(0), p) - r; // signed distance\n }\n";
  31307. /**
  31308. * param p - point
  31309. * param b - b.x = half width, b.y = half height
  31310. */
  31311. 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";
  31312. /**
  31313. * param p - point
  31314. * param b - b.x = half width, b.y = half height
  31315. * param cr - vector of corner radiuses
  31316. */
  31317. 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";
  31318. /**
  31319. * param p - point
  31320. * param ab - a.x = horizontal radius, a.y = vertical radius
  31321. */
  31322. 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";
  31323. /**
  31324. * Two render modes. Each mode has its own shader program. They are almost identical, the main difference is the output.
  31325. * SCREEN: output pixel colors to the screen
  31326. * PICKING: output z-order index to an offscreen framebuffer, used to detect what's under the mouse cursor
  31327. */
  31328. var RENDER_TARGET = {
  31329. SCREEN: {
  31330. name: 'screen',
  31331. screen: true
  31332. },
  31333. PICKING: {
  31334. name: 'picking',
  31335. picking: true
  31336. }
  31337. };
  31338. /**
  31339. * Special handing for label textures in PICKING mode. See issue #3337.
  31340. */
  31341. var TEX_PICKING_MODE = {
  31342. // render the texture just like in RENDER_TARGET.SCREEN mode
  31343. IGNORE: 1,
  31344. // don't render the texture at all
  31345. USE_BB: 2 // render the bounding box as an opaque rectangle
  31346. };
  31347. // Vertex types.
  31348. // Used directly in the shaders so must be numeric.
  31349. // There is only one shader program used for an entire frame that renders all types of elements.
  31350. // There are if-else blocks in the shaders that do different things depending on the vertex type.
  31351. // This allows all elements to be rendererd in large batches without switching shader programs.
  31352. var TEXTURE = 0;
  31353. var EDGE_STRAIGHT = 1;
  31354. var EDGE_CURVE_SEGMENT = 2;
  31355. var EDGE_ARROW = 3;
  31356. var RECTANGLE = 4;
  31357. var ROUND_RECTANGLE = 5;
  31358. var BOTTOM_ROUND_RECTANGLE = 6;
  31359. var ELLIPSE = 7;
  31360. var ElementDrawingWebGL = /*#__PURE__*/function () {
  31361. /**
  31362. * @param {WebGLRenderingContext} gl
  31363. */
  31364. function ElementDrawingWebGL(r, gl, opts) {
  31365. _classCallCheck(this, ElementDrawingWebGL);
  31366. this.r = r; // reference to the canvas renderer
  31367. this.gl = gl;
  31368. this.maxInstances = opts.webglBatchSize;
  31369. this.atlasSize = opts.webglTexSize;
  31370. this.bgColor = opts.bgColor;
  31371. this.debug = opts.webglDebug;
  31372. this.batchDebugInfo = [];
  31373. opts.enableWrapping = true;
  31374. opts.createTextureCanvas = createTextureCanvas; // Unit tests mock this
  31375. this.atlasManager = new AtlasManager(r, opts);
  31376. this.batchManager = new AtlasBatchManager(opts);
  31377. this.simpleShapeOptions = new Map();
  31378. this.program = this._createShaderProgram(RENDER_TARGET.SCREEN);
  31379. this.pickingProgram = this._createShaderProgram(RENDER_TARGET.PICKING);
  31380. this.vao = this._createVAO();
  31381. }
  31382. /**
  31383. * @param { string } collectionName
  31384. * @param {{ texRows: number }} opts
  31385. */
  31386. return _createClass(ElementDrawingWebGL, [{
  31387. key: "addAtlasCollection",
  31388. value: function addAtlasCollection(collectionName, opts) {
  31389. this.atlasManager.addAtlasCollection(collectionName, opts);
  31390. }
  31391. /**
  31392. * @typedef { Object } TextureRenderTypeOpts
  31393. * @property { string } collection - name of atlas collection to render textures to
  31394. * @property { function } getKey - returns the "style key" for an element, may be a single value or an array for multi-line lables
  31395. * @property { function } drawElement - uses a canvas renderer to draw the element to the texture atlas
  31396. * @property { boolean } drawClipped - if true the context will be clipped to the bounding box before drawElement() is called, may affect performance
  31397. * @property { function } getBoundingBox - returns the bounding box for an element
  31398. * @property { function } getRotation
  31399. * @property { function } getRotationPoint
  31400. * @property { function } getRotationOffset
  31401. * @property { function } isVisible - an extra check for visibility in addition to ele.visible()
  31402. * @property { function } getTexPickingMode - returns a value from the TEX_PICKING_MODE enum
  31403. */
  31404. /**
  31405. * @param { string } typeName
  31406. * @param { TextureRenderTypeOpts } opts
  31407. */
  31408. }, {
  31409. key: "addTextureAtlasRenderType",
  31410. value: function addTextureAtlasRenderType(typeName, opts) {
  31411. this.atlasManager.addRenderType(typeName, opts);
  31412. }
  31413. /**
  31414. * @typedef { Object } SimpleShapeRenderTypeOpts
  31415. * @property { function } getBoundingBox - returns the bounding box for an element
  31416. * @property { function } isVisible - this is an extra check for visibility in addition to ele.visible()
  31417. * @property { function } isSimple - check if element is a simple shape, or if it needs to fall back to texture rendering
  31418. * @property { ShapeVisualProperties } shapeProps
  31419. */
  31420. /**
  31421. * @typedef { Object } ShapeVisualProperties
  31422. * @property { string } shape
  31423. * @property { string } color
  31424. * @property { string } opacity
  31425. * @property { string } padding
  31426. * @property { string } radius
  31427. * @property { boolean } border
  31428. */
  31429. /**
  31430. * @param { string } typeName
  31431. * @param { SimpleShapeRenderTypeOpts } opts
  31432. */
  31433. }, {
  31434. key: "addSimpleShapeRenderType",
  31435. value: function addSimpleShapeRenderType(typeName, opts) {
  31436. this.simpleShapeOptions.set(typeName, opts);
  31437. }
  31438. /**
  31439. * Inform the atlasManager when element style keys may have changed.
  31440. * The atlasManager can then mark unused textures for "garbage collection".
  31441. */
  31442. }, {
  31443. key: "invalidate",
  31444. value: function invalidate(eles) {
  31445. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  31446. type = _ref.type;
  31447. var atlasManager = this.atlasManager;
  31448. if (type) {
  31449. return atlasManager.invalidate(eles, {
  31450. filterType: function filterType(t) {
  31451. return t === type;
  31452. },
  31453. forceRedraw: true
  31454. });
  31455. } else {
  31456. return atlasManager.invalidate(eles);
  31457. }
  31458. }
  31459. /**
  31460. * Run texture garbage collection.
  31461. */
  31462. }, {
  31463. key: "gc",
  31464. value: function gc() {
  31465. this.atlasManager.gc();
  31466. }
  31467. }, {
  31468. key: "_createShaderProgram",
  31469. value: function _createShaderProgram(renderTarget) {
  31470. var gl = this.gl;
  31471. 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 ");
  31472. var idxs = this.batchManager.getIndexArray();
  31473. 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) {
  31474. return "uniform sampler2D uTexture".concat(i, ";");
  31475. }).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) {
  31476. return "if(vAtlasId == ".concat(i, ") outColor = texture(uTexture").concat(i, ", vTexCoord);");
  31477. }).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 ");
  31478. var program = createProgram(gl, vertexShaderSource, fragmentShaderSource);
  31479. // instance geometry
  31480. program.aPosition = gl.getAttribLocation(program, 'aPosition');
  31481. // attributes
  31482. program.aIndex = gl.getAttribLocation(program, 'aIndex');
  31483. program.aVertType = gl.getAttribLocation(program, 'aVertType');
  31484. program.aTransform = gl.getAttribLocation(program, 'aTransform');
  31485. program.aAtlasId = gl.getAttribLocation(program, 'aAtlasId');
  31486. program.aTex = gl.getAttribLocation(program, 'aTex');
  31487. program.aPointAPointB = gl.getAttribLocation(program, 'aPointAPointB');
  31488. program.aPointCPointD = gl.getAttribLocation(program, 'aPointCPointD');
  31489. program.aLineWidth = gl.getAttribLocation(program, 'aLineWidth');
  31490. program.aColor = gl.getAttribLocation(program, 'aColor');
  31491. program.aCornerRadius = gl.getAttribLocation(program, 'aCornerRadius');
  31492. program.aBorderColor = gl.getAttribLocation(program, 'aBorderColor');
  31493. // uniforms
  31494. program.uPanZoomMatrix = gl.getUniformLocation(program, 'uPanZoomMatrix');
  31495. program.uAtlasSize = gl.getUniformLocation(program, 'uAtlasSize');
  31496. program.uBGColor = gl.getUniformLocation(program, 'uBGColor');
  31497. program.uZoom = gl.getUniformLocation(program, 'uZoom');
  31498. program.uTextures = [];
  31499. for (var i = 0; i < this.batchManager.getMaxAtlasesPerBatch(); i++) {
  31500. program.uTextures.push(gl.getUniformLocation(program, "uTexture".concat(i)));
  31501. }
  31502. return program;
  31503. }
  31504. }, {
  31505. key: "_createVAO",
  31506. value: function _createVAO() {
  31507. var unitSquare = [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1];
  31508. this.vertexCount = unitSquare.length / 2;
  31509. var n = this.maxInstances;
  31510. var gl = this.gl,
  31511. program = this.program;
  31512. var vao = gl.createVertexArray();
  31513. gl.bindVertexArray(vao);
  31514. createBufferStaticDraw(gl, 'vec2', program.aPosition, unitSquare);
  31515. // Create buffers for all the attributes
  31516. this.transformBuffer = create3x3MatrixBufferDynamicDraw(gl, n, program.aTransform);
  31517. this.indexBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aIndex);
  31518. this.vertTypeBuffer = createBufferDynamicDraw(gl, n, 'int', program.aVertType);
  31519. this.atlasIdBuffer = createBufferDynamicDraw(gl, n, 'int', program.aAtlasId);
  31520. this.texBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aTex);
  31521. this.pointAPointBBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointAPointB);
  31522. this.pointCPointDBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aPointCPointD);
  31523. this.lineWidthBuffer = createBufferDynamicDraw(gl, n, 'vec2', program.aLineWidth);
  31524. this.colorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aColor);
  31525. this.cornerRadiusBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aCornerRadius);
  31526. this.borderColorBuffer = createBufferDynamicDraw(gl, n, 'vec4', program.aBorderColor);
  31527. gl.bindVertexArray(null);
  31528. return vao;
  31529. }
  31530. }, {
  31531. key: "buffers",
  31532. get: function get() {
  31533. var _this = this;
  31534. if (!this._buffers) {
  31535. this._buffers = Object.keys(this).filter(function (k) {
  31536. return endsWith(k, 'Buffer');
  31537. }).map(function (k) {
  31538. return _this[k];
  31539. });
  31540. }
  31541. return this._buffers;
  31542. }
  31543. }, {
  31544. key: "startFrame",
  31545. value: function startFrame(panZoomMatrix) {
  31546. var renderTarget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : RENDER_TARGET.SCREEN;
  31547. this.panZoomMatrix = panZoomMatrix;
  31548. this.renderTarget = renderTarget;
  31549. this.batchDebugInfo = [];
  31550. this.wrappedCount = 0;
  31551. this.simpleCount = 0;
  31552. this.startBatch();
  31553. }
  31554. }, {
  31555. key: "startBatch",
  31556. value: function startBatch() {
  31557. this.instanceCount = 0;
  31558. this.batchManager.startBatch();
  31559. }
  31560. }, {
  31561. key: "endFrame",
  31562. value: function endFrame() {
  31563. this.endBatch();
  31564. }
  31565. }, {
  31566. key: "_isVisible",
  31567. value: function _isVisible(ele, opts) {
  31568. if (ele.visible()) {
  31569. if (opts && opts.isVisible) {
  31570. return opts.isVisible(ele);
  31571. }
  31572. return true;
  31573. }
  31574. return false;
  31575. }
  31576. /**
  31577. * Draws a texture using the texture atlas.
  31578. */
  31579. }, {
  31580. key: "drawTexture",
  31581. value: function drawTexture(ele, eleIndex, type) {
  31582. var atlasManager = this.atlasManager,
  31583. batchManager = this.batchManager;
  31584. var opts = atlasManager.getRenderTypeOpts(type);
  31585. if (!this._isVisible(ele, opts)) {
  31586. return;
  31587. }
  31588. // Edges with invalid points could be passed here (labels), causing errors
  31589. // Ref: Random "Script Error" thrown when generating nodes and edges in newest webgl version #3365
  31590. // https://github.com/cytoscape/cytoscape.js/issues/3365
  31591. if (ele.isEdge() && !this._isValidEdge(ele)) {
  31592. return;
  31593. }
  31594. if (this.renderTarget.picking && opts.getTexPickingMode) {
  31595. var mode = opts.getTexPickingMode(ele);
  31596. if (mode === TEX_PICKING_MODE.IGNORE) {
  31597. return;
  31598. } else if (mode == TEX_PICKING_MODE.USE_BB) {
  31599. this.drawPickingRectangle(ele, eleIndex, type);
  31600. return;
  31601. }
  31602. }
  31603. // Get the atlas and the texture coordinates, will draw the texture if it hasn't been drawn yet
  31604. // May be more than one texture if for example the label has multiple lines
  31605. var atlasInfoArray = atlasManager.getAtlasInfo(ele, type);
  31606. var _iterator = _createForOfIteratorHelper(atlasInfoArray),
  31607. _step;
  31608. try {
  31609. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  31610. var atlasInfo = _step.value;
  31611. var atlas = atlasInfo.atlas,
  31612. tex1 = atlasInfo.tex1,
  31613. tex2 = atlasInfo.tex2; // tex2 is used if the label wraps and there are two textures
  31614. if (!batchManager.canAddToCurrentBatch(atlas)) {
  31615. this.endBatch();
  31616. }
  31617. var atlasIndex = batchManager.getAtlasIndexForBatch(atlas);
  31618. for (var _i = 0, _arr = [[tex1, true], [tex2, false]]; _i < _arr.length; _i++) {
  31619. var _arr$_i = _slicedToArray(_arr[_i], 2),
  31620. tex = _arr$_i[0],
  31621. first = _arr$_i[1];
  31622. if (tex.w != 0) {
  31623. var instance = this.instanceCount;
  31624. this.vertTypeBuffer.getView(instance)[0] = TEXTURE;
  31625. var indexView = this.indexBuffer.getView(instance);
  31626. indexToVec4(eleIndex, indexView);
  31627. // Set values in the buffers using Typed Array Views for performance.
  31628. var atlasIdView = this.atlasIdBuffer.getView(instance);
  31629. atlasIdView[0] = atlasIndex;
  31630. // we have two sets of texture coordinates and transforms because textures can wrap in the atlas
  31631. var texView = this.texBuffer.getView(instance);
  31632. texView[0] = tex.x;
  31633. texView[1] = tex.y;
  31634. texView[2] = tex.w;
  31635. texView[3] = tex.h;
  31636. var matrixView = this.transformBuffer.getMatrixView(instance);
  31637. this.setTransformMatrix(ele, matrixView, opts, atlasInfo, first);
  31638. this.instanceCount++;
  31639. if (!first) this.wrappedCount++;
  31640. if (this.instanceCount >= this.maxInstances) {
  31641. this.endBatch();
  31642. }
  31643. }
  31644. }
  31645. }
  31646. } catch (err) {
  31647. _iterator.e(err);
  31648. } finally {
  31649. _iterator.f();
  31650. }
  31651. }
  31652. /**
  31653. * matrix is expected to be a 9 element array
  31654. * this function follows same pattern as CRp.drawCachedElementPortion(...)
  31655. */
  31656. }, {
  31657. key: "setTransformMatrix",
  31658. value: function setTransformMatrix(ele, matrix, opts, atlasInfo) {
  31659. var first = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  31660. var padding = 0;
  31661. if (opts.shapeProps && opts.shapeProps.padding) {
  31662. padding = ele.pstyle(opts.shapeProps.padding).pfValue;
  31663. }
  31664. if (atlasInfo) {
  31665. // we've already computed the bb and tex bounds for a texture
  31666. var bb = atlasInfo.bb,
  31667. tex1 = atlasInfo.tex1,
  31668. tex2 = atlasInfo.tex2;
  31669. // wrapped textures need separate matrix for each part
  31670. var ratio = tex1.w / (tex1.w + tex2.w);
  31671. if (!first) {
  31672. // first = true means its the first part of the wrapped texture
  31673. ratio = 1 - ratio;
  31674. }
  31675. var adjBB = this._getAdjustedBB(bb, padding, first, ratio);
  31676. this._applyTransformMatrix(matrix, adjBB, opts, ele);
  31677. } else {
  31678. // we don't have a texture, or we want to avoid creating a texture for simple shapes
  31679. var _bb = opts.getBoundingBox(ele);
  31680. var _adjBB = this._getAdjustedBB(_bb, padding, true, 1);
  31681. this._applyTransformMatrix(matrix, _adjBB, opts, ele);
  31682. }
  31683. }
  31684. }, {
  31685. key: "_applyTransformMatrix",
  31686. value: function _applyTransformMatrix(matrix, adjBB, opts, ele) {
  31687. var x, y;
  31688. identity(matrix);
  31689. var theta = opts.getRotation ? opts.getRotation(ele) : 0;
  31690. if (theta !== 0) {
  31691. var _opts$getRotationPoin = opts.getRotationPoint(ele),
  31692. sx = _opts$getRotationPoin.x,
  31693. sy = _opts$getRotationPoin.y;
  31694. translate(matrix, matrix, [sx, sy]);
  31695. rotate(matrix, matrix, theta);
  31696. var offset = opts.getRotationOffset(ele);
  31697. x = offset.x + (adjBB.xOffset || 0);
  31698. y = offset.y + (adjBB.yOffset || 0);
  31699. } else {
  31700. x = adjBB.x1;
  31701. y = adjBB.y1;
  31702. }
  31703. translate(matrix, matrix, [x, y]);
  31704. scale(matrix, matrix, [adjBB.w, adjBB.h]);
  31705. }
  31706. /**
  31707. * Adjusts a node or label BB to accomodate padding and split for wrapped textures.
  31708. * @param bb - the original bounding box
  31709. * @param padding - the padding to add to the bounding box
  31710. * @param first - whether this is the first part of a wrapped texture
  31711. * @param ratio - the ratio of the texture width of part of the text to the entire texture
  31712. */
  31713. }, {
  31714. key: "_getAdjustedBB",
  31715. value: function _getAdjustedBB(bb, padding, first, ratio) {
  31716. var x1 = bb.x1,
  31717. y1 = bb.y1,
  31718. w = bb.w,
  31719. h = bb.h,
  31720. yOffset = bb.yOffset;
  31721. if (padding) {
  31722. x1 -= padding;
  31723. y1 -= padding;
  31724. w += 2 * padding;
  31725. h += 2 * padding;
  31726. }
  31727. var xOffset = 0;
  31728. var adjW = w * ratio;
  31729. if (first && ratio < 1) {
  31730. w = adjW;
  31731. } else if (!first && ratio < 1) {
  31732. xOffset = w - adjW;
  31733. x1 += xOffset;
  31734. w = adjW;
  31735. }
  31736. return {
  31737. x1: x1,
  31738. y1: y1,
  31739. w: w,
  31740. h: h,
  31741. xOffset: xOffset,
  31742. yOffset: yOffset
  31743. };
  31744. }
  31745. /**
  31746. * Draw a solid opaque rectangle matching the element's Bounding Box.
  31747. * Used by the PICKING mode to make the entire BB of a label clickable.
  31748. */
  31749. }, {
  31750. key: "drawPickingRectangle",
  31751. value: function drawPickingRectangle(ele, eleIndex, type) {
  31752. var opts = this.atlasManager.getRenderTypeOpts(type);
  31753. var instance = this.instanceCount;
  31754. this.vertTypeBuffer.getView(instance)[0] = RECTANGLE;
  31755. var indexView = this.indexBuffer.getView(instance);
  31756. indexToVec4(eleIndex, indexView);
  31757. var colorView = this.colorBuffer.getView(instance);
  31758. toWebGLColor([0, 0, 0], 1, colorView); // opaque, so entire label BB is clickable
  31759. var matrixView = this.transformBuffer.getMatrixView(instance);
  31760. this.setTransformMatrix(ele, matrixView, opts);
  31761. this.simpleCount++;
  31762. this.instanceCount++;
  31763. if (this.instanceCount >= this.maxInstances) {
  31764. this.endBatch();
  31765. }
  31766. }
  31767. /**
  31768. * Draw a node using either a texture or a "simple shape".
  31769. */
  31770. }, {
  31771. key: "drawNode",
  31772. value: function drawNode(node, eleIndex, type) {
  31773. var opts = this.simpleShapeOptions.get(type);
  31774. if (!this._isVisible(node, opts)) {
  31775. return;
  31776. }
  31777. var props = opts.shapeProps;
  31778. // Check if we have to use a texture
  31779. var vertType = this._getVertTypeForShape(node, props.shape);
  31780. if (vertType === undefined || opts.isSimple && !opts.isSimple(node, this.renderTarget)) {
  31781. this.drawTexture(node, eleIndex, type);
  31782. return;
  31783. }
  31784. // Render a "simple shape" using SDF (signed distance fields)
  31785. var instance = this.instanceCount;
  31786. this.vertTypeBuffer.getView(instance)[0] = vertType;
  31787. if (vertType === ROUND_RECTANGLE || vertType === BOTTOM_ROUND_RECTANGLE) {
  31788. // get corner radius
  31789. var bb = opts.getBoundingBox(node);
  31790. var radius = this._getCornerRadius(node, props.radius, bb);
  31791. var radiusView = this.cornerRadiusBuffer.getView(instance);
  31792. radiusView[0] = radius; // top-right
  31793. radiusView[1] = radius; // bottom-right
  31794. radiusView[2] = radius; // top-left
  31795. radiusView[3] = radius; // bottom-left
  31796. if (vertType === BOTTOM_ROUND_RECTANGLE) {
  31797. radiusView[0] = 0;
  31798. radiusView[2] = 0;
  31799. }
  31800. }
  31801. var indexView = this.indexBuffer.getView(instance);
  31802. indexToVec4(eleIndex, indexView);
  31803. // Nodes should still be clickable if they pass the visibility check but
  31804. // have background-opacity: 0
  31805. var opacity = this.renderTarget.picking ? 1 : node.pstyle(props.opacity).value;
  31806. var color = node.pstyle(props.color).value;
  31807. var colorView = this.colorBuffer.getView(instance);
  31808. toWebGLColor(color, opacity, colorView);
  31809. var lineWidthView = this.lineWidthBuffer.getView(instance); // reuse edge line width attribute for node border
  31810. lineWidthView[0] = 0;
  31811. lineWidthView[1] = 0;
  31812. if (props.border) {
  31813. var borderWidth = node.pstyle('border-width').value;
  31814. if (borderWidth > 0) {
  31815. var borderColor = node.pstyle('border-color').value;
  31816. var borderOpacity = node.pstyle('border-opacity').value;
  31817. var borderColorView = this.borderColorBuffer.getView(instance);
  31818. toWebGLColor(borderColor, borderOpacity, borderColorView);
  31819. // SDF distance is negative inside the shape and positive outside
  31820. var borderPos = node.pstyle('border-position').value;
  31821. if (borderPos === 'inside') {
  31822. lineWidthView[0] = 0;
  31823. lineWidthView[1] = -borderWidth;
  31824. } else if (borderPos === 'outside') {
  31825. lineWidthView[0] = borderWidth;
  31826. lineWidthView[1] = 0;
  31827. } else {
  31828. // 'center'
  31829. var halfWidth = borderWidth / 2;
  31830. lineWidthView[0] = halfWidth;
  31831. lineWidthView[1] = -halfWidth;
  31832. }
  31833. }
  31834. }
  31835. var matrixView = this.transformBuffer.getMatrixView(instance);
  31836. this.setTransformMatrix(node, matrixView, opts);
  31837. this.simpleCount++;
  31838. this.instanceCount++;
  31839. if (this.instanceCount >= this.maxInstances) {
  31840. this.endBatch();
  31841. }
  31842. }
  31843. }, {
  31844. key: "_getVertTypeForShape",
  31845. value: function _getVertTypeForShape(node, shapeProp) {
  31846. var shape = node.pstyle(shapeProp).value;
  31847. switch (shape) {
  31848. case 'rectangle':
  31849. return RECTANGLE;
  31850. case 'ellipse':
  31851. return ELLIPSE;
  31852. case 'roundrectangle':
  31853. case 'round-rectangle':
  31854. return ROUND_RECTANGLE;
  31855. case 'bottom-round-rectangle':
  31856. return BOTTOM_ROUND_RECTANGLE;
  31857. default:
  31858. return undefined;
  31859. }
  31860. }
  31861. }, {
  31862. key: "_getCornerRadius",
  31863. value: function _getCornerRadius(node, radiusProp, _ref2) {
  31864. var w = _ref2.w,
  31865. h = _ref2.h;
  31866. // see CRp.drawRoundRectanglePath
  31867. if (node.pstyle(radiusProp).value === 'auto') {
  31868. return getRoundRectangleRadius(w, h);
  31869. } else {
  31870. var radius = node.pstyle(radiusProp).pfValue;
  31871. var halfWidth = w / 2;
  31872. var halfHeight = h / 2;
  31873. return Math.min(radius, halfHeight, halfWidth);
  31874. }
  31875. }
  31876. /**
  31877. * Only supports drawing triangles at the moment.
  31878. */
  31879. }, {
  31880. key: "drawEdgeArrow",
  31881. value: function drawEdgeArrow(edge, eleIndex, prefix) {
  31882. if (!edge.visible()) {
  31883. return;
  31884. }
  31885. // Edge points and arrow angles etc are calculated by the base renderer and cached in the rscratch object.
  31886. var rs = edge._private.rscratch;
  31887. var x, y, angle;
  31888. if (prefix === 'source') {
  31889. x = rs.arrowStartX;
  31890. y = rs.arrowStartY;
  31891. angle = rs.srcArrowAngle;
  31892. } else {
  31893. x = rs.arrowEndX;
  31894. y = rs.arrowEndY;
  31895. angle = rs.tgtArrowAngle;
  31896. }
  31897. // taken from CRp.drawArrowhead
  31898. if (isNaN(x) || x == null || isNaN(y) || y == null || isNaN(angle) || angle == null) {
  31899. return;
  31900. }
  31901. // check shape after the x/y check because pstyle() is a bit slow
  31902. var arrowShape = edge.pstyle(prefix + '-arrow-shape').value;
  31903. if (arrowShape === 'none') {
  31904. return;
  31905. }
  31906. var color = edge.pstyle(prefix + '-arrow-color').value;
  31907. var baseOpacity = edge.pstyle('opacity').value;
  31908. var lineOpacity = edge.pstyle('line-opacity').value;
  31909. var opacity = baseOpacity * lineOpacity;
  31910. var lineWidth = edge.pstyle('width').pfValue;
  31911. var scale$1 = edge.pstyle('arrow-scale').value;
  31912. var size = this.r.getArrowWidth(lineWidth, scale$1);
  31913. var instance = this.instanceCount;
  31914. var transform = this.transformBuffer.getMatrixView(instance);
  31915. identity(transform);
  31916. translate(transform, transform, [x, y]);
  31917. scale(transform, transform, [size, size]);
  31918. rotate(transform, transform, angle);
  31919. this.vertTypeBuffer.getView(instance)[0] = EDGE_ARROW;
  31920. var indexView = this.indexBuffer.getView(instance);
  31921. indexToVec4(eleIndex, indexView);
  31922. var colorView = this.colorBuffer.getView(instance);
  31923. toWebGLColor(color, opacity, colorView);
  31924. this.instanceCount++;
  31925. if (this.instanceCount >= this.maxInstances) {
  31926. this.endBatch();
  31927. }
  31928. }
  31929. /**
  31930. * Draw straight-line or bezier curve edges.
  31931. */
  31932. }, {
  31933. key: "drawEdgeLine",
  31934. value: function drawEdgeLine(edge, eleIndex) {
  31935. if (!edge.visible()) {
  31936. return;
  31937. }
  31938. var points = this._getEdgePoints(edge);
  31939. if (!points) {
  31940. return;
  31941. }
  31942. // line style
  31943. var baseOpacity = edge.pstyle('opacity').value;
  31944. var lineOpacity = edge.pstyle('line-opacity').value;
  31945. var width = edge.pstyle('width').pfValue;
  31946. var color = edge.pstyle('line-color').value;
  31947. var opacity = baseOpacity * lineOpacity;
  31948. if (points.length / 2 + this.instanceCount > this.maxInstances) {
  31949. this.endBatch();
  31950. }
  31951. if (points.length == 4) {
  31952. // straight line
  31953. var instance = this.instanceCount;
  31954. this.vertTypeBuffer.getView(instance)[0] = EDGE_STRAIGHT;
  31955. var indexView = this.indexBuffer.getView(instance);
  31956. indexToVec4(eleIndex, indexView);
  31957. var colorView = this.colorBuffer.getView(instance);
  31958. toWebGLColor(color, opacity, colorView);
  31959. var lineWidthBuffer = this.lineWidthBuffer.getView(instance);
  31960. lineWidthBuffer[0] = width;
  31961. var sourceTargetView = this.pointAPointBBuffer.getView(instance);
  31962. sourceTargetView[0] = points[0]; // source x
  31963. sourceTargetView[1] = points[1]; // source y
  31964. sourceTargetView[2] = points[2]; // target x
  31965. sourceTargetView[3] = points[3]; // target y
  31966. this.instanceCount++;
  31967. if (this.instanceCount >= this.maxInstances) {
  31968. this.endBatch();
  31969. }
  31970. } else {
  31971. // curved line
  31972. for (var i = 0; i < points.length - 2; i += 2) {
  31973. var _instance = this.instanceCount;
  31974. this.vertTypeBuffer.getView(_instance)[0] = EDGE_CURVE_SEGMENT;
  31975. var _indexView = this.indexBuffer.getView(_instance);
  31976. indexToVec4(eleIndex, _indexView);
  31977. var _colorView = this.colorBuffer.getView(_instance);
  31978. toWebGLColor(color, opacity, _colorView);
  31979. var _lineWidthBuffer = this.lineWidthBuffer.getView(_instance);
  31980. _lineWidthBuffer[0] = width;
  31981. var pAx = points[i - 2],
  31982. pAy = points[i - 1];
  31983. var pBx = points[i],
  31984. pBy = points[i + 1];
  31985. var pCx = points[i + 2],
  31986. pCy = points[i + 3];
  31987. var pDx = points[i + 4],
  31988. pDy = points[i + 5];
  31989. // make phantom points for the first and last segments
  31990. // TODO adding 0.001 to avoid division by zero in the shader (I think), need a better solution
  31991. if (i == 0) {
  31992. pAx = 2 * pBx - pCx + 0.001;
  31993. pAy = 2 * pBy - pCy + 0.001;
  31994. }
  31995. if (i == points.length - 4) {
  31996. pDx = 2 * pCx - pBx + 0.001;
  31997. pDy = 2 * pCy - pBy + 0.001;
  31998. }
  31999. var pointABView = this.pointAPointBBuffer.getView(_instance);
  32000. pointABView[0] = pAx;
  32001. pointABView[1] = pAy;
  32002. pointABView[2] = pBx;
  32003. pointABView[3] = pBy;
  32004. var pointCDView = this.pointCPointDBuffer.getView(_instance);
  32005. pointCDView[0] = pCx;
  32006. pointCDView[1] = pCy;
  32007. pointCDView[2] = pDx;
  32008. pointCDView[3] = pDy;
  32009. this.instanceCount++;
  32010. if (this.instanceCount >= this.maxInstances) {
  32011. this.endBatch();
  32012. }
  32013. }
  32014. }
  32015. }
  32016. }, {
  32017. key: "_isValidEdge",
  32018. value: function _isValidEdge(edge) {
  32019. var rs = edge._private.rscratch;
  32020. if (rs.badLine || rs.allpts == null || isNaN(rs.allpts[0])) {
  32021. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  32022. return false;
  32023. }
  32024. return true;
  32025. }
  32026. }, {
  32027. key: "_getEdgePoints",
  32028. value: function _getEdgePoints(edge) {
  32029. var rs = edge._private.rscratch;
  32030. // if bezier ctrl pts can not be calculated, then die
  32031. if (!this._isValidEdge(edge)) {
  32032. // isNaN in case edge is impossible and browser bugs (e.g. safari)
  32033. return;
  32034. }
  32035. var controlPoints = rs.allpts;
  32036. if (controlPoints.length == 4) {
  32037. return controlPoints;
  32038. }
  32039. var numSegments = this._getNumSegments(edge);
  32040. return this._getCurveSegmentPoints(controlPoints, numSegments);
  32041. }
  32042. }, {
  32043. key: "_getNumSegments",
  32044. value: function _getNumSegments(edge) {
  32045. // TODO Need a heuristic that decides how many segments to use. Factors to consider:
  32046. // - edge width/length
  32047. // - edge curvature (the more the curvature, the more segments)
  32048. // - zoom level (more segments when zoomed in)
  32049. // - number of visible edges (more segments when there are fewer edges)
  32050. // - performance (fewer segments when performance is a concern)
  32051. // - user configurable option(s)
  32052. // note: number of segments must be less than the max number of instances
  32053. // note: segments don't need to be evenly spaced out, it might make sense to have shorter segments nearer to the control points
  32054. var numSegments = 15;
  32055. return Math.min(Math.max(numSegments, 5), this.maxInstances);
  32056. }
  32057. }, {
  32058. key: "_getCurveSegmentPoints",
  32059. value: function _getCurveSegmentPoints(controlPoints, segments) {
  32060. if (controlPoints.length == 4) {
  32061. return controlPoints; // straight line
  32062. }
  32063. var curvePoints = Array((segments + 1) * 2);
  32064. for (var i = 0; i <= segments; i++) {
  32065. // the first and last points are the same as the first and last control points
  32066. if (i == 0) {
  32067. curvePoints[0] = controlPoints[0];
  32068. curvePoints[1] = controlPoints[1];
  32069. } else if (i == segments) {
  32070. curvePoints[i * 2] = controlPoints[controlPoints.length - 2];
  32071. curvePoints[i * 2 + 1] = controlPoints[controlPoints.length - 1];
  32072. } else {
  32073. var t = i / segments; // segments have equal length, its not strictly necessary to do it this way
  32074. // pass in curvePoints to set the values in the array directly
  32075. this._setCurvePoint(controlPoints, t, curvePoints, i * 2);
  32076. }
  32077. }
  32078. return curvePoints;
  32079. }
  32080. }, {
  32081. key: "_setCurvePoint",
  32082. value: function _setCurvePoint(points, t, curvePoints, cpi) {
  32083. if (points.length <= 2) {
  32084. curvePoints[cpi] = points[0];
  32085. curvePoints[cpi + 1] = points[1];
  32086. } else {
  32087. var newpoints = Array(points.length - 2);
  32088. for (var i = 0; i < newpoints.length; i += 2) {
  32089. var x = (1 - t) * points[i] + t * points[i + 2];
  32090. var y = (1 - t) * points[i + 1] + t * points[i + 3];
  32091. newpoints[i] = x;
  32092. newpoints[i + 1] = y;
  32093. }
  32094. return this._setCurvePoint(newpoints, t, curvePoints, cpi);
  32095. }
  32096. }
  32097. }, {
  32098. key: "endBatch",
  32099. value: function endBatch() {
  32100. var gl = this.gl,
  32101. vao = this.vao,
  32102. vertexCount = this.vertexCount,
  32103. count = this.instanceCount;
  32104. if (count === 0) return;
  32105. var program = this.renderTarget.picking ? this.pickingProgram : this.program;
  32106. gl.useProgram(program);
  32107. gl.bindVertexArray(vao);
  32108. // buffer the attribute data
  32109. var _iterator2 = _createForOfIteratorHelper(this.buffers),
  32110. _step2;
  32111. try {
  32112. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  32113. var buffer = _step2.value;
  32114. buffer.bufferSubData(count);
  32115. }
  32116. } catch (err) {
  32117. _iterator2.e(err);
  32118. } finally {
  32119. _iterator2.f();
  32120. }
  32121. var atlases = this.batchManager.getAtlases();
  32122. // must buffer before activating texture units
  32123. for (var i = 0; i < atlases.length; i++) {
  32124. atlases[i].bufferIfNeeded(gl);
  32125. }
  32126. // Activate all the texture units that we need
  32127. for (var _i2 = 0; _i2 < atlases.length; _i2++) {
  32128. gl.activeTexture(gl.TEXTURE0 + _i2);
  32129. gl.bindTexture(gl.TEXTURE_2D, atlases[_i2].texture);
  32130. gl.uniform1i(program.uTextures[_i2], _i2);
  32131. }
  32132. // Set the uniforms
  32133. gl.uniform1f(program.uZoom, getEffectiveZoom(this.r));
  32134. gl.uniformMatrix3fv(program.uPanZoomMatrix, false, this.panZoomMatrix);
  32135. gl.uniform1i(program.uAtlasSize, this.batchManager.getAtlasSize());
  32136. // set background color, needed for edge arrow color blending
  32137. var webglBgColor = toWebGLColor(this.bgColor, 1);
  32138. gl.uniform4fv(program.uBGColor, webglBgColor);
  32139. // draw!
  32140. gl.drawArraysInstanced(gl.TRIANGLES, 0, vertexCount, count);
  32141. gl.bindVertexArray(null);
  32142. gl.bindTexture(gl.TEXTURE_2D, null); // TODO is this right when having multiple texture units?
  32143. if (this.debug) {
  32144. this.batchDebugInfo.push({
  32145. count: count,
  32146. // instance count
  32147. atlasCount: atlases.length
  32148. });
  32149. }
  32150. // start the next batch, even if not needed
  32151. this.startBatch();
  32152. }
  32153. }, {
  32154. key: "getDebugInfo",
  32155. value: function getDebugInfo() {
  32156. var atlasInfo = this.atlasManager.getDebugInfo();
  32157. var totalAtlases = atlasInfo.reduce(function (count, info) {
  32158. return count + info.atlasCount;
  32159. }, 0);
  32160. var batchInfo = this.batchDebugInfo;
  32161. var totalInstances = batchInfo.reduce(function (count, info) {
  32162. return count + info.count;
  32163. }, 0);
  32164. return {
  32165. atlasInfo: atlasInfo,
  32166. totalAtlases: totalAtlases,
  32167. wrappedCount: this.wrappedCount,
  32168. simpleCount: this.simpleCount,
  32169. batchCount: batchInfo.length,
  32170. batchInfo: batchInfo,
  32171. totalInstances: totalInstances
  32172. };
  32173. }
  32174. }]);
  32175. }();
  32176. var CRp$4 = {};
  32177. /**
  32178. * Initialize the WebGL rendering mode after the Canvas renderer has been initialized.
  32179. */
  32180. CRp$4.initWebgl = function (opts, fns) {
  32181. var r = this;
  32182. var gl = r.data.contexts[r.WEBGL];
  32183. // Set defaults and limits for configuration options.
  32184. opts.bgColor = getBGColor(r);
  32185. opts.webglTexSize = Math.min(opts.webglTexSize, gl.getParameter(gl.MAX_TEXTURE_SIZE));
  32186. opts.webglTexRows = Math.min(opts.webglTexRows, 54);
  32187. opts.webglTexRowsNodes = Math.min(opts.webglTexRowsNodes, 54);
  32188. opts.webglBatchSize = Math.min(opts.webglBatchSize, 16384);
  32189. opts.webglTexPerBatch = Math.min(opts.webglTexPerBatch, gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS));
  32190. // Turn debug mode on or off.
  32191. r.webglDebug = opts.webglDebug;
  32192. r.webglDebugShowAtlases = opts.webglDebugShowAtlases;
  32193. // Create offscreen framebuffer that stores the results when RENDER_TARGET.PICKING is enabled.
  32194. // This is used to store the topmost element z-index for each pixel, which is used to tell whats under the mouse cursor point.
  32195. r.pickingFrameBuffer = createPickingFrameBuffer(gl);
  32196. r.pickingFrameBuffer.needsDraw = true;
  32197. // Create an ElementDrawingWebGL instance wich is used to do the actual WebGL rendering.
  32198. // This instance needs to be configured to draw various types of elements.
  32199. r.drawing = new ElementDrawingWebGL(r, gl, opts);
  32200. // Some functions that are used to configure ElementDrawingWebGL
  32201. var getLabelRotation = function getLabelRotation(prop) {
  32202. return function (ele) {
  32203. return r.getTextAngle(ele, prop);
  32204. };
  32205. };
  32206. var isLabelVisible = function isLabelVisible(prop) {
  32207. return function (ele) {
  32208. var label = ele.pstyle(prop);
  32209. return label && label.value;
  32210. };
  32211. };
  32212. var isLayerVisible = function isLayerVisible(prefix) {
  32213. return function (node) {
  32214. // prefix is 'overlay' or 'underlay'
  32215. return node.pstyle("".concat(prefix, "-opacity")).value > 0;
  32216. };
  32217. };
  32218. var getTexPickingMode = function getTexPickingMode(ele) {
  32219. // tells when a label should be clickable
  32220. var enabled = ele.pstyle('text-events').strValue === 'yes';
  32221. return enabled ? TEX_PICKING_MODE.USE_BB : TEX_PICKING_MODE.IGNORE;
  32222. };
  32223. var getBBForSimpleShape = function getBBForSimpleShape(node) {
  32224. // "simple" shapes need their BB to include border and padding
  32225. var _node$position = node.position(),
  32226. x = _node$position.x,
  32227. y = _node$position.y;
  32228. var w = node.outerWidth(); // includes border and padding
  32229. var h = node.outerHeight();
  32230. return {
  32231. w: w,
  32232. h: h,
  32233. x1: x - w / 2,
  32234. y1: y - h / 2
  32235. };
  32236. };
  32237. // An AtlasCollection is a collection of Atlases that have the same configuraiton options.
  32238. // Create one for node bodies and one for all types of labels.
  32239. r.drawing.addAtlasCollection('node', {
  32240. texRows: opts.webglTexRowsNodes
  32241. });
  32242. r.drawing.addAtlasCollection('label', {
  32243. texRows: opts.webglTexRows
  32244. });
  32245. // Configure the different types of elements that can be rendered.
  32246. // Node bodies can be rendered as textures or as "simple shapes".
  32247. // Simple shapes are preferred because they do not use texture memory.
  32248. // Textures are required if the node body uses complex styles.
  32249. r.drawing.addTextureAtlasRenderType('node-body', {
  32250. collection: 'node',
  32251. getKey: fns.getStyleKey,
  32252. getBoundingBox: fns.getElementBox,
  32253. drawElement: fns.drawElement
  32254. });
  32255. r.drawing.addSimpleShapeRenderType('node-body', {
  32256. getBoundingBox: getBBForSimpleShape,
  32257. isSimple: isSimpleShape,
  32258. shapeProps: {
  32259. shape: 'shape',
  32260. color: 'background-color',
  32261. opacity: 'background-opacity',
  32262. radius: 'corner-radius',
  32263. border: true
  32264. }
  32265. });
  32266. r.drawing.addSimpleShapeRenderType('node-overlay', {
  32267. getBoundingBox: getBBForSimpleShape,
  32268. isVisible: isLayerVisible('overlay'),
  32269. shapeProps: {
  32270. shape: 'overlay-shape',
  32271. color: 'overlay-color',
  32272. opacity: 'overlay-opacity',
  32273. padding: 'overlay-padding',
  32274. radius: 'overlay-corner-radius'
  32275. }
  32276. });
  32277. r.drawing.addSimpleShapeRenderType('node-underlay', {
  32278. getBoundingBox: getBBForSimpleShape,
  32279. isVisible: isLayerVisible('underlay'),
  32280. shapeProps: {
  32281. shape: 'underlay-shape',
  32282. color: 'underlay-color',
  32283. opacity: 'underlay-opacity',
  32284. padding: 'underlay-padding',
  32285. radius: 'underlay-corner-radius'
  32286. }
  32287. });
  32288. r.drawing.addTextureAtlasRenderType('label', {
  32289. // node label or edge mid label
  32290. collection: 'label',
  32291. getTexPickingMode: getTexPickingMode,
  32292. getKey: getStyleKeysForLabel(fns.getLabelKey, null),
  32293. getBoundingBox: getBoundingBoxForLabel(fns.getLabelBox, null),
  32294. drawClipped: true,
  32295. drawElement: fns.drawLabel,
  32296. getRotation: getLabelRotation(null),
  32297. getRotationPoint: fns.getLabelRotationPoint,
  32298. getRotationOffset: fns.getLabelRotationOffset,
  32299. isVisible: isLabelVisible('label')
  32300. });
  32301. r.drawing.addTextureAtlasRenderType('edge-source-label', {
  32302. collection: 'label',
  32303. getTexPickingMode: getTexPickingMode,
  32304. getKey: getStyleKeysForLabel(fns.getSourceLabelKey, 'source'),
  32305. getBoundingBox: getBoundingBoxForLabel(fns.getSourceLabelBox, 'source'),
  32306. drawClipped: true,
  32307. drawElement: fns.drawSourceLabel,
  32308. getRotation: getLabelRotation('source'),
  32309. getRotationPoint: fns.getSourceLabelRotationPoint,
  32310. getRotationOffset: fns.getSourceLabelRotationOffset,
  32311. isVisible: isLabelVisible('source-label')
  32312. });
  32313. r.drawing.addTextureAtlasRenderType('edge-target-label', {
  32314. collection: 'label',
  32315. getTexPickingMode: getTexPickingMode,
  32316. getKey: getStyleKeysForLabel(fns.getTargetLabelKey, 'target'),
  32317. getBoundingBox: getBoundingBoxForLabel(fns.getTargetLabelBox, 'target'),
  32318. drawClipped: true,
  32319. drawElement: fns.drawTargetLabel,
  32320. getRotation: getLabelRotation('target'),
  32321. getRotationPoint: fns.getTargetLabelRotationPoint,
  32322. getRotationOffset: fns.getTargetLabelRotationOffset,
  32323. isVisible: isLabelVisible('target-label')
  32324. });
  32325. // Very simplistic way of triggering garbage collection, just use a timer.
  32326. var setGCFlag = debounce(function () {
  32327. console.log('garbage collect flag set');
  32328. r.data.gc = true;
  32329. }, 10000);
  32330. // Event listener checks if style keys are no longer in use.
  32331. r.onUpdateEleCalcs(function (willDraw, eles) {
  32332. var gcNeeded = false;
  32333. if (eles && eles.length > 0) {
  32334. gcNeeded |= r.drawing.invalidate(eles);
  32335. }
  32336. if (gcNeeded) {
  32337. setGCFlag();
  32338. }
  32339. });
  32340. // "Override" certain functions in canvas and base renderer
  32341. overrideCanvasRendererFunctions(r);
  32342. };
  32343. function getBGColor(r) {
  32344. var container = r.cy.container();
  32345. var cssColor = container && container.style && container.style.backgroundColor || 'white';
  32346. return color2tuple(cssColor);
  32347. }
  32348. function getLabelLines(ele, prefix) {
  32349. var rs = ele._private.rscratch;
  32350. return getPrefixedProperty(rs, 'labelWrapCachedLines', prefix) || [];
  32351. }
  32352. /**
  32353. * Handle multi-line labels by rendering each line as a seperate texture.
  32354. * That means each line needs its own style key.
  32355. */
  32356. var getStyleKeysForLabel = function getStyleKeysForLabel(getKey, prefix) {
  32357. return function (ele) {
  32358. var key = getKey(ele);
  32359. var lines = getLabelLines(ele, prefix);
  32360. if (lines.length > 1) {
  32361. return lines.map(function (line, index) {
  32362. return "".concat(key, "_").concat(index);
  32363. });
  32364. }
  32365. return key;
  32366. };
  32367. };
  32368. /**
  32369. * Need to create a separate bounding box for each line of a multi-line label.
  32370. * Note that 'drawClipped: true' should be used with this.
  32371. */
  32372. var getBoundingBoxForLabel = function getBoundingBoxForLabel(getBoundingBox, prefix) {
  32373. return function (ele, styleKey) {
  32374. var bb = getBoundingBox(ele);
  32375. if (typeof styleKey === 'string') {
  32376. var ui = styleKey.indexOf('_');
  32377. if (ui > 0) {
  32378. var lineIndex = Number(styleKey.substring(ui + 1));
  32379. var lines = getLabelLines(ele, prefix);
  32380. // Adjust the height and Y coordinate for one line of the label.
  32381. var h = bb.h / lines.length;
  32382. var yOffset = h * lineIndex;
  32383. var y1 = bb.y1 + yOffset;
  32384. // the yOffset is needed when rotating the label
  32385. return {
  32386. x1: bb.x1,
  32387. w: bb.w,
  32388. y1: y1,
  32389. h: h,
  32390. yOffset: yOffset
  32391. };
  32392. }
  32393. }
  32394. return bb;
  32395. };
  32396. };
  32397. /**
  32398. * Plug into the canvas renderer by dynamically overriding some of its functions.
  32399. * This requires minimal changes to the canvas rendrerer.
  32400. */
  32401. function overrideCanvasRendererFunctions(r) {
  32402. {
  32403. // Override the render function to call the webgl render function if the zoom level is appropriate
  32404. var renderCanvas = r.render;
  32405. r.render = function (options) {
  32406. options = options || {};
  32407. var cy = r.cy;
  32408. if (r.webgl) {
  32409. // If the zoom level is greater than the max zoom level, then disable webgl and switch back to
  32410. // the canvas renderer.
  32411. if (cy.zoom() > maxZoom$1) {
  32412. clearWebgl(r);
  32413. renderCanvas.call(r, options);
  32414. } else {
  32415. clearCanvas(r);
  32416. renderWebgl(r, options, RENDER_TARGET.SCREEN);
  32417. }
  32418. }
  32419. };
  32420. }
  32421. {
  32422. // Override the matchCanvasSize function to update the picking frame buffer size
  32423. var baseFunc = r.matchCanvasSize;
  32424. r.matchCanvasSize = function (container) {
  32425. baseFunc.call(r, container);
  32426. r.pickingFrameBuffer.setFramebufferAttachmentSizes(r.canvasWidth, r.canvasHeight);
  32427. r.pickingFrameBuffer.needsDraw = true;
  32428. };
  32429. }
  32430. {
  32431. // Override function to call the webgl version for picking.
  32432. // Don't override r.getAllInBox() selction box picking, its not accurate enough with webgl
  32433. r.findNearestElements = function (x, y, interactiveElementsOnly, isTouch) {
  32434. // the canvas version of this function is very slow on large graphs
  32435. return findNearestElementsWebgl(r, x, y);
  32436. };
  32437. }
  32438. {
  32439. // need to know when the cached elements have changed so we can invalidate our caches
  32440. var _baseFunc = r.invalidateCachedZSortedEles;
  32441. r.invalidateCachedZSortedEles = function () {
  32442. _baseFunc.call(r);
  32443. r.pickingFrameBuffer.needsDraw = true;
  32444. };
  32445. }
  32446. {
  32447. // need to know when the cached elements have changed so we can invalidate our caches
  32448. var _baseFunc2 = r.notify;
  32449. r.notify = function (eventName, eles) {
  32450. _baseFunc2.call(r, eventName, eles);
  32451. if (eventName === 'viewport' || eventName === 'bounds') {
  32452. r.pickingFrameBuffer.needsDraw = true;
  32453. } else if (eventName === 'background') {
  32454. // background image finished loading, need to redraw
  32455. r.drawing.invalidate(eles, {
  32456. type: 'node-body'
  32457. });
  32458. }
  32459. };
  32460. }
  32461. }
  32462. function clearWebgl(r) {
  32463. var gl = r.data.contexts[r.WEBGL];
  32464. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  32465. }
  32466. function clearCanvas(r) {
  32467. // the CRp.clearCanvas() function doesn't take the transform into account
  32468. var clear = function clear(context) {
  32469. context.save();
  32470. context.setTransform(1, 0, 0, 1, 0, 0);
  32471. context.clearRect(0, 0, r.canvasWidth, r.canvasHeight);
  32472. context.restore();
  32473. };
  32474. clear(r.data.contexts[r.NODE]);
  32475. clear(r.data.contexts[r.DRAG]);
  32476. }
  32477. function createPanZoomMatrix(r) {
  32478. var width = r.canvasWidth;
  32479. var height = r.canvasHeight;
  32480. var _util$getEffectivePan = getEffectivePanZoom(r),
  32481. pan = _util$getEffectivePan.pan,
  32482. zoom = _util$getEffectivePan.zoom;
  32483. var transform = create();
  32484. translate(transform, transform, [pan.x, pan.y]);
  32485. scale(transform, transform, [zoom, zoom]);
  32486. var projection$1 = create();
  32487. projection(projection$1, width, height);
  32488. var product = create();
  32489. multiply(product, projection$1, transform);
  32490. return product;
  32491. }
  32492. function setContextTransform(r, context) {
  32493. var width = r.canvasWidth;
  32494. var height = r.canvasHeight;
  32495. var _util$getEffectivePan2 = getEffectivePanZoom(r),
  32496. pan = _util$getEffectivePan2.pan,
  32497. zoom = _util$getEffectivePan2.zoom;
  32498. context.setTransform(1, 0, 0, 1, 0, 0);
  32499. context.clearRect(0, 0, width, height);
  32500. context.translate(pan.x, pan.y);
  32501. context.scale(zoom, zoom);
  32502. }
  32503. function drawSelectionRectangle(r, options) {
  32504. r.drawSelectionRectangle(options, function (context) {
  32505. return setContextTransform(r, context);
  32506. });
  32507. }
  32508. function drawAxes(r) {
  32509. // for debgging
  32510. var context = r.data.contexts[r.NODE];
  32511. context.save();
  32512. setContextTransform(r, context);
  32513. context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
  32514. context.beginPath();
  32515. context.moveTo(-1e3, 0);
  32516. context.lineTo(1000, 0);
  32517. context.stroke();
  32518. context.beginPath();
  32519. context.moveTo(0, -1e3);
  32520. context.lineTo(0, 1000);
  32521. context.stroke();
  32522. context.restore();
  32523. }
  32524. function drawAtlases(r) {
  32525. // For debugging the atlases, this doesn't work for Atlases that are locked
  32526. var draw = function draw(drawing, name, row) {
  32527. var collection = drawing.atlasManager.getAtlasCollection(name);
  32528. var context = r.data.contexts[r.NODE];
  32529. var atlases = collection.atlases;
  32530. for (var _i = 0; _i < atlases.length; _i++) {
  32531. var atlas = atlases[_i];
  32532. var canvas = atlas.canvas;
  32533. if (canvas) {
  32534. var w = canvas.width;
  32535. var h = canvas.height;
  32536. var x = w * _i;
  32537. var y = canvas.height * row;
  32538. var scale = 0.4;
  32539. context.save();
  32540. context.scale(scale, scale);
  32541. context.drawImage(canvas, x, y);
  32542. context.strokeStyle = 'black';
  32543. context.rect(x, y, w, h);
  32544. context.stroke();
  32545. context.restore();
  32546. }
  32547. }
  32548. };
  32549. var i = 0;
  32550. draw(r.drawing, 'node', i++);
  32551. draw(r.drawing, 'label', i++);
  32552. }
  32553. /**
  32554. * Returns the z-order index of elments under or very close to the mouse cursor point.
  32555. * Arguments are in model coordinates.
  32556. * (x1, y1) is top left corner
  32557. * (x2, y2) is bottom right corner (optional)
  32558. * Returns a Set of indexes.
  32559. */
  32560. function getPickingIndexes(r, mX1, mY1, mX2, mY2) {
  32561. var x, y, w, h;
  32562. var _util$getEffectivePan3 = getEffectivePanZoom(r),
  32563. pan = _util$getEffectivePan3.pan,
  32564. zoom = _util$getEffectivePan3.zoom;
  32565. {
  32566. var _util$modelToRendered = modelToRenderedPosition(r, pan, zoom, mX1, mY1),
  32567. _util$modelToRendered2 = _slicedToArray(_util$modelToRendered, 2),
  32568. cX1 = _util$modelToRendered2[0],
  32569. cY1 = _util$modelToRendered2[1];
  32570. var t = 6; // should be even
  32571. x = cX1 - t / 2;
  32572. y = cY1 - t / 2;
  32573. w = t;
  32574. h = t;
  32575. }
  32576. if (w === 0 || h === 0) {
  32577. return [];
  32578. }
  32579. var gl = r.data.contexts[r.WEBGL];
  32580. gl.bindFramebuffer(gl.FRAMEBUFFER, r.pickingFrameBuffer);
  32581. if (r.pickingFrameBuffer.needsDraw) {
  32582. // Draw element z-indexes to the picking framebuffer
  32583. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  32584. renderWebgl(r, null, RENDER_TARGET.PICKING);
  32585. r.pickingFrameBuffer.needsDraw = false;
  32586. }
  32587. var n = w * h; // number of pixels to read
  32588. var data = new Uint8Array(n * 4); // 4 bytes per pixel
  32589. gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, data);
  32590. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  32591. var indexes = new Set();
  32592. for (var i = 0; i < n; i++) {
  32593. var pixel = data.slice(i * 4, i * 4 + 4);
  32594. var index = vec4ToIndex(pixel) - 1; // The framebuffer is cleared with 0s, so z-indexes are offset by 1
  32595. if (index >= 0) {
  32596. indexes.add(index);
  32597. }
  32598. }
  32599. return indexes;
  32600. }
  32601. /**
  32602. * Cy.js: model coordinate y axis goes down
  32603. */
  32604. function findNearestElementsWebgl(r, x, y) {
  32605. // model coordinates
  32606. var indexes = getPickingIndexes(r, x, y);
  32607. var eles = r.getCachedZSortedEles();
  32608. var node, edge;
  32609. var _iterator = _createForOfIteratorHelper(indexes),
  32610. _step;
  32611. try {
  32612. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  32613. var index = _step.value;
  32614. var ele = eles[index];
  32615. if (!node && ele.isNode()) {
  32616. node = ele;
  32617. }
  32618. if (!edge && ele.isEdge()) {
  32619. edge = ele;
  32620. }
  32621. if (node && edge) {
  32622. break;
  32623. }
  32624. }
  32625. } catch (err) {
  32626. _iterator.e(err);
  32627. } finally {
  32628. _iterator.f();
  32629. }
  32630. return [node, edge].filter(Boolean);
  32631. }
  32632. /**
  32633. * Draw one node or edge.
  32634. */
  32635. function drawEle(r, index, ele) {
  32636. var drawing = r.drawing;
  32637. index += 1; // 0 is used to clear the background, need to offset all z-indexes by one
  32638. if (ele.isNode()) {
  32639. drawing.drawNode(ele, index, 'node-underlay');
  32640. drawing.drawNode(ele, index, 'node-body');
  32641. drawing.drawTexture(ele, index, 'label');
  32642. drawing.drawNode(ele, index, 'node-overlay');
  32643. } else {
  32644. drawing.drawEdgeLine(ele, index);
  32645. drawing.drawEdgeArrow(ele, index, 'source');
  32646. drawing.drawEdgeArrow(ele, index, 'target');
  32647. drawing.drawTexture(ele, index, 'label');
  32648. drawing.drawTexture(ele, index, 'edge-source-label');
  32649. drawing.drawTexture(ele, index, 'edge-target-label');
  32650. }
  32651. }
  32652. /**
  32653. * Render one frame.
  32654. */
  32655. function renderWebgl(r, options, renderTarget) {
  32656. var start;
  32657. if (r.webglDebug) {
  32658. start = performance.now(); // eslint-disable-line no-undef
  32659. }
  32660. var drawing = r.drawing;
  32661. var eleCount = 0;
  32662. if (renderTarget.screen) {
  32663. if (r.data.canvasNeedsRedraw[r.SELECT_BOX]) {
  32664. drawSelectionRectangle(r, options);
  32665. }
  32666. }
  32667. // see drawing-elements.js drawCachedElement()
  32668. if (r.data.canvasNeedsRedraw[r.NODE] || renderTarget.picking) {
  32669. var gl = r.data.contexts[r.WEBGL];
  32670. if (renderTarget.screen) {
  32671. gl.clearColor(0, 0, 0, 0); // background color
  32672. gl.enable(gl.BLEND); // enable alpha blending of colors
  32673. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // webgl colors use premultiplied alpha
  32674. } else {
  32675. gl.disable(gl.BLEND); // don't blend z-order index values! they are not colors
  32676. }
  32677. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  32678. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  32679. var panZoomMatrix = createPanZoomMatrix(r);
  32680. var eles = r.getCachedZSortedEles();
  32681. eleCount = eles.length;
  32682. drawing.startFrame(panZoomMatrix, renderTarget);
  32683. if (renderTarget.screen) {
  32684. for (var i = 0; i < eles.nondrag.length; i++) {
  32685. drawEle(r, i, eles.nondrag[i]);
  32686. }
  32687. for (var _i2 = 0; _i2 < eles.drag.length; _i2++) {
  32688. drawEle(r, _i2, eles.drag[_i2]);
  32689. }
  32690. } else if (renderTarget.picking) {
  32691. for (var _i3 = 0; _i3 < eles.length; _i3++) {
  32692. drawEle(r, _i3, eles[_i3]);
  32693. }
  32694. }
  32695. drawing.endFrame();
  32696. if (renderTarget.screen && r.webglDebugShowAtlases) {
  32697. drawAxes(r);
  32698. drawAtlases(r);
  32699. }
  32700. r.data.canvasNeedsRedraw[r.NODE] = false;
  32701. r.data.canvasNeedsRedraw[r.DRAG] = false;
  32702. }
  32703. if (r.webglDebug) {
  32704. // eslint-disable-next-line no-undef
  32705. var end = performance.now();
  32706. var compact = false;
  32707. var time = Math.ceil(end - start);
  32708. var debugInfo = drawing.getDebugInfo();
  32709. 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(', ');
  32710. if (compact) {
  32711. console.log("WebGL (".concat(renderTarget.name, ") - time ").concat(time, "ms, ").concat(report));
  32712. } else {
  32713. console.log("WebGL (".concat(renderTarget.name, ") - frame time ").concat(time, "ms"));
  32714. console.log('Totals:');
  32715. console.log(" ".concat(report));
  32716. console.log('Texture Atlases Used:');
  32717. var atlasInfo = debugInfo.atlasInfo;
  32718. var _iterator2 = _createForOfIteratorHelper(atlasInfo),
  32719. _step2;
  32720. try {
  32721. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  32722. var info = _step2.value;
  32723. console.log(" ".concat(info.type, ": ").concat(info.keyCount, " keys, ").concat(info.atlasCount, " atlases"));
  32724. }
  32725. } catch (err) {
  32726. _iterator2.e(err);
  32727. } finally {
  32728. _iterator2.f();
  32729. }
  32730. console.log('');
  32731. }
  32732. }
  32733. if (r.data.gc) {
  32734. console.log('Garbage Collect!');
  32735. r.data.gc = false;
  32736. drawing.gc();
  32737. }
  32738. }
  32739. var CRp$3 = {};
  32740. // @O Polygon drawing
  32741. CRp$3.drawPolygonPath = function (context, x, y, width, height, points) {
  32742. var halfW = width / 2;
  32743. var halfH = height / 2;
  32744. if (context.beginPath) {
  32745. context.beginPath();
  32746. }
  32747. context.moveTo(x + halfW * points[0], y + halfH * points[1]);
  32748. for (var i = 1; i < points.length / 2; i++) {
  32749. context.lineTo(x + halfW * points[i * 2], y + halfH * points[i * 2 + 1]);
  32750. }
  32751. context.closePath();
  32752. };
  32753. CRp$3.drawRoundPolygonPath = function (context, x, y, width, height, points, corners) {
  32754. corners.forEach(function (corner) {
  32755. return drawPreparedRoundCorner(context, corner);
  32756. });
  32757. context.closePath();
  32758. };
  32759. // Round rectangle drawing
  32760. CRp$3.drawRoundRectanglePath = function (context, x, y, width, height, radius) {
  32761. var halfWidth = width / 2;
  32762. var halfHeight = height / 2;
  32763. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : Math.min(radius, halfHeight, halfWidth);
  32764. if (context.beginPath) {
  32765. context.beginPath();
  32766. }
  32767. // Start at top middle
  32768. context.moveTo(x, y - halfHeight);
  32769. // Arc from middle top to right side
  32770. context.arcTo(x + halfWidth, y - halfHeight, x + halfWidth, y, cornerRadius);
  32771. // Arc from right side to bottom
  32772. context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  32773. // Arc from bottom to left side
  32774. context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  32775. // Arc from left side to topBorder
  32776. context.arcTo(x - halfWidth, y - halfHeight, x, y - halfHeight, cornerRadius);
  32777. // Join line
  32778. context.lineTo(x, y - halfHeight);
  32779. context.closePath();
  32780. };
  32781. CRp$3.drawBottomRoundRectanglePath = function (context, x, y, width, height, radius) {
  32782. var halfWidth = width / 2;
  32783. var halfHeight = height / 2;
  32784. var cornerRadius = radius === 'auto' ? getRoundRectangleRadius(width, height) : radius;
  32785. if (context.beginPath) {
  32786. context.beginPath();
  32787. }
  32788. // Start at top middle
  32789. context.moveTo(x, y - halfHeight);
  32790. context.lineTo(x + halfWidth, y - halfHeight);
  32791. context.lineTo(x + halfWidth, y);
  32792. context.arcTo(x + halfWidth, y + halfHeight, x, y + halfHeight, cornerRadius);
  32793. context.arcTo(x - halfWidth, y + halfHeight, x - halfWidth, y, cornerRadius);
  32794. context.lineTo(x - halfWidth, y - halfHeight);
  32795. context.lineTo(x, y - halfHeight);
  32796. context.closePath();
  32797. };
  32798. CRp$3.drawCutRectanglePath = function (context, x, y, width, height, points, corners) {
  32799. var halfWidth = width / 2;
  32800. var halfHeight = height / 2;
  32801. var cornerLength = corners === 'auto' ? getCutRectangleCornerLength() : corners;
  32802. if (context.beginPath) {
  32803. context.beginPath();
  32804. }
  32805. context.moveTo(x - halfWidth + cornerLength, y - halfHeight);
  32806. context.lineTo(x + halfWidth - cornerLength, y - halfHeight);
  32807. context.lineTo(x + halfWidth, y - halfHeight + cornerLength);
  32808. context.lineTo(x + halfWidth, y + halfHeight - cornerLength);
  32809. context.lineTo(x + halfWidth - cornerLength, y + halfHeight);
  32810. context.lineTo(x - halfWidth + cornerLength, y + halfHeight);
  32811. context.lineTo(x - halfWidth, y + halfHeight - cornerLength);
  32812. context.lineTo(x - halfWidth, y - halfHeight + cornerLength);
  32813. context.closePath();
  32814. };
  32815. CRp$3.drawBarrelPath = function (context, x, y, width, height) {
  32816. var halfWidth = width / 2;
  32817. var halfHeight = height / 2;
  32818. var xBegin = x - halfWidth;
  32819. var xEnd = x + halfWidth;
  32820. var yBegin = y - halfHeight;
  32821. var yEnd = y + halfHeight;
  32822. var barrelCurveConstants = getBarrelCurveConstants(width, height);
  32823. var wOffset = barrelCurveConstants.widthOffset;
  32824. var hOffset = barrelCurveConstants.heightOffset;
  32825. var ctrlPtXOffset = barrelCurveConstants.ctrlPtOffsetPct * wOffset;
  32826. if (context.beginPath) {
  32827. context.beginPath();
  32828. }
  32829. context.moveTo(xBegin, yBegin + hOffset);
  32830. context.lineTo(xBegin, yEnd - hOffset);
  32831. context.quadraticCurveTo(xBegin + ctrlPtXOffset, yEnd, xBegin + wOffset, yEnd);
  32832. context.lineTo(xEnd - wOffset, yEnd);
  32833. context.quadraticCurveTo(xEnd - ctrlPtXOffset, yEnd, xEnd, yEnd - hOffset);
  32834. context.lineTo(xEnd, yBegin + hOffset);
  32835. context.quadraticCurveTo(xEnd - ctrlPtXOffset, yBegin, xEnd - wOffset, yBegin);
  32836. context.lineTo(xBegin + wOffset, yBegin);
  32837. context.quadraticCurveTo(xBegin + ctrlPtXOffset, yBegin, xBegin, yBegin + hOffset);
  32838. context.closePath();
  32839. };
  32840. var sin0 = Math.sin(0);
  32841. var cos0 = Math.cos(0);
  32842. var sin = {};
  32843. var cos = {};
  32844. var ellipseStepSize = Math.PI / 40;
  32845. for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  32846. sin[i] = Math.sin(i);
  32847. cos[i] = Math.cos(i);
  32848. }
  32849. CRp$3.drawEllipsePath = function (context, centerX, centerY, width, height) {
  32850. if (context.beginPath) {
  32851. context.beginPath();
  32852. }
  32853. if (context.ellipse) {
  32854. context.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, 2 * Math.PI);
  32855. } else {
  32856. var xPos, yPos;
  32857. var rw = width / 2;
  32858. var rh = height / 2;
  32859. for (var i = 0 * Math.PI; i < 2 * Math.PI; i += ellipseStepSize) {
  32860. xPos = centerX - rw * sin[i] * sin0 + rw * cos[i] * cos0;
  32861. yPos = centerY + rh * cos[i] * sin0 + rh * sin[i] * cos0;
  32862. if (i === 0) {
  32863. context.moveTo(xPos, yPos);
  32864. } else {
  32865. context.lineTo(xPos, yPos);
  32866. }
  32867. }
  32868. }
  32869. context.closePath();
  32870. };
  32871. /* global atob, ArrayBuffer, Uint8Array, Blob */
  32872. var CRp$2 = {};
  32873. CRp$2.createBuffer = function (w, h) {
  32874. var buffer = document.createElement('canvas'); // eslint-disable-line no-undef
  32875. buffer.width = w;
  32876. buffer.height = h;
  32877. return [buffer, buffer.getContext('2d')];
  32878. };
  32879. CRp$2.bufferCanvasImage = function (options) {
  32880. var cy = this.cy;
  32881. var eles = cy.mutableElements();
  32882. var bb = eles.boundingBox();
  32883. var ctrRect = this.findContainerClientCoords();
  32884. var width = options.full ? Math.ceil(bb.w) : ctrRect[2];
  32885. var height = options.full ? Math.ceil(bb.h) : ctrRect[3];
  32886. var specdMaxDims = number$1(options.maxWidth) || number$1(options.maxHeight);
  32887. var pxRatio = this.getPixelRatio();
  32888. var scale = 1;
  32889. if (options.scale !== undefined) {
  32890. width *= options.scale;
  32891. height *= options.scale;
  32892. scale = options.scale;
  32893. } else if (specdMaxDims) {
  32894. var maxScaleW = Infinity;
  32895. var maxScaleH = Infinity;
  32896. if (number$1(options.maxWidth)) {
  32897. maxScaleW = scale * options.maxWidth / width;
  32898. }
  32899. if (number$1(options.maxHeight)) {
  32900. maxScaleH = scale * options.maxHeight / height;
  32901. }
  32902. scale = Math.min(maxScaleW, maxScaleH);
  32903. width *= scale;
  32904. height *= scale;
  32905. }
  32906. if (!specdMaxDims) {
  32907. width *= pxRatio;
  32908. height *= pxRatio;
  32909. scale *= pxRatio;
  32910. }
  32911. var buffCanvas = document.createElement('canvas'); // eslint-disable-line no-undef
  32912. buffCanvas.width = width;
  32913. buffCanvas.height = height;
  32914. buffCanvas.style.width = width + 'px';
  32915. buffCanvas.style.height = height + 'px';
  32916. var buffCxt = buffCanvas.getContext('2d');
  32917. // Rasterize the layers, but only if container has nonzero size
  32918. if (width > 0 && height > 0) {
  32919. buffCxt.clearRect(0, 0, width, height);
  32920. buffCxt.globalCompositeOperation = 'source-over';
  32921. var zsortedEles = this.getCachedZSortedEles();
  32922. if (options.full) {
  32923. // draw the full bounds of the graph
  32924. buffCxt.translate(-bb.x1 * scale, -bb.y1 * scale);
  32925. buffCxt.scale(scale, scale);
  32926. this.drawElements(buffCxt, zsortedEles);
  32927. buffCxt.scale(1 / scale, 1 / scale);
  32928. buffCxt.translate(bb.x1 * scale, bb.y1 * scale);
  32929. } else {
  32930. // draw the current view
  32931. var pan = cy.pan();
  32932. var translation = {
  32933. x: pan.x * scale,
  32934. y: pan.y * scale
  32935. };
  32936. scale *= cy.zoom();
  32937. buffCxt.translate(translation.x, translation.y);
  32938. buffCxt.scale(scale, scale);
  32939. this.drawElements(buffCxt, zsortedEles);
  32940. buffCxt.scale(1 / scale, 1 / scale);
  32941. buffCxt.translate(-translation.x, -translation.y);
  32942. }
  32943. // need to fill bg at end like this in order to fill cleared transparent pixels in jpgs
  32944. if (options.bg) {
  32945. buffCxt.globalCompositeOperation = 'destination-over';
  32946. buffCxt.fillStyle = options.bg;
  32947. buffCxt.rect(0, 0, width, height);
  32948. buffCxt.fill();
  32949. }
  32950. }
  32951. return buffCanvas;
  32952. };
  32953. function b64ToBlob(b64, mimeType) {
  32954. var bytes = atob(b64);
  32955. var buff = new ArrayBuffer(bytes.length);
  32956. var buffUint8 = new Uint8Array(buff);
  32957. for (var i = 0; i < bytes.length; i++) {
  32958. buffUint8[i] = bytes.charCodeAt(i);
  32959. }
  32960. return new Blob([buff], {
  32961. type: mimeType
  32962. });
  32963. }
  32964. function b64UriToB64(b64uri) {
  32965. var i = b64uri.indexOf(',');
  32966. return b64uri.substr(i + 1);
  32967. }
  32968. function output(options, canvas, mimeType) {
  32969. var getB64Uri = function getB64Uri() {
  32970. return canvas.toDataURL(mimeType, options.quality);
  32971. };
  32972. switch (options.output) {
  32973. case 'blob-promise':
  32974. return new Promise$1(function (resolve, reject) {
  32975. try {
  32976. canvas.toBlob(function (blob) {
  32977. if (blob != null) {
  32978. resolve(blob);
  32979. } else {
  32980. reject(new Error('`canvas.toBlob()` sent a null value in its callback'));
  32981. }
  32982. }, mimeType, options.quality);
  32983. } catch (err) {
  32984. reject(err);
  32985. }
  32986. });
  32987. case 'blob':
  32988. return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);
  32989. case 'base64':
  32990. return b64UriToB64(getB64Uri());
  32991. case 'base64uri':
  32992. default:
  32993. return getB64Uri();
  32994. }
  32995. }
  32996. CRp$2.png = function (options) {
  32997. return output(options, this.bufferCanvasImage(options), 'image/png');
  32998. };
  32999. CRp$2.jpg = function (options) {
  33000. return output(options, this.bufferCanvasImage(options), 'image/jpeg');
  33001. };
  33002. var CRp$1 = {};
  33003. CRp$1.nodeShapeImpl = function (name, context, centerX, centerY, width, height, points, corners) {
  33004. switch (name) {
  33005. case 'ellipse':
  33006. return this.drawEllipsePath(context, centerX, centerY, width, height);
  33007. case 'polygon':
  33008. return this.drawPolygonPath(context, centerX, centerY, width, height, points);
  33009. case 'round-polygon':
  33010. return this.drawRoundPolygonPath(context, centerX, centerY, width, height, points, corners);
  33011. case 'roundrectangle':
  33012. case 'round-rectangle':
  33013. return this.drawRoundRectanglePath(context, centerX, centerY, width, height, corners);
  33014. case 'cutrectangle':
  33015. case 'cut-rectangle':
  33016. return this.drawCutRectanglePath(context, centerX, centerY, width, height, points, corners);
  33017. case 'bottomroundrectangle':
  33018. case 'bottom-round-rectangle':
  33019. return this.drawBottomRoundRectanglePath(context, centerX, centerY, width, height, corners);
  33020. case 'barrel':
  33021. return this.drawBarrelPath(context, centerX, centerY, width, height);
  33022. }
  33023. };
  33024. var CR = CanvasRenderer;
  33025. var CRp = CanvasRenderer.prototype;
  33026. CRp.CANVAS_LAYERS = 3;
  33027. //
  33028. CRp.SELECT_BOX = 0;
  33029. CRp.DRAG = 1;
  33030. CRp.NODE = 2;
  33031. CRp.WEBGL = 3;
  33032. CRp.CANVAS_TYPES = ['2d', '2d', '2d', 'webgl2'];
  33033. CRp.BUFFER_COUNT = 3;
  33034. //
  33035. CRp.TEXTURE_BUFFER = 0;
  33036. CRp.MOTIONBLUR_BUFFER_NODE = 1;
  33037. CRp.MOTIONBLUR_BUFFER_DRAG = 2;
  33038. function CanvasRenderer(options) {
  33039. var r = this;
  33040. var containerWindow = r.cy.window();
  33041. var document = containerWindow.document;
  33042. if (options.webgl) {
  33043. CRp.CANVAS_LAYERS = r.CANVAS_LAYERS = 4;
  33044. console.log('webgl rendering enabled');
  33045. }
  33046. r.data = {
  33047. canvases: new Array(CRp.CANVAS_LAYERS),
  33048. contexts: new Array(CRp.CANVAS_LAYERS),
  33049. canvasNeedsRedraw: new Array(CRp.CANVAS_LAYERS),
  33050. bufferCanvases: new Array(CRp.BUFFER_COUNT),
  33051. bufferContexts: new Array(CRp.CANVAS_LAYERS)
  33052. };
  33053. var tapHlOffAttr = '-webkit-tap-highlight-color';
  33054. var tapHlOffStyle = 'rgba(0,0,0,0)';
  33055. r.data.canvasContainer = document.createElement('div'); // eslint-disable-line no-undef
  33056. var containerStyle = r.data.canvasContainer.style;
  33057. r.data.canvasContainer.style[tapHlOffAttr] = tapHlOffStyle;
  33058. containerStyle.position = 'relative';
  33059. containerStyle.zIndex = '0';
  33060. containerStyle.overflow = 'hidden';
  33061. var container = options.cy.container();
  33062. container.appendChild(r.data.canvasContainer);
  33063. container.style[tapHlOffAttr] = tapHlOffStyle;
  33064. var styleMap = {
  33065. '-webkit-user-select': 'none',
  33066. '-moz-user-select': '-moz-none',
  33067. 'user-select': 'none',
  33068. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',
  33069. 'outline-style': 'none'
  33070. };
  33071. if (ms()) {
  33072. styleMap['-ms-touch-action'] = 'none';
  33073. styleMap['touch-action'] = 'none';
  33074. }
  33075. for (var i = 0; i < CRp.CANVAS_LAYERS; i++) {
  33076. var canvas = r.data.canvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
  33077. var type = CRp.CANVAS_TYPES[i];
  33078. r.data.contexts[i] = canvas.getContext(type);
  33079. if (!r.data.contexts[i]) {
  33080. error('Could not create canvas of type ' + type);
  33081. }
  33082. Object.keys(styleMap).forEach(function (k) {
  33083. canvas.style[k] = styleMap[k];
  33084. });
  33085. canvas.style.position = 'absolute';
  33086. canvas.setAttribute('data-id', 'layer' + i);
  33087. canvas.style.zIndex = String(CRp.CANVAS_LAYERS - i);
  33088. r.data.canvasContainer.appendChild(canvas);
  33089. r.data.canvasNeedsRedraw[i] = false;
  33090. }
  33091. r.data.topCanvas = r.data.canvases[0];
  33092. r.data.canvases[CRp.NODE].setAttribute('data-id', 'layer' + CRp.NODE + '-node');
  33093. r.data.canvases[CRp.SELECT_BOX].setAttribute('data-id', 'layer' + CRp.SELECT_BOX + '-selectbox');
  33094. r.data.canvases[CRp.DRAG].setAttribute('data-id', 'layer' + CRp.DRAG + '-drag');
  33095. if (r.data.canvases[CRp.WEBGL]) {
  33096. r.data.canvases[CRp.WEBGL].setAttribute('data-id', 'layer' + CRp.WEBGL + '-webgl');
  33097. }
  33098. for (var i = 0; i < CRp.BUFFER_COUNT; i++) {
  33099. r.data.bufferCanvases[i] = document.createElement('canvas'); // eslint-disable-line no-undef
  33100. r.data.bufferContexts[i] = r.data.bufferCanvases[i].getContext('2d');
  33101. r.data.bufferCanvases[i].style.position = 'absolute';
  33102. r.data.bufferCanvases[i].setAttribute('data-id', 'buffer' + i);
  33103. r.data.bufferCanvases[i].style.zIndex = String(-i - 1);
  33104. r.data.bufferCanvases[i].style.visibility = 'hidden';
  33105. //r.data.canvasContainer.appendChild(r.data.bufferCanvases[i]);
  33106. }
  33107. r.pathsEnabled = true;
  33108. var emptyBb = makeBoundingBox();
  33109. var getBoxCenter = function getBoxCenter(bb) {
  33110. return {
  33111. x: (bb.x1 + bb.x2) / 2,
  33112. y: (bb.y1 + bb.y2) / 2
  33113. };
  33114. };
  33115. var getCenterOffset = function getCenterOffset(bb) {
  33116. return {
  33117. x: -bb.w / 2,
  33118. y: -bb.h / 2
  33119. };
  33120. };
  33121. var backgroundTimestampHasChanged = function backgroundTimestampHasChanged(ele) {
  33122. var _p = ele[0]._private;
  33123. var same = _p.oldBackgroundTimestamp === _p.backgroundTimestamp;
  33124. return !same;
  33125. };
  33126. var getStyleKey = function getStyleKey(ele) {
  33127. return ele[0]._private.nodeKey;
  33128. };
  33129. var getLabelKey = function getLabelKey(ele) {
  33130. return ele[0]._private.labelStyleKey;
  33131. };
  33132. var getSourceLabelKey = function getSourceLabelKey(ele) {
  33133. return ele[0]._private.sourceLabelStyleKey;
  33134. };
  33135. var getTargetLabelKey = function getTargetLabelKey(ele) {
  33136. return ele[0]._private.targetLabelStyleKey;
  33137. };
  33138. var drawElement = function drawElement(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33139. return r.drawElement(context, ele, bb, false, false, useEleOpacity);
  33140. };
  33141. var drawLabel = function drawLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33142. return r.drawElementText(context, ele, bb, scaledLabelShown, 'main', useEleOpacity);
  33143. };
  33144. var drawSourceLabel = function drawSourceLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33145. return r.drawElementText(context, ele, bb, scaledLabelShown, 'source', useEleOpacity);
  33146. };
  33147. var drawTargetLabel = function drawTargetLabel(context, ele, bb, scaledLabelShown, useEleOpacity) {
  33148. return r.drawElementText(context, ele, bb, scaledLabelShown, 'target', useEleOpacity);
  33149. };
  33150. var getElementBox = function getElementBox(ele) {
  33151. ele.boundingBox();
  33152. return ele[0]._private.bodyBounds;
  33153. };
  33154. var getLabelBox = function getLabelBox(ele) {
  33155. ele.boundingBox();
  33156. return ele[0]._private.labelBounds.main || emptyBb;
  33157. };
  33158. var getSourceLabelBox = function getSourceLabelBox(ele) {
  33159. ele.boundingBox();
  33160. return ele[0]._private.labelBounds.source || emptyBb;
  33161. };
  33162. var getTargetLabelBox = function getTargetLabelBox(ele) {
  33163. ele.boundingBox();
  33164. return ele[0]._private.labelBounds.target || emptyBb;
  33165. };
  33166. var isLabelVisibleAtScale = function isLabelVisibleAtScale(ele, scaledLabelShown) {
  33167. return scaledLabelShown;
  33168. };
  33169. var getElementRotationPoint = function getElementRotationPoint(ele) {
  33170. return getBoxCenter(getElementBox(ele));
  33171. };
  33172. var addTextMargin = function addTextMargin(prefix, pt, ele) {
  33173. var pre = prefix ? prefix + '-' : '';
  33174. return {
  33175. x: pt.x + ele.pstyle(pre + 'text-margin-x').pfValue,
  33176. y: pt.y + ele.pstyle(pre + 'text-margin-y').pfValue
  33177. };
  33178. };
  33179. var getRsPt = function getRsPt(ele, x, y) {
  33180. var rs = ele[0]._private.rscratch;
  33181. return {
  33182. x: rs[x],
  33183. y: rs[y]
  33184. };
  33185. };
  33186. var getLabelRotationPoint = function getLabelRotationPoint(ele) {
  33187. return addTextMargin('', getRsPt(ele, 'labelX', 'labelY'), ele);
  33188. };
  33189. var getSourceLabelRotationPoint = function getSourceLabelRotationPoint(ele) {
  33190. return addTextMargin('source', getRsPt(ele, 'sourceLabelX', 'sourceLabelY'), ele);
  33191. };
  33192. var getTargetLabelRotationPoint = function getTargetLabelRotationPoint(ele) {
  33193. return addTextMargin('target', getRsPt(ele, 'targetLabelX', 'targetLabelY'), ele);
  33194. };
  33195. var getElementRotationOffset = function getElementRotationOffset(ele) {
  33196. return getCenterOffset(getElementBox(ele));
  33197. };
  33198. var getSourceLabelRotationOffset = function getSourceLabelRotationOffset(ele) {
  33199. return getCenterOffset(getSourceLabelBox(ele));
  33200. };
  33201. var getTargetLabelRotationOffset = function getTargetLabelRotationOffset(ele) {
  33202. return getCenterOffset(getTargetLabelBox(ele));
  33203. };
  33204. var getLabelRotationOffset = function getLabelRotationOffset(ele) {
  33205. var bb = getLabelBox(ele);
  33206. var p = getCenterOffset(getLabelBox(ele));
  33207. if (ele.isNode()) {
  33208. switch (ele.pstyle('text-halign').value) {
  33209. case 'left':
  33210. p.x = -bb.w - (bb.leftPad || 0);
  33211. break;
  33212. case 'right':
  33213. p.x = -(bb.rightPad || 0);
  33214. break;
  33215. }
  33216. switch (ele.pstyle('text-valign').value) {
  33217. case 'top':
  33218. p.y = -bb.h - (bb.topPad || 0);
  33219. break;
  33220. case 'bottom':
  33221. p.y = -(bb.botPad || 0);
  33222. break;
  33223. }
  33224. }
  33225. return p;
  33226. };
  33227. var eleTxrCache = r.data.eleTxrCache = new ElementTextureCache(r, {
  33228. getKey: getStyleKey,
  33229. doesEleInvalidateKey: backgroundTimestampHasChanged,
  33230. drawElement: drawElement,
  33231. getBoundingBox: getElementBox,
  33232. getRotationPoint: getElementRotationPoint,
  33233. getRotationOffset: getElementRotationOffset,
  33234. allowEdgeTxrCaching: false,
  33235. allowParentTxrCaching: false
  33236. });
  33237. var lblTxrCache = r.data.lblTxrCache = new ElementTextureCache(r, {
  33238. getKey: getLabelKey,
  33239. drawElement: drawLabel,
  33240. getBoundingBox: getLabelBox,
  33241. getRotationPoint: getLabelRotationPoint,
  33242. getRotationOffset: getLabelRotationOffset,
  33243. isVisible: isLabelVisibleAtScale
  33244. });
  33245. var slbTxrCache = r.data.slbTxrCache = new ElementTextureCache(r, {
  33246. getKey: getSourceLabelKey,
  33247. drawElement: drawSourceLabel,
  33248. getBoundingBox: getSourceLabelBox,
  33249. getRotationPoint: getSourceLabelRotationPoint,
  33250. getRotationOffset: getSourceLabelRotationOffset,
  33251. isVisible: isLabelVisibleAtScale
  33252. });
  33253. var tlbTxrCache = r.data.tlbTxrCache = new ElementTextureCache(r, {
  33254. getKey: getTargetLabelKey,
  33255. drawElement: drawTargetLabel,
  33256. getBoundingBox: getTargetLabelBox,
  33257. getRotationPoint: getTargetLabelRotationPoint,
  33258. getRotationOffset: getTargetLabelRotationOffset,
  33259. isVisible: isLabelVisibleAtScale
  33260. });
  33261. var lyrTxrCache = r.data.lyrTxrCache = new LayeredTextureCache(r);
  33262. r.onUpdateEleCalcs(function invalidateTextureCaches(willDraw, eles) {
  33263. // each cache should check for sub-key diff to see that the update affects that cache particularly
  33264. eleTxrCache.invalidateElements(eles);
  33265. lblTxrCache.invalidateElements(eles);
  33266. slbTxrCache.invalidateElements(eles);
  33267. tlbTxrCache.invalidateElements(eles);
  33268. // any change invalidates the layers
  33269. lyrTxrCache.invalidateElements(eles);
  33270. // update the old bg timestamp so diffs can be done in the ele txr caches
  33271. for (var _i = 0; _i < eles.length; _i++) {
  33272. var _p = eles[_i]._private;
  33273. _p.oldBackgroundTimestamp = _p.backgroundTimestamp;
  33274. }
  33275. });
  33276. var refineInLayers = function refineInLayers(reqs) {
  33277. for (var i = 0; i < reqs.length; i++) {
  33278. lyrTxrCache.enqueueElementRefinement(reqs[i].ele);
  33279. }
  33280. };
  33281. eleTxrCache.onDequeue(refineInLayers);
  33282. lblTxrCache.onDequeue(refineInLayers);
  33283. slbTxrCache.onDequeue(refineInLayers);
  33284. tlbTxrCache.onDequeue(refineInLayers);
  33285. if (options.webgl) {
  33286. r.initWebgl(options, {
  33287. getStyleKey: getStyleKey,
  33288. getLabelKey: getLabelKey,
  33289. getSourceLabelKey: getSourceLabelKey,
  33290. getTargetLabelKey: getTargetLabelKey,
  33291. drawElement: drawElement,
  33292. drawLabel: drawLabel,
  33293. drawSourceLabel: drawSourceLabel,
  33294. drawTargetLabel: drawTargetLabel,
  33295. getElementBox: getElementBox,
  33296. getLabelBox: getLabelBox,
  33297. getSourceLabelBox: getSourceLabelBox,
  33298. getTargetLabelBox: getTargetLabelBox,
  33299. getElementRotationPoint: getElementRotationPoint,
  33300. getElementRotationOffset: getElementRotationOffset,
  33301. getLabelRotationPoint: getLabelRotationPoint,
  33302. getSourceLabelRotationPoint: getSourceLabelRotationPoint,
  33303. getTargetLabelRotationPoint: getTargetLabelRotationPoint,
  33304. getLabelRotationOffset: getLabelRotationOffset,
  33305. getSourceLabelRotationOffset: getSourceLabelRotationOffset,
  33306. getTargetLabelRotationOffset: getTargetLabelRotationOffset
  33307. });
  33308. }
  33309. }
  33310. CRp.redrawHint = function (group, bool) {
  33311. var r = this;
  33312. switch (group) {
  33313. case 'eles':
  33314. r.data.canvasNeedsRedraw[CRp.NODE] = bool;
  33315. break;
  33316. case 'drag':
  33317. r.data.canvasNeedsRedraw[CRp.DRAG] = bool;
  33318. break;
  33319. case 'select':
  33320. r.data.canvasNeedsRedraw[CRp.SELECT_BOX] = bool;
  33321. break;
  33322. case 'gc':
  33323. r.data.gc = true;
  33324. break;
  33325. }
  33326. };
  33327. // whether to use Path2D caching for drawing
  33328. var pathsImpld = typeof Path2D !== 'undefined';
  33329. CRp.path2dEnabled = function (on) {
  33330. if (on === undefined) {
  33331. return this.pathsEnabled;
  33332. }
  33333. this.pathsEnabled = on ? true : false;
  33334. };
  33335. CRp.usePaths = function () {
  33336. return pathsImpld && this.pathsEnabled;
  33337. };
  33338. CRp.setImgSmoothing = function (context, bool) {
  33339. if (context.imageSmoothingEnabled != null) {
  33340. context.imageSmoothingEnabled = bool;
  33341. } else {
  33342. context.webkitImageSmoothingEnabled = bool;
  33343. context.mozImageSmoothingEnabled = bool;
  33344. context.msImageSmoothingEnabled = bool;
  33345. }
  33346. };
  33347. CRp.getImgSmoothing = function (context) {
  33348. if (context.imageSmoothingEnabled != null) {
  33349. return context.imageSmoothingEnabled;
  33350. } else {
  33351. return context.webkitImageSmoothingEnabled || context.mozImageSmoothingEnabled || context.msImageSmoothingEnabled;
  33352. }
  33353. };
  33354. CRp.makeOffscreenCanvas = function (width, height) {
  33355. var canvas;
  33356. if ((typeof OffscreenCanvas === "undefined" ? "undefined" : _typeof(OffscreenCanvas)) !== ("undefined" )) {
  33357. canvas = new OffscreenCanvas(width, height);
  33358. } else {
  33359. var containerWindow = this.cy.window();
  33360. var document = containerWindow.document;
  33361. canvas = document.createElement('canvas'); // eslint-disable-line no-undef
  33362. canvas.width = width;
  33363. canvas.height = height;
  33364. }
  33365. return canvas;
  33366. };
  33367. [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) {
  33368. extend(CRp, props);
  33369. });
  33370. var renderer = [{
  33371. name: 'null',
  33372. impl: NullRenderer
  33373. }, {
  33374. name: 'base',
  33375. impl: BR
  33376. }, {
  33377. name: 'canvas',
  33378. impl: CR
  33379. }];
  33380. var incExts = [{
  33381. type: 'layout',
  33382. extensions: layout
  33383. }, {
  33384. type: 'renderer',
  33385. extensions: renderer
  33386. }];
  33387. // registered extensions to cytoscape, indexed by name
  33388. var extensions = {};
  33389. // registered modules for extensions, indexed by name
  33390. var modules = {};
  33391. function setExtension(type, name, registrant) {
  33392. var ext = registrant;
  33393. var overrideErr = function overrideErr(field) {
  33394. warn('Can not register `' + name + '` for `' + type + '` since `' + field + '` already exists in the prototype and can not be overridden');
  33395. };
  33396. if (type === 'core') {
  33397. if (Core.prototype[name]) {
  33398. return overrideErr(name);
  33399. } else {
  33400. Core.prototype[name] = registrant;
  33401. }
  33402. } else if (type === 'collection') {
  33403. if (Collection.prototype[name]) {
  33404. return overrideErr(name);
  33405. } else {
  33406. Collection.prototype[name] = registrant;
  33407. }
  33408. } else if (type === 'layout') {
  33409. // fill in missing layout functions in the prototype
  33410. var Layout = function Layout(options) {
  33411. this.options = options;
  33412. registrant.call(this, options);
  33413. // make sure layout has _private for use w/ std apis like .on()
  33414. if (!plainObject(this._private)) {
  33415. this._private = {};
  33416. }
  33417. this._private.cy = options.cy;
  33418. this._private.listeners = [];
  33419. this.createEmitter();
  33420. };
  33421. var layoutProto = Layout.prototype = Object.create(registrant.prototype);
  33422. var optLayoutFns = [];
  33423. for (var i = 0; i < optLayoutFns.length; i++) {
  33424. var fnName = optLayoutFns[i];
  33425. layoutProto[fnName] = layoutProto[fnName] || function () {
  33426. return this;
  33427. };
  33428. }
  33429. // either .start() or .run() is defined, so autogen the other
  33430. if (layoutProto.start && !layoutProto.run) {
  33431. layoutProto.run = function () {
  33432. this.start();
  33433. return this;
  33434. };
  33435. } else if (!layoutProto.start && layoutProto.run) {
  33436. layoutProto.start = function () {
  33437. this.run();
  33438. return this;
  33439. };
  33440. }
  33441. var regStop = registrant.prototype.stop;
  33442. layoutProto.stop = function () {
  33443. var opts = this.options;
  33444. if (opts && opts.animate) {
  33445. var anis = this.animations;
  33446. if (anis) {
  33447. for (var _i = 0; _i < anis.length; _i++) {
  33448. anis[_i].stop();
  33449. }
  33450. }
  33451. }
  33452. if (regStop) {
  33453. regStop.call(this);
  33454. } else {
  33455. this.emit('layoutstop');
  33456. }
  33457. return this;
  33458. };
  33459. if (!layoutProto.destroy) {
  33460. layoutProto.destroy = function () {
  33461. return this;
  33462. };
  33463. }
  33464. layoutProto.cy = function () {
  33465. return this._private.cy;
  33466. };
  33467. var getCy = function getCy(layout) {
  33468. return layout._private.cy;
  33469. };
  33470. var emitterOpts = {
  33471. addEventFields: function addEventFields(layout, evt) {
  33472. evt.layout = layout;
  33473. evt.cy = getCy(layout);
  33474. evt.target = layout;
  33475. },
  33476. bubble: function bubble() {
  33477. return true;
  33478. },
  33479. parent: function parent(layout) {
  33480. return getCy(layout);
  33481. }
  33482. };
  33483. extend(layoutProto, {
  33484. createEmitter: function createEmitter() {
  33485. this._private.emitter = new Emitter(emitterOpts, this);
  33486. return this;
  33487. },
  33488. emitter: function emitter() {
  33489. return this._private.emitter;
  33490. },
  33491. on: function on(evt, cb) {
  33492. this.emitter().on(evt, cb);
  33493. return this;
  33494. },
  33495. one: function one(evt, cb) {
  33496. this.emitter().one(evt, cb);
  33497. return this;
  33498. },
  33499. once: function once(evt, cb) {
  33500. this.emitter().one(evt, cb);
  33501. return this;
  33502. },
  33503. removeListener: function removeListener(evt, cb) {
  33504. this.emitter().removeListener(evt, cb);
  33505. return this;
  33506. },
  33507. removeAllListeners: function removeAllListeners() {
  33508. this.emitter().removeAllListeners();
  33509. return this;
  33510. },
  33511. emit: function emit(evt, params) {
  33512. this.emitter().emit(evt, params);
  33513. return this;
  33514. }
  33515. });
  33516. define.eventAliasesOn(layoutProto);
  33517. ext = Layout; // replace with our wrapped layout
  33518. } else if (type === 'renderer' && name !== 'null' && name !== 'base') {
  33519. // user registered renderers inherit from base
  33520. var BaseRenderer = getExtension('renderer', 'base');
  33521. var bProto = BaseRenderer.prototype;
  33522. var RegistrantRenderer = registrant;
  33523. var rProto = registrant.prototype;
  33524. var Renderer = function Renderer() {
  33525. BaseRenderer.apply(this, arguments);
  33526. RegistrantRenderer.apply(this, arguments);
  33527. };
  33528. var proto = Renderer.prototype;
  33529. for (var pName in bProto) {
  33530. var pVal = bProto[pName];
  33531. var existsInR = rProto[pName] != null;
  33532. if (existsInR) {
  33533. return overrideErr(pName);
  33534. }
  33535. proto[pName] = pVal; // take impl from base
  33536. }
  33537. for (var _pName in rProto) {
  33538. proto[_pName] = rProto[_pName]; // take impl from registrant
  33539. }
  33540. bProto.clientFunctions.forEach(function (name) {
  33541. proto[name] = proto[name] || function () {
  33542. error('Renderer does not implement `renderer.' + name + '()` on its prototype');
  33543. };
  33544. });
  33545. ext = Renderer;
  33546. } else if (type === '__proto__' || type === 'constructor' || type === 'prototype') {
  33547. // to avoid potential prototype pollution
  33548. return error(type + ' is an illegal type to be registered, possibly lead to prototype pollutions');
  33549. }
  33550. return setMap({
  33551. map: extensions,
  33552. keys: [type, name],
  33553. value: ext
  33554. });
  33555. }
  33556. function getExtension(type, name) {
  33557. return getMap({
  33558. map: extensions,
  33559. keys: [type, name]
  33560. });
  33561. }
  33562. function setModule(type, name, moduleType, moduleName, registrant) {
  33563. return setMap({
  33564. map: modules,
  33565. keys: [type, name, moduleType, moduleName],
  33566. value: registrant
  33567. });
  33568. }
  33569. function getModule(type, name, moduleType, moduleName) {
  33570. return getMap({
  33571. map: modules,
  33572. keys: [type, name, moduleType, moduleName]
  33573. });
  33574. }
  33575. var extension = function extension() {
  33576. // e.g. extension('renderer', 'svg')
  33577. if (arguments.length === 2) {
  33578. return getExtension.apply(null, arguments);
  33579. }
  33580. // e.g. extension('renderer', 'svg', { ... })
  33581. else if (arguments.length === 3) {
  33582. return setExtension.apply(null, arguments);
  33583. }
  33584. // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse')
  33585. else if (arguments.length === 4) {
  33586. return getModule.apply(null, arguments);
  33587. }
  33588. // e.g. extension('renderer', 'svg', 'nodeShape', 'ellipse', { ... })
  33589. else if (arguments.length === 5) {
  33590. return setModule.apply(null, arguments);
  33591. } else {
  33592. error('Invalid extension access syntax');
  33593. }
  33594. };
  33595. // allows a core instance to access extensions internally
  33596. Core.prototype.extension = extension;
  33597. // included extensions
  33598. incExts.forEach(function (group) {
  33599. group.extensions.forEach(function (ext) {
  33600. setExtension(group.type, ext.name, ext.impl);
  33601. });
  33602. });
  33603. // a dummy stylesheet object that doesn't need a reference to the core
  33604. // (useful for init)
  33605. var _Stylesheet = function Stylesheet() {
  33606. if (!(this instanceof _Stylesheet)) {
  33607. return new _Stylesheet();
  33608. }
  33609. this.length = 0;
  33610. };
  33611. var sheetfn = _Stylesheet.prototype;
  33612. sheetfn.instanceString = function () {
  33613. return 'stylesheet';
  33614. };
  33615. // just store the selector to be parsed later
  33616. sheetfn.selector = function (selector) {
  33617. var i = this.length++;
  33618. this[i] = {
  33619. selector: selector,
  33620. properties: []
  33621. };
  33622. return this; // chaining
  33623. };
  33624. // just store the property to be parsed later
  33625. sheetfn.css = function (name, value) {
  33626. var i = this.length - 1;
  33627. if (string(name)) {
  33628. this[i].properties.push({
  33629. name: name,
  33630. value: value
  33631. });
  33632. } else if (plainObject(name)) {
  33633. var map = name;
  33634. var propNames = Object.keys(map);
  33635. for (var j = 0; j < propNames.length; j++) {
  33636. var key = propNames[j];
  33637. var mapVal = map[key];
  33638. if (mapVal == null) {
  33639. continue;
  33640. }
  33641. var prop = _Style.properties[key] || _Style.properties[dash2camel(key)];
  33642. if (prop == null) {
  33643. continue;
  33644. }
  33645. var _name = prop.name;
  33646. var _value = mapVal;
  33647. this[i].properties.push({
  33648. name: _name,
  33649. value: _value
  33650. });
  33651. }
  33652. }
  33653. return this; // chaining
  33654. };
  33655. sheetfn.style = sheetfn.css;
  33656. // generate a real style object from the dummy stylesheet
  33657. sheetfn.generateStyle = function (cy) {
  33658. var style = new _Style(cy);
  33659. return this.appendToStyle(style);
  33660. };
  33661. // append a dummy stylesheet object on a real style object
  33662. sheetfn.appendToStyle = function (style) {
  33663. for (var i = 0; i < this.length; i++) {
  33664. var context = this[i];
  33665. var selector = context.selector;
  33666. var props = context.properties;
  33667. style.selector(selector); // apply selector
  33668. for (var j = 0; j < props.length; j++) {
  33669. var prop = props[j];
  33670. style.css(prop.name, prop.value); // apply property
  33671. }
  33672. }
  33673. return style;
  33674. };
  33675. var version = "3.33.2";
  33676. var cytoscape = function cytoscape(options) {
  33677. // if no options specified, use default
  33678. if (options === undefined) {
  33679. options = {};
  33680. }
  33681. // create instance
  33682. if (plainObject(options)) {
  33683. return new Core(options);
  33684. }
  33685. // allow for registration of extensions
  33686. else if (string(options)) {
  33687. return extension.apply(extension, arguments);
  33688. }
  33689. };
  33690. // e.g. cytoscape.use( require('cytoscape-foo'), bar )
  33691. cytoscape.use = function (ext) {
  33692. var args = Array.prototype.slice.call(arguments, 1); // args to pass to ext
  33693. args.unshift(cytoscape); // cytoscape is first arg to ext
  33694. ext.apply(null, args);
  33695. return this;
  33696. };
  33697. cytoscape.warnings = function (bool) {
  33698. return warnings(bool);
  33699. };
  33700. // replaced by build system
  33701. cytoscape.version = version;
  33702. // expose public apis (mostly for extensions)
  33703. cytoscape.stylesheet = cytoscape.Stylesheet = _Stylesheet;
  33704. export { cytoscape as default };