index.js 511 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var RBush = require('rbush/rbush.js');
  4. var util = require('@antv/util');
  5. var d3 = require('d3-color');
  6. var glMatrix = require('gl-matrix');
  7. var gMath = require('@antv/g-math');
  8. var EventEmitter = require('eventemitter3');
  9. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  10. var RBush__default = /*#__PURE__*/_interopDefaultLegacy(RBush);
  11. var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
  12. /**
  13. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type
  14. */
  15. (function (PropertySyntax) {
  16. /**
  17. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#coordinate
  18. */
  19. PropertySyntax["COORDINATE"] = "<coordinate>";
  20. /**
  21. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#color
  22. */
  23. PropertySyntax["COLOR"] = "<color>";
  24. /**
  25. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#paint
  26. */
  27. PropertySyntax["PAINT"] = "<paint>";
  28. /**
  29. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number
  30. */
  31. PropertySyntax["NUMBER"] = "<number>";
  32. /**
  33. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/angle
  34. */
  35. PropertySyntax["ANGLE"] = "<angle>";
  36. /**
  37. * <number> with range 0..1
  38. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#opacity_value
  39. */
  40. PropertySyntax["OPACITY_VALUE"] = "<opacity-value>";
  41. /**
  42. * <number> with range 0..Infinity
  43. */
  44. PropertySyntax["SHADOW_BLUR"] = "<shadow-blur>";
  45. /**
  46. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#length
  47. */
  48. PropertySyntax["LENGTH"] = "<length>";
  49. /**
  50. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage
  51. */
  52. PropertySyntax["PERCENTAGE"] = "<percentage>";
  53. PropertySyntax["LENGTH_PERCENTAGE"] = "<length> | <percentage>";
  54. PropertySyntax["LENGTH_PERCENTAGE_12"] = "[<length> | <percentage>]{1,2}";
  55. /**
  56. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin#formal_syntax
  57. */
  58. PropertySyntax["LENGTH_PERCENTAGE_14"] = "[<length> | <percentage>]{1,4}";
  59. /**
  60. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts
  61. */
  62. PropertySyntax["LIST_OF_POINTS"] = "<list-of-points>";
  63. PropertySyntax["PATH"] = "<path>";
  64. /**
  65. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter#formal_syntax
  66. */
  67. PropertySyntax["FILTER"] = "<filter>";
  68. PropertySyntax["Z_INDEX"] = "<z-index>";
  69. PropertySyntax["OFFSET_DISTANCE"] = "<offset-distance>";
  70. PropertySyntax["DEFINED_PATH"] = "<defined-path>";
  71. PropertySyntax["MARKER"] = "<marker>";
  72. PropertySyntax["TRANSFORM"] = "<transform>";
  73. PropertySyntax["TRANSFORM_ORIGIN"] = "<transform-origin>";
  74. PropertySyntax["TEXT"] = "<text>";
  75. PropertySyntax["TEXT_TRANSFORM"] = "<text-transform>";
  76. })(exports.PropertySyntax || (exports.PropertySyntax = {}));
  77. function _regeneratorRuntime() {
  78. _regeneratorRuntime = function () {
  79. return exports;
  80. };
  81. var exports = {},
  82. Op = Object.prototype,
  83. hasOwn = Op.hasOwnProperty,
  84. defineProperty = Object.defineProperty || function (obj, key, desc) {
  85. obj[key] = desc.value;
  86. },
  87. $Symbol = "function" == typeof Symbol ? Symbol : {},
  88. iteratorSymbol = $Symbol.iterator || "@@iterator",
  89. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  90. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  91. function define(obj, key, value) {
  92. return Object.defineProperty(obj, key, {
  93. value: value,
  94. enumerable: !0,
  95. configurable: !0,
  96. writable: !0
  97. }), obj[key];
  98. }
  99. try {
  100. define({}, "");
  101. } catch (err) {
  102. define = function (obj, key, value) {
  103. return obj[key] = value;
  104. };
  105. }
  106. function wrap(innerFn, outerFn, self, tryLocsList) {
  107. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  108. generator = Object.create(protoGenerator.prototype),
  109. context = new Context(tryLocsList || []);
  110. return defineProperty(generator, "_invoke", {
  111. value: makeInvokeMethod(innerFn, self, context)
  112. }), generator;
  113. }
  114. function tryCatch(fn, obj, arg) {
  115. try {
  116. return {
  117. type: "normal",
  118. arg: fn.call(obj, arg)
  119. };
  120. } catch (err) {
  121. return {
  122. type: "throw",
  123. arg: err
  124. };
  125. }
  126. }
  127. exports.wrap = wrap;
  128. var ContinueSentinel = {};
  129. function Generator() {}
  130. function GeneratorFunction() {}
  131. function GeneratorFunctionPrototype() {}
  132. var IteratorPrototype = {};
  133. define(IteratorPrototype, iteratorSymbol, function () {
  134. return this;
  135. });
  136. var getProto = Object.getPrototypeOf,
  137. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  138. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  139. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  140. function defineIteratorMethods(prototype) {
  141. ["next", "throw", "return"].forEach(function (method) {
  142. define(prototype, method, function (arg) {
  143. return this._invoke(method, arg);
  144. });
  145. });
  146. }
  147. function AsyncIterator(generator, PromiseImpl) {
  148. function invoke(method, arg, resolve, reject) {
  149. var record = tryCatch(generator[method], generator, arg);
  150. if ("throw" !== record.type) {
  151. var result = record.arg,
  152. value = result.value;
  153. return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  154. invoke("next", value, resolve, reject);
  155. }, function (err) {
  156. invoke("throw", err, resolve, reject);
  157. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  158. result.value = unwrapped, resolve(result);
  159. }, function (error) {
  160. return invoke("throw", error, resolve, reject);
  161. });
  162. }
  163. reject(record.arg);
  164. }
  165. var previousPromise;
  166. defineProperty(this, "_invoke", {
  167. value: function (method, arg) {
  168. function callInvokeWithMethodAndArg() {
  169. return new PromiseImpl(function (resolve, reject) {
  170. invoke(method, arg, resolve, reject);
  171. });
  172. }
  173. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  174. }
  175. });
  176. }
  177. function makeInvokeMethod(innerFn, self, context) {
  178. var state = "suspendedStart";
  179. return function (method, arg) {
  180. if ("executing" === state) throw new Error("Generator is already running");
  181. if ("completed" === state) {
  182. if ("throw" === method) throw arg;
  183. return doneResult();
  184. }
  185. for (context.method = method, context.arg = arg;;) {
  186. var delegate = context.delegate;
  187. if (delegate) {
  188. var delegateResult = maybeInvokeDelegate(delegate, context);
  189. if (delegateResult) {
  190. if (delegateResult === ContinueSentinel) continue;
  191. return delegateResult;
  192. }
  193. }
  194. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  195. if ("suspendedStart" === state) throw state = "completed", context.arg;
  196. context.dispatchException(context.arg);
  197. } else "return" === context.method && context.abrupt("return", context.arg);
  198. state = "executing";
  199. var record = tryCatch(innerFn, self, context);
  200. if ("normal" === record.type) {
  201. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  202. return {
  203. value: record.arg,
  204. done: context.done
  205. };
  206. }
  207. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  208. }
  209. };
  210. }
  211. function maybeInvokeDelegate(delegate, context) {
  212. var methodName = context.method,
  213. method = delegate.iterator[methodName];
  214. if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
  215. var record = tryCatch(method, delegate.iterator, context.arg);
  216. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  217. var info = record.arg;
  218. return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
  219. }
  220. function pushTryEntry(locs) {
  221. var entry = {
  222. tryLoc: locs[0]
  223. };
  224. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  225. }
  226. function resetTryEntry(entry) {
  227. var record = entry.completion || {};
  228. record.type = "normal", delete record.arg, entry.completion = record;
  229. }
  230. function Context(tryLocsList) {
  231. this.tryEntries = [{
  232. tryLoc: "root"
  233. }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
  234. }
  235. function values(iterable) {
  236. if (iterable) {
  237. var iteratorMethod = iterable[iteratorSymbol];
  238. if (iteratorMethod) return iteratorMethod.call(iterable);
  239. if ("function" == typeof iterable.next) return iterable;
  240. if (!isNaN(iterable.length)) {
  241. var i = -1,
  242. next = function next() {
  243. for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  244. return next.value = undefined, next.done = !0, next;
  245. };
  246. return next.next = next;
  247. }
  248. }
  249. return {
  250. next: doneResult
  251. };
  252. }
  253. function doneResult() {
  254. return {
  255. value: undefined,
  256. done: !0
  257. };
  258. }
  259. return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
  260. value: GeneratorFunctionPrototype,
  261. configurable: !0
  262. }), defineProperty(GeneratorFunctionPrototype, "constructor", {
  263. value: GeneratorFunction,
  264. configurable: !0
  265. }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  266. var ctor = "function" == typeof genFun && genFun.constructor;
  267. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  268. }, exports.mark = function (genFun) {
  269. return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
  270. }, exports.awrap = function (arg) {
  271. return {
  272. __await: arg
  273. };
  274. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  275. return this;
  276. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  277. void 0 === PromiseImpl && (PromiseImpl = Promise);
  278. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  279. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  280. return result.done ? result.value : iter.next();
  281. });
  282. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  283. return this;
  284. }), define(Gp, "toString", function () {
  285. return "[object Generator]";
  286. }), exports.keys = function (val) {
  287. var object = Object(val),
  288. keys = [];
  289. for (var key in object) keys.push(key);
  290. return keys.reverse(), function next() {
  291. for (; keys.length;) {
  292. var key = keys.pop();
  293. if (key in object) return next.value = key, next.done = !1, next;
  294. }
  295. return next.done = !0, next;
  296. };
  297. }, exports.values = values, Context.prototype = {
  298. constructor: Context,
  299. reset: function (skipTempReset) {
  300. if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
  301. },
  302. stop: function () {
  303. this.done = !0;
  304. var rootRecord = this.tryEntries[0].completion;
  305. if ("throw" === rootRecord.type) throw rootRecord.arg;
  306. return this.rval;
  307. },
  308. dispatchException: function (exception) {
  309. if (this.done) throw exception;
  310. var context = this;
  311. function handle(loc, caught) {
  312. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  313. }
  314. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  315. var entry = this.tryEntries[i],
  316. record = entry.completion;
  317. if ("root" === entry.tryLoc) return handle("end");
  318. if (entry.tryLoc <= this.prev) {
  319. var hasCatch = hasOwn.call(entry, "catchLoc"),
  320. hasFinally = hasOwn.call(entry, "finallyLoc");
  321. if (hasCatch && hasFinally) {
  322. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  323. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  324. } else if (hasCatch) {
  325. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  326. } else {
  327. if (!hasFinally) throw new Error("try statement without catch or finally");
  328. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  329. }
  330. }
  331. }
  332. },
  333. abrupt: function (type, arg) {
  334. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  335. var entry = this.tryEntries[i];
  336. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  337. var finallyEntry = entry;
  338. break;
  339. }
  340. }
  341. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  342. var record = finallyEntry ? finallyEntry.completion : {};
  343. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  344. },
  345. complete: function (record, afterLoc) {
  346. if ("throw" === record.type) throw record.arg;
  347. return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
  348. },
  349. finish: function (finallyLoc) {
  350. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  351. var entry = this.tryEntries[i];
  352. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  353. }
  354. },
  355. catch: function (tryLoc) {
  356. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  357. var entry = this.tryEntries[i];
  358. if (entry.tryLoc === tryLoc) {
  359. var record = entry.completion;
  360. if ("throw" === record.type) {
  361. var thrown = record.arg;
  362. resetTryEntry(entry);
  363. }
  364. return thrown;
  365. }
  366. }
  367. throw new Error("illegal catch attempt");
  368. },
  369. delegateYield: function (iterable, resultName, nextLoc) {
  370. return this.delegate = {
  371. iterator: values(iterable),
  372. resultName: resultName,
  373. nextLoc: nextLoc
  374. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  375. }
  376. }, exports;
  377. }
  378. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  379. try {
  380. var info = gen[key](arg);
  381. var value = info.value;
  382. } catch (error) {
  383. reject(error);
  384. return;
  385. }
  386. if (info.done) {
  387. resolve(value);
  388. } else {
  389. Promise.resolve(value).then(_next, _throw);
  390. }
  391. }
  392. function _asyncToGenerator(fn) {
  393. return function () {
  394. var self = this,
  395. args = arguments;
  396. return new Promise(function (resolve, reject) {
  397. var gen = fn.apply(self, args);
  398. function _next(value) {
  399. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  400. }
  401. function _throw(err) {
  402. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  403. }
  404. _next(undefined);
  405. });
  406. };
  407. }
  408. function _defineProperties(target, props) {
  409. for (var i = 0; i < props.length; i++) {
  410. var descriptor = props[i];
  411. descriptor.enumerable = descriptor.enumerable || false;
  412. descriptor.configurable = true;
  413. if ("value" in descriptor) descriptor.writable = true;
  414. Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  415. }
  416. }
  417. function _createClass(Constructor, protoProps, staticProps) {
  418. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  419. if (staticProps) _defineProperties(Constructor, staticProps);
  420. Object.defineProperty(Constructor, "prototype", {
  421. writable: false
  422. });
  423. return Constructor;
  424. }
  425. function _extends() {
  426. _extends = Object.assign ? Object.assign.bind() : function (target) {
  427. for (var i = 1; i < arguments.length; i++) {
  428. var source = arguments[i];
  429. for (var key in source) {
  430. if (Object.prototype.hasOwnProperty.call(source, key)) {
  431. target[key] = source[key];
  432. }
  433. }
  434. }
  435. return target;
  436. };
  437. return _extends.apply(this, arguments);
  438. }
  439. function _inheritsLoose(subClass, superClass) {
  440. subClass.prototype = Object.create(superClass.prototype);
  441. subClass.prototype.constructor = subClass;
  442. _setPrototypeOf(subClass, superClass);
  443. }
  444. function _setPrototypeOf(o, p) {
  445. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  446. o.__proto__ = p;
  447. return o;
  448. };
  449. return _setPrototypeOf(o, p);
  450. }
  451. function _objectWithoutPropertiesLoose(source, excluded) {
  452. if (source == null) return {};
  453. var target = {};
  454. var sourceKeys = Object.keys(source);
  455. var key, i;
  456. for (i = 0; i < sourceKeys.length; i++) {
  457. key = sourceKeys[i];
  458. if (excluded.indexOf(key) >= 0) continue;
  459. target[key] = source[key];
  460. }
  461. return target;
  462. }
  463. function _assertThisInitialized(self) {
  464. if (self === void 0) {
  465. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  466. }
  467. return self;
  468. }
  469. function _unsupportedIterableToArray(o, minLen) {
  470. if (!o) return;
  471. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  472. var n = Object.prototype.toString.call(o).slice(8, -1);
  473. if (n === "Object" && o.constructor) n = o.constructor.name;
  474. if (n === "Map" || n === "Set") return Array.from(o);
  475. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  476. }
  477. function _arrayLikeToArray(arr, len) {
  478. if (len == null || len > arr.length) len = arr.length;
  479. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  480. return arr2;
  481. }
  482. function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  483. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  484. if (it) return (it = it.call(o)).next.bind(it);
  485. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  486. if (it) o = it;
  487. var i = 0;
  488. return function () {
  489. if (i >= o.length) return {
  490. done: true
  491. };
  492. return {
  493. done: false,
  494. value: o[i++]
  495. };
  496. };
  497. }
  498. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  499. }
  500. function _toPrimitive(input, hint) {
  501. if (typeof input !== "object" || input === null) return input;
  502. var prim = input[Symbol.toPrimitive];
  503. if (prim !== undefined) {
  504. var res = prim.call(input, hint || "default");
  505. if (typeof res !== "object") return res;
  506. throw new TypeError("@@toPrimitive must return a primitive value.");
  507. }
  508. return (hint === "string" ? String : Number)(input);
  509. }
  510. function _toPropertyKey(arg) {
  511. var key = _toPrimitive(arg, "string");
  512. return typeof key === "symbol" ? key : String(key);
  513. }
  514. // These units are iterated through, so be careful when adding or changing the
  515. (function (UnitType) {
  516. UnitType[UnitType["kUnknown"] = 0] = "kUnknown";
  517. UnitType[UnitType["kNumber"] = 1] = "kNumber";
  518. UnitType[UnitType["kPercentage"] = 2] = "kPercentage";
  519. // Length units
  520. UnitType[UnitType["kEms"] = 3] = "kEms";
  521. // kExs,
  522. UnitType[UnitType["kPixels"] = 4] = "kPixels";
  523. // kCentimeters,
  524. // kMillimeters,
  525. // kInches,
  526. // kPoints,
  527. // kPicas,
  528. // kQuarterMillimeters,
  529. // https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
  530. //
  531. // See also IsViewportPercentageLength.
  532. // kViewportWidth,
  533. // kViewportHeight,
  534. // kViewportInlineSize,
  535. // kViewportBlockSize,
  536. // kViewportMin,
  537. // kViewportMax,
  538. // kSmallViewportWidth,
  539. // kSmallViewportHeight,
  540. // kSmallViewportInlineSize,
  541. // kSmallViewportBlockSize,
  542. // kSmallViewportMin,
  543. // kSmallViewportMax,
  544. // kLargeViewportWidth,
  545. // kLargeViewportHeight,
  546. // kLargeViewportInlineSize,
  547. // kLargeViewportBlockSize,
  548. // kLargeViewportMin,
  549. // kLargeViewportMax,
  550. // kDynamicViewportWidth,
  551. // kDynamicViewportHeight,
  552. // kDynamicViewportInlineSize,
  553. // kDynamicViewportBlockSize,
  554. // kDynamicViewportMin,
  555. // kDynamicViewportMax,
  556. // https://drafts.csswg.org/css-contain-3/#container-lengths
  557. //
  558. // See also IsContainerPercentageLength.
  559. // kContainerWidth,
  560. // kContainerHeight,
  561. // kContainerInlineSize,
  562. // kContainerBlockSize,
  563. // kContainerMin,
  564. // kContainerMax,
  565. UnitType[UnitType["kRems"] = 5] = "kRems";
  566. // kChs,
  567. // kUserUnits, // The SVG term for unitless lengths
  568. // Angle units
  569. UnitType[UnitType["kDegrees"] = 6] = "kDegrees";
  570. UnitType[UnitType["kRadians"] = 7] = "kRadians";
  571. UnitType[UnitType["kGradians"] = 8] = "kGradians";
  572. UnitType[UnitType["kTurns"] = 9] = "kTurns";
  573. // Time units
  574. UnitType[UnitType["kMilliseconds"] = 10] = "kMilliseconds";
  575. UnitType[UnitType["kSeconds"] = 11] = "kSeconds";
  576. // kHertz,
  577. // kKilohertz,
  578. // Resolution
  579. // kDotsPerPixel,
  580. // kDotsPerInch,
  581. // kDotsPerCentimeter,
  582. // Other units
  583. // kFraction,
  584. UnitType[UnitType["kInteger"] = 12] = "kInteger";
  585. // This value is used to handle quirky margins in reflow roots (body, td,
  586. // and th) like WinIE. The basic idea is that a stylesheet can use the value
  587. // __qem (for quirky em) instead of em. When the quirky value is used, if
  588. // you're in quirks mode, the margin will collapse away inside a table cell.
  589. // This quirk is specified in the HTML spec but our impl is different.
  590. // TODO: Remove this. crbug.com/443952
  591. // kQuirkyEms,
  592. })(exports.UnitType || (exports.UnitType = {}));
  593. var UnitCategory;
  594. (function (UnitCategory) {
  595. UnitCategory[UnitCategory["kUNumber"] = 0] = "kUNumber";
  596. UnitCategory[UnitCategory["kUPercent"] = 1] = "kUPercent";
  597. UnitCategory[UnitCategory["kULength"] = 2] = "kULength";
  598. UnitCategory[UnitCategory["kUAngle"] = 3] = "kUAngle";
  599. UnitCategory[UnitCategory["kUTime"] = 4] = "kUTime";
  600. // kUFrequency,
  601. // kUResolution,
  602. UnitCategory[UnitCategory["kUOther"] = 5] = "kUOther";
  603. })(UnitCategory || (UnitCategory = {}));
  604. var ValueRange;
  605. (function (ValueRange) {
  606. ValueRange[ValueRange["kAll"] = 0] = "kAll";
  607. ValueRange[ValueRange["kNonNegative"] = 1] = "kNonNegative";
  608. ValueRange[ValueRange["kInteger"] = 2] = "kInteger";
  609. ValueRange[ValueRange["kNonNegativeInteger"] = 3] = "kNonNegativeInteger";
  610. ValueRange[ValueRange["kPositiveInteger"] = 4] = "kPositiveInteger";
  611. })(ValueRange || (ValueRange = {}));
  612. var Nested;
  613. (function (Nested) {
  614. Nested[Nested["kYes"] = 0] = "kYes";
  615. Nested[Nested["kNo"] = 1] = "kNo";
  616. })(Nested || (Nested = {}));
  617. var ParenLess;
  618. (function (ParenLess) {
  619. ParenLess[ParenLess["kYes"] = 0] = "kYes";
  620. ParenLess[ParenLess["kNo"] = 1] = "kNo";
  621. })(ParenLess || (ParenLess = {}));
  622. // This file specifies the unit strings used in CSSPrimitiveValues.
  623. var data = [{
  624. name: 'em',
  625. unit_type: exports.UnitType.kEms
  626. },
  627. // {
  628. // name: 'ex',
  629. // unit_type: UnitType.kExs,
  630. // },
  631. {
  632. name: 'px',
  633. unit_type: exports.UnitType.kPixels
  634. },
  635. // {
  636. // name: "cm",
  637. // unit_type: UnitType.kCentimeters,
  638. // },
  639. // {
  640. // name: "mm",
  641. // unit_type: UnitType.kMillimeters,
  642. // },
  643. // {
  644. // name: "q",
  645. // unit_type: UnitType.kQuarterMillimeters,
  646. // },
  647. // {
  648. // name: "in",
  649. // unit_type: UnitType.kInches,
  650. // },
  651. // {
  652. // name: "pt",
  653. // unit_type: UnitType.kPoints,
  654. // },
  655. // {
  656. // name: "pc",
  657. // unit_type: UnitType.kPicas,
  658. // },
  659. {
  660. name: 'deg',
  661. unit_type: exports.UnitType.kDegrees
  662. }, {
  663. name: 'rad',
  664. unit_type: exports.UnitType.kRadians
  665. }, {
  666. name: 'grad',
  667. unit_type: exports.UnitType.kGradians
  668. }, {
  669. name: 'ms',
  670. unit_type: exports.UnitType.kMilliseconds
  671. }, {
  672. name: 's',
  673. unit_type: exports.UnitType.kSeconds
  674. },
  675. // {
  676. // name: "hz",
  677. // unit_type: UnitType.kHertz,
  678. // },
  679. // {
  680. // name: "khz",
  681. // unit_type: UnitType.kKilohertz,
  682. // },
  683. // {
  684. // name: "dpi",
  685. // unit_type: "kDotsPerInch",
  686. // },
  687. // {
  688. // name: "dpcm",
  689. // unit_type: "kDotsPerCentimeter",
  690. // },
  691. // {
  692. // name: "dppx",
  693. // unit_type: "kDotsPerPixel",
  694. // },
  695. // {
  696. // name: "x",
  697. // unit_type: "kDotsPerPixel",
  698. // },
  699. // {
  700. // name: "vw",
  701. // unit_type: "kViewportWidth",
  702. // },
  703. // {
  704. // name: "vh",
  705. // unit_type: "kViewportHeight",
  706. // },
  707. // {
  708. // name: "vi",
  709. // unit_type: "kViewportInlineSize",
  710. // },
  711. // {
  712. // name: "vb",
  713. // unit_type: "kViewportBlockSize",
  714. // },
  715. // {
  716. // name: "vmin",
  717. // unit_type: UnitType.kViewportMin,
  718. // },
  719. // {
  720. // name: "vmax",
  721. // unit_type: UnitType.kViewportMax,
  722. // },
  723. // {
  724. // name: "svw",
  725. // unit_type: "kSmallViewportWidth",
  726. // },
  727. // {
  728. // name: "svh",
  729. // unit_type: "kSmallViewportHeight",
  730. // },
  731. // {
  732. // name: "svi",
  733. // unit_type: "kSmallViewportInlineSize",
  734. // },
  735. // {
  736. // name: "svb",
  737. // unit_type: "kSmallViewportBlockSize",
  738. // },
  739. // {
  740. // name: "svmin",
  741. // unit_type: "kSmallViewportMin",
  742. // },
  743. // {
  744. // name: "svmax",
  745. // unit_type: "kSmallViewportMax",
  746. // },
  747. // {
  748. // name: "lvw",
  749. // unit_type: "kLargeViewportWidth",
  750. // },
  751. // {
  752. // name: "lvh",
  753. // unit_type: "kLargeViewportHeight",
  754. // },
  755. // {
  756. // name: "lvi",
  757. // unit_type: "kLargeViewportInlineSize",
  758. // },
  759. // {
  760. // name: "lvb",
  761. // unit_type: "kLargeViewportBlockSize",
  762. // },
  763. // {
  764. // name: "lvmin",
  765. // unit_type: UnitType.kLargeViewportMin,
  766. // },
  767. // {
  768. // name: "lvmax",
  769. // unit_type: UnitType.kLargeViewportMax,
  770. // },
  771. // {
  772. // name: "dvw",
  773. // unit_type: UnitType.kDynamicViewportWidth,
  774. // },
  775. // {
  776. // name: "dvh",
  777. // unit_type: UnitType.kDynamicViewportHeight,
  778. // },
  779. // {
  780. // name: "dvi",
  781. // unit_type: UnitType.kDynamicViewportInlineSize,
  782. // },
  783. // {
  784. // name: "dvb",
  785. // unit_type: UnitType.kDynamicViewportBlockSize,
  786. // },
  787. // {
  788. // name: "dvmin",
  789. // unit_type: UnitType.kDynamicViewportMin,
  790. // },
  791. // {
  792. // name: "dvmax",
  793. // unit_type: UnitType.kDynamicViewportMax,
  794. // },
  795. // {
  796. // name: "cqw",
  797. // unit_type: UnitType.kContainerWidth,
  798. // },
  799. // {
  800. // name: "cqh",
  801. // unit_type: UnitType.kContainerHeight,
  802. // },
  803. // {
  804. // name: "cqi",
  805. // unit_type: UnitType.kContainerInlineSize,
  806. // },
  807. // {
  808. // name: "cqb",
  809. // unit_type: UnitType.kContainerBlockSize,
  810. // },
  811. // {
  812. // name: "cqmin",
  813. // unit_type: UnitType.kContainerMin,
  814. // },
  815. // {
  816. // name: "cqmax",
  817. // unit_type: UnitType.kContainerMax,
  818. // },
  819. {
  820. name: 'rem',
  821. unit_type: exports.UnitType.kRems
  822. },
  823. // {
  824. // name: 'fr',
  825. // unit_type: UnitType.kFraction,
  826. // },
  827. {
  828. name: 'turn',
  829. unit_type: exports.UnitType.kTurns
  830. }
  831. // {
  832. // name: 'ch',
  833. // unit_type: UnitType.kChs,
  834. // },
  835. // {
  836. // name: '__qem',
  837. // unit_type: UnitType.kQuirkyEms,
  838. // },
  839. ];
  840. var CSSStyleValueType;
  841. (function (CSSStyleValueType) {
  842. CSSStyleValueType[CSSStyleValueType["kUnknownType"] = 0] = "kUnknownType";
  843. CSSStyleValueType[CSSStyleValueType["kUnparsedType"] = 1] = "kUnparsedType";
  844. CSSStyleValueType[CSSStyleValueType["kKeywordType"] = 2] = "kKeywordType";
  845. // Start of CSSNumericValue subclasses
  846. CSSStyleValueType[CSSStyleValueType["kUnitType"] = 3] = "kUnitType";
  847. CSSStyleValueType[CSSStyleValueType["kSumType"] = 4] = "kSumType";
  848. CSSStyleValueType[CSSStyleValueType["kProductType"] = 5] = "kProductType";
  849. CSSStyleValueType[CSSStyleValueType["kNegateType"] = 6] = "kNegateType";
  850. CSSStyleValueType[CSSStyleValueType["kInvertType"] = 7] = "kInvertType";
  851. CSSStyleValueType[CSSStyleValueType["kMinType"] = 8] = "kMinType";
  852. CSSStyleValueType[CSSStyleValueType["kMaxType"] = 9] = "kMaxType";
  853. CSSStyleValueType[CSSStyleValueType["kClampType"] = 10] = "kClampType";
  854. // End of CSSNumericValue subclasses
  855. CSSStyleValueType[CSSStyleValueType["kTransformType"] = 11] = "kTransformType";
  856. CSSStyleValueType[CSSStyleValueType["kPositionType"] = 12] = "kPositionType";
  857. CSSStyleValueType[CSSStyleValueType["kURLImageType"] = 13] = "kURLImageType";
  858. CSSStyleValueType[CSSStyleValueType["kColorType"] = 14] = "kColorType";
  859. CSSStyleValueType[CSSStyleValueType["kUnsupportedColorType"] = 15] = "kUnsupportedColorType";
  860. })(CSSStyleValueType || (CSSStyleValueType = {}));
  861. // function parseCSSStyleValue(propertyName: string, value: string): CSSStyleValue[] {
  862. // // const propertyId = cssPropertyID(propertyName);
  863. // // if (propertyId === CSSPropertyID.kInvalid) {
  864. // // return [];
  865. // // }
  866. // // const customPropertyName = propertyId === CSSPropertyID.kVariable ? propertyName : null;
  867. // // return fromString(propertyId, customPropertyName, value);
  868. // return [];
  869. // }
  870. var stringToUnitType = function stringToUnitType(name) {
  871. return data.find(function (item) {
  872. return item.name === name;
  873. }).unit_type;
  874. };
  875. var unitFromName = function unitFromName(name) {
  876. if (!name) {
  877. return exports.UnitType.kUnknown;
  878. }
  879. if (name === 'number') {
  880. return exports.UnitType.kNumber;
  881. }
  882. if (name === 'percent' || name === '%') {
  883. return exports.UnitType.kPercentage;
  884. }
  885. return stringToUnitType(name);
  886. };
  887. var unitTypeToUnitCategory = function unitTypeToUnitCategory(type) {
  888. switch (type) {
  889. case exports.UnitType.kNumber:
  890. case exports.UnitType.kInteger:
  891. return UnitCategory.kUNumber;
  892. case exports.UnitType.kPercentage:
  893. return UnitCategory.kUPercent;
  894. case exports.UnitType.kPixels:
  895. // case UnitType.kCentimeters:
  896. // case UnitType.kMillimeters:
  897. // case UnitType.kQuarterMillimeters:
  898. // case UnitType.kInches:
  899. // case UnitType.kPoints:
  900. // case UnitType.kPicas:
  901. // case UnitType.kUserUnits:
  902. return UnitCategory.kULength;
  903. case exports.UnitType.kMilliseconds:
  904. case exports.UnitType.kSeconds:
  905. return UnitCategory.kUTime;
  906. case exports.UnitType.kDegrees:
  907. case exports.UnitType.kRadians:
  908. case exports.UnitType.kGradians:
  909. case exports.UnitType.kTurns:
  910. return UnitCategory.kUAngle;
  911. // case UnitType.kHertz:
  912. // case UnitType.kKilohertz:
  913. // return UnitCategory.kUFrequency;
  914. // case UnitType.kDotsPerPixel:
  915. // case UnitType.kDotsPerInch:
  916. // case UnitType.kDotsPerCentimeter:
  917. // return UnitCategory.kUResolution;
  918. default:
  919. return UnitCategory.kUOther;
  920. }
  921. };
  922. var canonicalUnitTypeForCategory = function canonicalUnitTypeForCategory(category) {
  923. // The canonical unit type is chosen according to the way
  924. // CSSPropertyParser.ValidUnit() chooses the default unit in each category
  925. // (based on unitflags).
  926. switch (category) {
  927. case UnitCategory.kUNumber:
  928. return exports.UnitType.kNumber;
  929. case UnitCategory.kULength:
  930. return exports.UnitType.kPixels;
  931. case UnitCategory.kUPercent:
  932. return exports.UnitType.kPercentage;
  933. // return UnitType.kUnknown; // Cannot convert between numbers and percent.
  934. case UnitCategory.kUTime:
  935. return exports.UnitType.kSeconds;
  936. case UnitCategory.kUAngle:
  937. return exports.UnitType.kDegrees;
  938. // case UnitCategory.kUFrequency:
  939. // return UnitType.kHertz;
  940. // case UnitCategory.kUResolution:
  941. // return UnitType.kDotsPerPixel;
  942. default:
  943. return exports.UnitType.kUnknown;
  944. }
  945. };
  946. /**
  947. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/css_primitive_value.cc#353
  948. */
  949. var conversionToCanonicalUnitsScaleFactor = function conversionToCanonicalUnitsScaleFactor(unit_type) {
  950. var factor = 1.0;
  951. // FIXME: the switch can be replaced by an array of scale factors.
  952. switch (unit_type) {
  953. // These are "canonical" units in their respective categories.
  954. case exports.UnitType.kPixels:
  955. // case UnitType.kUserUnits:
  956. case exports.UnitType.kDegrees:
  957. case exports.UnitType.kSeconds:
  958. // case UnitType.kHertz:
  959. break;
  960. case exports.UnitType.kMilliseconds:
  961. factor = 0.001;
  962. break;
  963. // case UnitType.kCentimeters:
  964. // // factor = kCssPixelsPerCentimeter;
  965. // break;
  966. // case UnitType.kDotsPerCentimeter:
  967. // // factor = 1 / kCssPixelsPerCentimeter;
  968. // break;
  969. // case UnitType.kMillimeters:
  970. // // factor = kCssPixelsPerMillimeter;
  971. // break;
  972. // case UnitType.kQuarterMillimeters:
  973. // // factor = kCssPixelsPerQuarterMillimeter;
  974. // break;
  975. // case UnitType.kInches:
  976. // // factor = kCssPixelsPerInch;
  977. // break;
  978. // case UnitType.kDotsPerInch:
  979. // // factor = 1 / kCssPixelsPerInch;
  980. // break;
  981. // case UnitType.kPoints:
  982. // // factor = kCssPixelsPerPoint;
  983. // break;
  984. // case UnitType.kPicas:
  985. // // factor = kCssPixelsPerPica;
  986. // break;
  987. case exports.UnitType.kRadians:
  988. factor = 180 / Math.PI;
  989. break;
  990. case exports.UnitType.kGradians:
  991. factor = 0.9;
  992. break;
  993. case exports.UnitType.kTurns:
  994. factor = 360;
  995. break;
  996. }
  997. return factor;
  998. };
  999. var unitTypeToString = function unitTypeToString(type) {
  1000. switch (type) {
  1001. case exports.UnitType.kNumber:
  1002. case exports.UnitType.kInteger:
  1003. // case UnitType.kUserUnits:
  1004. return '';
  1005. case exports.UnitType.kPercentage:
  1006. return '%';
  1007. case exports.UnitType.kEms:
  1008. // case UnitType.kQuirkyEms:
  1009. return 'em';
  1010. // case UnitType.kExs:
  1011. // return 'ex';
  1012. case exports.UnitType.kRems:
  1013. return 'rem';
  1014. // case UnitType.kChs:
  1015. // return 'ch';
  1016. case exports.UnitType.kPixels:
  1017. return 'px';
  1018. // case UnitType.kCentimeters:
  1019. // return 'cm';
  1020. // case UnitType.kDotsPerPixel:
  1021. // return 'dppx';
  1022. // case UnitType.kDotsPerInch:
  1023. // return 'dpi';
  1024. // case UnitType.kDotsPerCentimeter:
  1025. // return 'dpcm';
  1026. // case UnitType.kMillimeters:
  1027. // return 'mm';
  1028. // case UnitType.kQuarterMillimeters:
  1029. // return 'q';
  1030. // case UnitType.kInches:
  1031. // return 'in';
  1032. // case UnitType.kPoints:
  1033. // return 'pt';
  1034. // case UnitType.kPicas:
  1035. // return 'pc';
  1036. case exports.UnitType.kDegrees:
  1037. return 'deg';
  1038. case exports.UnitType.kRadians:
  1039. return 'rad';
  1040. case exports.UnitType.kGradians:
  1041. return 'grad';
  1042. case exports.UnitType.kMilliseconds:
  1043. return 'ms';
  1044. case exports.UnitType.kSeconds:
  1045. return 's';
  1046. // case UnitType.kHertz:
  1047. // return 'hz';
  1048. // case UnitType.kKilohertz:
  1049. // return 'khz';
  1050. case exports.UnitType.kTurns:
  1051. return 'turn';
  1052. }
  1053. return '';
  1054. };
  1055. /**
  1056. * CSSStyleValue is the base class for all CSS values accessible from Typed OM.
  1057. * Values that are not yet supported as specific types are also returned as base CSSStyleValues.
  1058. *
  1059. * Spec @see https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects
  1060. * Docs @see https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue
  1061. */
  1062. var CSSStyleValue = /*#__PURE__*/function () {
  1063. function CSSStyleValue() {}
  1064. // static parse(propertyName: string, value: string): CSSStyleValue {
  1065. // return parseCSSStyleValue(propertyName, value)[0];
  1066. // }
  1067. // static parseAll(propertyName: string, value: string): CSSStyleValue[] {
  1068. // return parseCSSStyleValue(propertyName, value);
  1069. // }
  1070. CSSStyleValue.isAngle = function isAngle(unit) {
  1071. return unit === exports.UnitType.kDegrees || unit === exports.UnitType.kRadians || unit === exports.UnitType.kGradians || unit === exports.UnitType.kTurns;
  1072. }
  1073. // static isViewportPercentageLength(type: UnitType) {
  1074. // return type >= UnitType.kViewportWidth && type <= UnitType.kDynamicViewportMax;
  1075. // }
  1076. // static isContainerPercentageLength(type: UnitType) {
  1077. // return type >= UnitType.kContainerWidth && type <= UnitType.kContainerMax;
  1078. // }
  1079. ;
  1080. CSSStyleValue.isLength = function isLength(type) {
  1081. // return (type >= UnitType.kEms && type <= UnitType.kUserUnits) || type == UnitType.kQuirkyEms;
  1082. return type >= exports.UnitType.kEms && type < exports.UnitType.kDegrees;
  1083. };
  1084. CSSStyleValue.isRelativeUnit = function isRelativeUnit(type) {
  1085. return type === exports.UnitType.kPercentage || type === exports.UnitType.kEms ||
  1086. // type === UnitType.kExs ||
  1087. type === exports.UnitType.kRems
  1088. // type === UnitType.kChs ||
  1089. // this.isViewportPercentageLength(type) ||
  1090. // this.isContainerPercentageLength(type)
  1091. ;
  1092. };
  1093. CSSStyleValue.isTime = function isTime(unit) {
  1094. return unit === exports.UnitType.kSeconds || unit === exports.UnitType.kMilliseconds;
  1095. }
  1096. // protected abstract toCSSValue(): CSSValue;
  1097. ;
  1098. var _proto = CSSStyleValue.prototype;
  1099. _proto.toString = function toString() {
  1100. return this.buildCSSText(Nested.kNo, ParenLess.kNo, '');
  1101. };
  1102. _proto.isNumericValue = function isNumericValue() {
  1103. return this.getType() >= CSSStyleValueType.kUnitType && this.getType() <= CSSStyleValueType.kClampType;
  1104. };
  1105. return CSSStyleValue;
  1106. }();
  1107. /**
  1108. * CSSColorValue is the base class used for the various CSS color interfaces.
  1109. *
  1110. * @see https://drafts.css-houdini.org/css-typed-om-1/#colorvalue-objects
  1111. */
  1112. var CSSColorValue = /*#__PURE__*/function (_CSSStyleValue) {
  1113. _inheritsLoose(CSSColorValue, _CSSStyleValue);
  1114. function CSSColorValue(colorSpace) {
  1115. var _this;
  1116. _this = _CSSStyleValue.call(this) || this;
  1117. _this.colorSpace = void 0;
  1118. _this.colorSpace = colorSpace;
  1119. return _this;
  1120. }
  1121. var _proto = CSSColorValue.prototype;
  1122. _proto.getType = function getType() {
  1123. return CSSStyleValueType.kColorType;
  1124. }
  1125. // buildCSSText(n: Nested, p: ParenLess, result: string): string {
  1126. // let text = '';
  1127. // if (this.colorSpace === 'rgb') {
  1128. // text = `rgba(${this.channels.join(',')},${this.alpha})`;
  1129. // }
  1130. // return (result += text);
  1131. // }
  1132. /**
  1133. * @see https://drafts.css-houdini.org/css-typed-om-1/#dom-csscolorvalue-to
  1134. */;
  1135. _proto.to = function to(colorSpace) {
  1136. return this;
  1137. };
  1138. return CSSColorValue;
  1139. }(CSSStyleValue);
  1140. (function (GradientType) {
  1141. GradientType[GradientType["Constant"] = 0] = "Constant";
  1142. GradientType[GradientType["LinearGradient"] = 1] = "LinearGradient";
  1143. GradientType[GradientType["RadialGradient"] = 2] = "RadialGradient";
  1144. })(exports.GradientType || (exports.GradientType = {}));
  1145. var CSSGradientValue = /*#__PURE__*/function (_CSSStyleValue) {
  1146. _inheritsLoose(CSSGradientValue, _CSSStyleValue);
  1147. function CSSGradientValue(type, value) {
  1148. var _this;
  1149. _this = _CSSStyleValue.call(this) || this;
  1150. _this.type = void 0;
  1151. _this.value = void 0;
  1152. _this.type = type;
  1153. _this.value = value;
  1154. return _this;
  1155. }
  1156. var _proto = CSSGradientValue.prototype;
  1157. _proto.clone = function clone() {
  1158. return new CSSGradientValue(this.type, this.value);
  1159. };
  1160. _proto.buildCSSText = function buildCSSText(n, p, result) {
  1161. return result;
  1162. };
  1163. _proto.getType = function getType() {
  1164. return CSSStyleValueType.kColorType;
  1165. };
  1166. return CSSGradientValue;
  1167. }(CSSStyleValue);
  1168. /**
  1169. * CSSKeywordValue represents CSS Values that are specified as keywords
  1170. * eg. 'initial'
  1171. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSKeywordValue
  1172. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_keyword_value.idl
  1173. */
  1174. var CSSKeywordValue = /*#__PURE__*/function (_CSSStyleValue) {
  1175. _inheritsLoose(CSSKeywordValue, _CSSStyleValue);
  1176. function CSSKeywordValue(value) {
  1177. var _this;
  1178. _this = _CSSStyleValue.call(this) || this;
  1179. _this.value = void 0;
  1180. _this.value = value;
  1181. return _this;
  1182. }
  1183. var _proto = CSSKeywordValue.prototype;
  1184. _proto.clone = function clone() {
  1185. return new CSSKeywordValue(this.value);
  1186. };
  1187. _proto.getType = function getType() {
  1188. return CSSStyleValueType.kKeywordType;
  1189. };
  1190. _proto.buildCSSText = function buildCSSText(n, p, result) {
  1191. return result + this.value;
  1192. };
  1193. return CSSKeywordValue;
  1194. }(CSSStyleValue);
  1195. function memoize(func, resolver) {
  1196. if (typeof func !== 'function' || resolver != null && typeof resolver !== 'function') {
  1197. throw new TypeError('Expected a function');
  1198. }
  1199. var memoized = function memoized() {
  1200. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  1201. args[_key] = arguments[_key];
  1202. }
  1203. var key = resolver ? resolver.apply(this, args) : args[0];
  1204. var cache = memoized.cache;
  1205. if (cache.has(key)) {
  1206. return cache.get(key);
  1207. }
  1208. var result = func.apply(this, args);
  1209. memoized.cache = cache.set(key, result) || cache;
  1210. return result;
  1211. };
  1212. memoized.cache = new (memoize.Cache || Map)();
  1213. return memoized;
  1214. }
  1215. memoize.Cache = Map;
  1216. var camelCase = memoize(function (str) {
  1217. if (str === void 0) {
  1218. str = '';
  1219. }
  1220. return str.replace(/-([a-z])/g, function (g) {
  1221. return g[1].toUpperCase();
  1222. });
  1223. });
  1224. var kebabize = function kebabize(str) {
  1225. return str.split('').map(function (letter, idx) {
  1226. return letter.toUpperCase() === letter ? "" + (idx !== 0 ? '-' : '') + letter.toLowerCase() : letter;
  1227. }).join('');
  1228. };
  1229. function DCHECK(bool) {
  1230. if (!bool) {
  1231. throw new Error();
  1232. }
  1233. }
  1234. function isFunction(func) {
  1235. return typeof func === 'function';
  1236. }
  1237. function isSymbol(value) {
  1238. // @see https://github.com/lodash/lodash/blob/master/isSymbol.js
  1239. return typeof value === 'symbol';
  1240. }
  1241. var definedProps = function definedProps(obj) {
  1242. return Object.fromEntries(Object.entries(obj).filter(function (_ref) {
  1243. var v = _ref[1];
  1244. return v !== undefined;
  1245. }));
  1246. };
  1247. var FORMAT_ATTR_MAP = {
  1248. d: {
  1249. alias: 'path'
  1250. },
  1251. strokeDasharray: {
  1252. alias: 'lineDash'
  1253. },
  1254. strokeWidth: {
  1255. alias: 'lineWidth'
  1256. },
  1257. textAnchor: {
  1258. alias: 'textAlign'
  1259. },
  1260. src: {
  1261. alias: 'img'
  1262. }
  1263. };
  1264. var formatAttributeName = memoize(function (name) {
  1265. var attributeName = camelCase(name);
  1266. var map = FORMAT_ATTR_MAP[attributeName];
  1267. attributeName = (map === null || map === void 0 ? void 0 : map.alias) || attributeName;
  1268. return attributeName;
  1269. });
  1270. // type CSSNumericBaseType =
  1271. // | 'length'
  1272. // | 'angle'
  1273. // | 'time'
  1274. // | 'frequency'
  1275. // | 'resolution'
  1276. // | 'flex'
  1277. // | 'percent';
  1278. // https://drafts.css-houdini.org/css-typed-om/#dictdef-cssnumerictype
  1279. // interface CSSNumericType {
  1280. // length: number;
  1281. // angle: number;
  1282. // time: number;
  1283. // frequency: number;
  1284. // resolution: number;
  1285. // flex: number;
  1286. // percent: number;
  1287. // percentHint: CSSNumericBaseType;
  1288. // }
  1289. var formatInfinityOrNaN = function formatInfinityOrNaN(number, suffix) {
  1290. if (suffix === void 0) {
  1291. suffix = '';
  1292. }
  1293. var result = '';
  1294. if (!Number.isFinite(number)) {
  1295. if (number > 0) result = 'infinity';else result = '-infinity';
  1296. } else {
  1297. DCHECK(Number.isNaN(number));
  1298. result = 'NaN';
  1299. }
  1300. return result += suffix;
  1301. };
  1302. var toCanonicalUnit = function toCanonicalUnit(unit) {
  1303. return canonicalUnitTypeForCategory(unitTypeToUnitCategory(unit));
  1304. };
  1305. /**
  1306. * CSSNumericValue is the base class for numeric and length typed CSS Values.
  1307. * @see https://drafts.css-houdini.org/css-typed-om/#numeric-objects
  1308. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericValue
  1309. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_numeric_value.idl
  1310. */
  1311. /**
  1312. * Represents numeric values that can be expressed as a single number plus a
  1313. * unit (or a naked number or percentage).
  1314. * @see https://drafts.css-houdini.org/css-typed-om/#cssunitvalue
  1315. */
  1316. var CSSUnitValue = /*#__PURE__*/function (_CSSStyleValue) {
  1317. _inheritsLoose(CSSUnitValue, _CSSStyleValue);
  1318. function CSSUnitValue(value, unitOrName) {
  1319. var _this;
  1320. if (unitOrName === void 0) {
  1321. unitOrName = exports.UnitType.kNumber;
  1322. }
  1323. _this = _CSSStyleValue.call(this) || this;
  1324. _this.unit = void 0;
  1325. _this.value = void 0;
  1326. var unit;
  1327. if (typeof unitOrName === 'string') {
  1328. unit = unitFromName(unitOrName);
  1329. } else {
  1330. unit = unitOrName;
  1331. }
  1332. _this.unit = unit;
  1333. _this.value = value;
  1334. return _this;
  1335. }
  1336. var _proto = CSSUnitValue.prototype;
  1337. _proto.clone = function clone() {
  1338. return new CSSUnitValue(this.value, this.unit);
  1339. };
  1340. _proto.equals = function equals(other) {
  1341. var other_unit_value = other;
  1342. return this.value === other_unit_value.value && this.unit === other_unit_value.unit;
  1343. };
  1344. _proto.getType = function getType() {
  1345. return CSSStyleValueType.kUnitType;
  1346. };
  1347. _proto.convertTo = function convertTo(target_unit) {
  1348. if (this.unit === target_unit) {
  1349. return new CSSUnitValue(this.value, this.unit);
  1350. }
  1351. // Instead of defining the scale factors for every unit to every other unit,
  1352. // we simply convert to the canonical unit and back since we already have
  1353. // the scale factors for canonical units.
  1354. var canonical_unit = toCanonicalUnit(this.unit);
  1355. if (canonical_unit !== toCanonicalUnit(target_unit) || canonical_unit === exports.UnitType.kUnknown) {
  1356. return null;
  1357. }
  1358. var scale_factor = conversionToCanonicalUnitsScaleFactor(this.unit) / conversionToCanonicalUnitsScaleFactor(target_unit);
  1359. return new CSSUnitValue(this.value * scale_factor, target_unit);
  1360. };
  1361. _proto.buildCSSText = function buildCSSText(n, p, result) {
  1362. var text;
  1363. switch (this.unit) {
  1364. case exports.UnitType.kUnknown:
  1365. // FIXME
  1366. break;
  1367. case exports.UnitType.kInteger:
  1368. text = Number(this.value).toFixed(0);
  1369. break;
  1370. case exports.UnitType.kNumber:
  1371. case exports.UnitType.kPercentage:
  1372. case exports.UnitType.kEms:
  1373. // case UnitType.kQuirkyEms:
  1374. // case UnitType.kExs:
  1375. case exports.UnitType.kRems:
  1376. // case UnitType.kChs:
  1377. case exports.UnitType.kPixels:
  1378. // case UnitType.kCentimeters:
  1379. // case UnitType.kDotsPerPixel:
  1380. // case UnitType.kDotsPerInch:
  1381. // case UnitType.kDotsPerCentimeter:
  1382. // case UnitType.kMillimeters:
  1383. // case UnitType.kQuarterMillimeters:
  1384. // case UnitType.kInches:
  1385. // case UnitType.kPoints:
  1386. // case UnitType.kPicas:
  1387. // case UnitType.kUserUnits:
  1388. case exports.UnitType.kDegrees:
  1389. case exports.UnitType.kRadians:
  1390. case exports.UnitType.kGradians:
  1391. case exports.UnitType.kMilliseconds:
  1392. case exports.UnitType.kSeconds:
  1393. // case UnitType.kHertz:
  1394. // case UnitType.kKilohertz:
  1395. case exports.UnitType.kTurns:
  1396. // case UnitType.kContainerMax: { // case UnitType.kContainerMin: // case UnitType.kContainerBlockSize: // case UnitType.kContainerInlineSize: // case UnitType.kContainerHeight: // case UnitType.kContainerWidth: // case UnitType.kDynamicViewportMax: // case UnitType.kDynamicViewportMin: // case UnitType.kDynamicViewportBlockSize: // case UnitType.kDynamicViewportInlineSize: // case UnitType.kDynamicViewportHeight: // case UnitType.kDynamicViewportWidth: // case UnitType.kLargeViewportMax: // case UnitType.kLargeViewportMin: // case UnitType.kLargeViewportBlockSize: // case UnitType.kLargeViewportInlineSize: // case UnitType.kLargeViewportHeight: // case UnitType.kLargeViewportWidth: // case UnitType.kSmallViewportMax: // case UnitType.kSmallViewportMin: // case UnitType.kSmallViewportBlockSize: // case UnitType.kSmallViewportInlineSize: // case UnitType.kSmallViewportHeight: // case UnitType.kSmallViewportWidth: // case UnitType.kViewportMax: // case UnitType.kViewportMin: // case UnitType.kViewportBlockSize: // case UnitType.kViewportInlineSize: // case UnitType.kViewportHeight: // case UnitType.kViewportWidth: // case UnitType.kFraction:
  1397. {
  1398. var kMinInteger = -999999;
  1399. var kMaxInteger = 999999;
  1400. var value = this.value;
  1401. var unit = unitTypeToString(this.unit);
  1402. if (value < kMinInteger || value > kMaxInteger) {
  1403. var _unit = unitTypeToString(this.unit);
  1404. if (!Number.isFinite(value) || Number.isNaN(value)) {
  1405. text = formatInfinityOrNaN(value, _unit);
  1406. } else {
  1407. text = value + (_unit || '');
  1408. }
  1409. } else {
  1410. text = "" + value + unit;
  1411. }
  1412. }
  1413. }
  1414. result += text;
  1415. return result;
  1416. };
  1417. return CSSUnitValue;
  1418. }(CSSStyleValue);
  1419. var Opx = new CSSUnitValue(0, 'px');
  1420. var Lpx = new CSSUnitValue(1, 'px');
  1421. var Odeg = new CSSUnitValue(0, 'deg');
  1422. /**
  1423. * The CSSRGB class represents the CSS rgb()/rgba() functions.
  1424. *
  1425. * @see https://drafts.css-houdini.org/css-typed-om-1/#cssrgb
  1426. */
  1427. var CSSRGB = /*#__PURE__*/function (_CSSColorValue) {
  1428. _inheritsLoose(CSSRGB, _CSSColorValue);
  1429. function CSSRGB(r, g, b, alpha,
  1430. /**
  1431. * 'transparent' & 'none' has the same rgba data
  1432. */
  1433. isNone) {
  1434. var _this;
  1435. if (alpha === void 0) {
  1436. alpha = 1;
  1437. }
  1438. if (isNone === void 0) {
  1439. isNone = false;
  1440. }
  1441. _this = _CSSColorValue.call(this, 'rgb') || this;
  1442. _this.r = void 0;
  1443. _this.g = void 0;
  1444. _this.b = void 0;
  1445. _this.alpha = void 0;
  1446. _this.isNone = void 0;
  1447. _this.r = r;
  1448. _this.g = g;
  1449. _this.b = b;
  1450. _this.alpha = alpha;
  1451. _this.isNone = isNone;
  1452. return _this;
  1453. }
  1454. var _proto = CSSRGB.prototype;
  1455. _proto.clone = function clone() {
  1456. return new CSSRGB(this.r, this.g, this.b, this.alpha);
  1457. };
  1458. _proto.buildCSSText = function buildCSSText(n, p, result) {
  1459. return result + ("rgba(" + this.r + "," + this.g + "," + this.b + "," + this.alpha + ")");
  1460. };
  1461. return CSSRGB;
  1462. }(CSSColorValue);
  1463. /**
  1464. * holds useful CSS-related methods.
  1465. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS
  1466. *
  1467. * * CSS Typed OM @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/factory_functions
  1468. * * register property @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
  1469. * * CSS Layout API
  1470. */
  1471. var CSS = {
  1472. /**
  1473. * <number>
  1474. * @see https://drafts.csswg.org/css-values-4/#number-value
  1475. */
  1476. number: function number(n) {
  1477. return new CSSUnitValue(n);
  1478. },
  1479. /**
  1480. * <percentage>
  1481. * @see https://drafts.csswg.org/css-values-4/#percentage-value
  1482. */
  1483. percent: function percent(n) {
  1484. return new CSSUnitValue(n, '%');
  1485. },
  1486. /**
  1487. * <length>
  1488. */
  1489. px: function px(n) {
  1490. return new CSSUnitValue(n, 'px');
  1491. },
  1492. /**
  1493. * <length>
  1494. */
  1495. em: function em(n) {
  1496. return new CSSUnitValue(n, 'em');
  1497. },
  1498. rem: function rem(n) {
  1499. return new CSSUnitValue(n, 'rem');
  1500. },
  1501. /**
  1502. * <angle>
  1503. */
  1504. deg: function deg(n) {
  1505. return new CSSUnitValue(n, 'deg');
  1506. },
  1507. /**
  1508. * <angle>
  1509. */
  1510. grad: function grad(n) {
  1511. return new CSSUnitValue(n, 'grad');
  1512. },
  1513. /**
  1514. * <angle>
  1515. */
  1516. rad: function rad(n) {
  1517. return new CSSUnitValue(n, 'rad');
  1518. },
  1519. /**
  1520. * <angle>
  1521. */
  1522. turn: function turn(n) {
  1523. return new CSSUnitValue(n, 'turn');
  1524. },
  1525. /**
  1526. * <time>
  1527. */
  1528. s: function s(n) {
  1529. return new CSSUnitValue(n, 's');
  1530. },
  1531. /**
  1532. * <time>
  1533. */
  1534. ms: function ms(n) {
  1535. return new CSSUnitValue(n, 'ms');
  1536. },
  1537. /**
  1538. * CSS Properties & Values API
  1539. *
  1540. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS_Properties_and_Values_API
  1541. * @see https://drafts.css-houdini.org/css-properties-values-api/#registering-custom-properties
  1542. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
  1543. */
  1544. registerProperty: function registerProperty(definition) {
  1545. var name = definition.name,
  1546. inherits = definition.inherits,
  1547. interpolable = definition.interpolable,
  1548. initialValue = definition.initialValue,
  1549. syntax = definition.syntax;
  1550. runtime.styleValueRegistry.registerMetadata({
  1551. n: name,
  1552. inh: inherits,
  1553. int: interpolable,
  1554. d: initialValue,
  1555. syntax: syntax
  1556. });
  1557. },
  1558. /**
  1559. * CSS Layout API
  1560. * register layout
  1561. *
  1562. * @see https://github.com/w3c/css-houdini-drafts/blob/main/css-layout-api/EXPLAINER.md
  1563. * @see https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini#css_layout_api
  1564. */
  1565. registerLayout: function registerLayout(name, clazz) {
  1566. runtime.layoutRegistry.registerLayout(name, clazz);
  1567. }
  1568. };
  1569. /**
  1570. * CSSKeywordValue
  1571. */
  1572. var unsetKeywordValue = new CSSKeywordValue('unset');
  1573. var initialKeywordValue = new CSSKeywordValue('initial');
  1574. var inheritKeywordValue = new CSSKeywordValue('inherit');
  1575. var keywordCache = {
  1576. '': unsetKeywordValue,
  1577. unset: unsetKeywordValue,
  1578. initial: initialKeywordValue,
  1579. inherit: inheritKeywordValue
  1580. };
  1581. var getOrCreateKeyword = function getOrCreateKeyword(name) {
  1582. if (!keywordCache[name]) {
  1583. keywordCache[name] = new CSSKeywordValue(name);
  1584. }
  1585. return keywordCache[name];
  1586. };
  1587. /**
  1588. * CSSColor
  1589. */
  1590. var noneColor = new CSSRGB(0, 0, 0, 0, true);
  1591. var transparentColor = new CSSRGB(0, 0, 0, 0);
  1592. var getOrCreateRGBA = memoize(function (r, g, b, a) {
  1593. return new CSSRGB(r, g, b, a);
  1594. }, function (r, g, b, a) {
  1595. return "rgba(" + r + "," + g + "," + b + "," + a + ")";
  1596. });
  1597. // export const getOrCreateUnitValue = memoize(
  1598. // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
  1599. // return new CSSUnitValue(value, unitOrName);
  1600. // },
  1601. // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
  1602. // return `${value}${unitOrName}`;
  1603. // },
  1604. // );
  1605. var getOrCreateUnitValue = function getOrCreateUnitValue(value, unitOrName) {
  1606. if (unitOrName === void 0) {
  1607. unitOrName = exports.UnitType.kNumber;
  1608. }
  1609. return new CSSUnitValue(value, unitOrName);
  1610. };
  1611. var PECENTAGE_50 = new CSSUnitValue(50, '%');
  1612. var canvasMap = {};
  1613. var defaultCanvasIdCounter = 0;
  1614. /**
  1615. * destroy existed canvas with the same id
  1616. */
  1617. function cleanExistedCanvas(container, canvas) {
  1618. if (container) {
  1619. var id = typeof container === 'string' ? container : container.id || defaultCanvasIdCounter++;
  1620. if (canvasMap[id]) {
  1621. canvasMap[id].destroy();
  1622. }
  1623. canvasMap[id] = canvas;
  1624. }
  1625. }
  1626. var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
  1627. function sortedIndex(array, value) {
  1628. var low = 0;
  1629. var high = array.length;
  1630. while (low < high) {
  1631. var mid = low + high >>> 1;
  1632. if (sortByZIndex(array[mid], value) < 0) {
  1633. low = mid + 1;
  1634. } else {
  1635. high = mid;
  1636. }
  1637. }
  1638. return low;
  1639. }
  1640. function sortByZIndex(o1, o2) {
  1641. var zIndex1 = Number(o1.parsedStyle.zIndex);
  1642. var zIndex2 = Number(o2.parsedStyle.zIndex);
  1643. if (zIndex1 === zIndex2) {
  1644. var parent = o1.parentNode;
  1645. if (parent) {
  1646. var children = parent.childNodes || [];
  1647. return children.indexOf(o1) - children.indexOf(o2);
  1648. }
  1649. }
  1650. return zIndex1 - zIndex2;
  1651. }
  1652. function findClosestClipPathTarget(object) {
  1653. var el = object;
  1654. do {
  1655. var _el$parsedStyle;
  1656. var clipPath = (_el$parsedStyle = el.parsedStyle) === null || _el$parsedStyle === void 0 ? void 0 : _el$parsedStyle.clipPath;
  1657. if (clipPath) return el;
  1658. el = el.parentElement;
  1659. } while (el !== null);
  1660. return null;
  1661. }
  1662. var PX_SUFFIX = 'px';
  1663. function setDOMSize($el, width, height) {
  1664. if (isBrowser && $el.style) {
  1665. $el.style.width = width + PX_SUFFIX;
  1666. $el.style.height = height + PX_SUFFIX;
  1667. }
  1668. }
  1669. function getStyle($el, property) {
  1670. if (isBrowser) {
  1671. return document.defaultView.getComputedStyle($el, null).getPropertyValue(property);
  1672. }
  1673. }
  1674. function getWidth($el) {
  1675. var width = getStyle($el, 'width');
  1676. if (width === 'auto') {
  1677. return $el.offsetWidth;
  1678. }
  1679. return parseFloat(width);
  1680. }
  1681. function getHeight($el) {
  1682. var height = getStyle($el, 'height');
  1683. if (height === 'auto') {
  1684. return $el.offsetHeight;
  1685. }
  1686. return parseFloat(height);
  1687. }
  1688. var ERROR_MSG_METHOD_NOT_IMPLEMENTED = 'Method not implemented.';
  1689. var ERROR_MSG_USE_DOCUMENT_ELEMENT = 'Use document.documentElement instead.';
  1690. var ERROR_MSG_APPEND_DESTROYED_ELEMENT = 'Cannot append a destroyed element.';
  1691. // borrow from hammer.js
  1692. var MOUSE_POINTER_ID = 1;
  1693. var TOUCH_TO_POINTER = {
  1694. touchstart: 'pointerdown',
  1695. touchend: 'pointerup',
  1696. touchendoutside: 'pointerupoutside',
  1697. touchmove: 'pointermove',
  1698. touchcancel: 'pointercancel'
  1699. };
  1700. function copyVec3(a, b) {
  1701. a[0] = b[0];
  1702. a[1] = b[1];
  1703. a[2] = b[2];
  1704. return a;
  1705. }
  1706. function subVec3(o, a, b) {
  1707. o[0] = a[0] - b[0];
  1708. o[1] = a[1] - b[1];
  1709. o[2] = a[2] - b[2];
  1710. return o;
  1711. }
  1712. function addVec3(o, a, b) {
  1713. o[0] = a[0] + b[0];
  1714. o[1] = a[1] + b[1];
  1715. o[2] = a[2] + b[2];
  1716. return o;
  1717. }
  1718. function scaleVec3(o, a, b) {
  1719. o[0] = a[0] * b;
  1720. o[1] = a[1] * b;
  1721. o[2] = a[2] * b;
  1722. return o;
  1723. }
  1724. function maxVec3(o, a, b) {
  1725. o[0] = Math.max(a[0], b[0]);
  1726. o[1] = Math.max(a[1], b[1]);
  1727. o[2] = Math.max(a[2], b[2]);
  1728. return o;
  1729. }
  1730. function minVec3(o, a, b) {
  1731. o[0] = Math.min(a[0], b[0]);
  1732. o[1] = Math.min(a[1], b[1]);
  1733. o[2] = Math.min(a[2], b[2]);
  1734. return o;
  1735. }
  1736. function getAngle(angle) {
  1737. if (angle === undefined) {
  1738. return 0;
  1739. } else if (angle > 360 || angle < -360) {
  1740. return angle % 360;
  1741. }
  1742. return angle;
  1743. }
  1744. function createVec3(x, y, z) {
  1745. if (y === void 0) {
  1746. y = 0;
  1747. }
  1748. if (z === void 0) {
  1749. z = 0;
  1750. }
  1751. if (Array.isArray(x) && x.length === 3) {
  1752. return glMatrix.vec3.clone(x);
  1753. }
  1754. if (util.isNumber(x)) {
  1755. return glMatrix.vec3.fromValues(x, y, z);
  1756. }
  1757. return glMatrix.vec3.fromValues(x[0], x[1] || y, x[2] || z);
  1758. }
  1759. function deg2rad(deg) {
  1760. return deg * (Math.PI / 180);
  1761. }
  1762. function rad2deg(rad) {
  1763. return rad * (180 / Math.PI);
  1764. }
  1765. function grad2deg(grads) {
  1766. grads = grads % 400;
  1767. if (grads < 0) {
  1768. grads += 400;
  1769. }
  1770. return grads / 400 * 360;
  1771. }
  1772. function deg2turn(deg) {
  1773. return deg / 360;
  1774. }
  1775. function turn2deg(turn) {
  1776. return 360 * turn;
  1777. }
  1778. function getEulerFromQuat(out, quat) {
  1779. var x = quat[0];
  1780. var y = quat[1];
  1781. var z = quat[2];
  1782. var w = quat[3];
  1783. var x2 = x * x;
  1784. var y2 = y * y;
  1785. var z2 = z * z;
  1786. var w2 = w * w;
  1787. var unit = x2 + y2 + z2 + w2;
  1788. var test = x * w - y * z;
  1789. if (test > 0.499995 * unit) {
  1790. // TODO: Use glmatrix.EPSILON
  1791. // singularity at the north pole
  1792. out[0] = Math.PI / 2;
  1793. out[1] = 2 * Math.atan2(y, x);
  1794. out[2] = 0;
  1795. } else if (test < -0.499995 * unit) {
  1796. //TODO: Use glmatrix.EPSILON
  1797. // singularity at the south pole
  1798. out[0] = -Math.PI / 2;
  1799. out[1] = 2 * Math.atan2(y, x);
  1800. out[2] = 0;
  1801. } else {
  1802. out[0] = Math.asin(2 * (x * z - w * y));
  1803. out[1] = Math.atan2(2 * (x * w + y * z), 1 - 2 * (z2 + w2));
  1804. out[2] = Math.atan2(2 * (x * y + z * w), 1 - 2 * (y2 + z2));
  1805. }
  1806. // TODO: Return them as degrees and not as radians
  1807. return out;
  1808. }
  1809. function getEulerFromMat4(out, m) {
  1810. var x;
  1811. var z;
  1812. var halfPi = Math.PI * 0.5;
  1813. var _mat4$getScaling = glMatrix.mat4.getScaling(glMatrix.vec3.create(), m),
  1814. sx = _mat4$getScaling[0],
  1815. sy = _mat4$getScaling[1],
  1816. sz = _mat4$getScaling[2];
  1817. var y = Math.asin(-m[2] / sx);
  1818. if (y < halfPi) {
  1819. if (y > -halfPi) {
  1820. x = Math.atan2(m[6] / sy, m[10] / sz);
  1821. z = Math.atan2(m[1] / sx, m[0] / sx);
  1822. } else {
  1823. // Not a unique solution
  1824. z = 0;
  1825. x = -Math.atan2(m[4] / sy, m[5] / sy);
  1826. }
  1827. } else {
  1828. // Not a unique solution
  1829. z = 0;
  1830. x = Math.atan2(m[4] / sy, m[5] / sy);
  1831. }
  1832. out[0] = x;
  1833. out[1] = y;
  1834. out[2] = z;
  1835. return out;
  1836. }
  1837. /**
  1838. * @see https://github.com/toji/gl-matrix/issues/329
  1839. * @see https://doc.babylonjs.com/divingDeeper/mesh/transforms/center_origin/rotation_conventions
  1840. */
  1841. function getEuler(out, quat) {
  1842. if (quat.length === 16) {
  1843. return getEulerFromMat4(out, quat);
  1844. } else {
  1845. return getEulerFromQuat(out, quat);
  1846. }
  1847. }
  1848. function fromRotationTranslationScale(rotation, x, y, scaleX, scaleY) {
  1849. var cos = Math.cos(rotation);
  1850. var sin = Math.sin(rotation);
  1851. return glMatrix.mat3.fromValues(scaleX * cos, scaleY * sin, 0, -scaleX * sin, scaleY * cos, 0, x, y, 1);
  1852. }
  1853. function makePerspective(out, left, right, top, bottom, near, far) {
  1854. var x = 2 * near / (right - left);
  1855. var y = 2 * near / (top - bottom);
  1856. var a = (right + left) / (right - left);
  1857. var b = (top + bottom) / (top - bottom);
  1858. var c = -(far + near) / (far - near);
  1859. var d = -2 * far * near / (far - near);
  1860. out[0] = x;
  1861. out[1] = 0;
  1862. out[2] = 0;
  1863. out[3] = 0;
  1864. out[4] = 0;
  1865. out[5] = y;
  1866. out[6] = 0;
  1867. out[7] = 0;
  1868. out[8] = a;
  1869. out[9] = b;
  1870. out[10] = c;
  1871. out[11] = -1;
  1872. out[12] = 0;
  1873. out[13] = 0;
  1874. out[14] = d;
  1875. out[15] = 0;
  1876. return out;
  1877. }
  1878. function decompose(mat) {
  1879. var row0x = mat[0];
  1880. var row0y = mat[1];
  1881. var row1x = mat[3];
  1882. var row1y = mat[4];
  1883. // decompose 3x3 matrix
  1884. // @see https://www.w3.org/TR/css-transforms-1/#decomposing-a-2d-matrix
  1885. var scalingX = Math.sqrt(row0x * row0x + row0y * row0y);
  1886. var scalingY = Math.sqrt(row1x * row1x + row1y * row1y);
  1887. // If determinant is negative, one axis was flipped.
  1888. var determinant = row0x * row1y - row0y * row1x;
  1889. if (determinant < 0) {
  1890. // Flip axis with minimum unit vector dot product.
  1891. if (row0x < row1y) {
  1892. scalingX = -scalingX;
  1893. } else {
  1894. scalingY = -scalingY;
  1895. }
  1896. }
  1897. // Renormalize matrix to remove scale.
  1898. if (scalingX) {
  1899. row0x *= 1 / scalingX;
  1900. row0y *= 1 / scalingX;
  1901. }
  1902. if (scalingY) {
  1903. row1x *= 1 / scalingY;
  1904. row1y *= 1 / scalingY;
  1905. }
  1906. // Compute rotation and renormalize matrix.
  1907. var rotation = Math.atan2(row0y, row0x);
  1908. var angle = rad2deg(rotation);
  1909. return [mat[6], mat[7], scalingX, scalingY, angle];
  1910. }
  1911. var tmp = glMatrix.mat4.create();
  1912. var perspectiveMatrix = glMatrix.mat4.create();
  1913. var tmpVec4 = glMatrix.vec4.create();
  1914. var row = [glMatrix.vec3.create(), glMatrix.vec3.create(), glMatrix.vec3.create()];
  1915. var pdum3 = glMatrix.vec3.create();
  1916. /*
  1917. Input: matrix ; a 4x4 matrix
  1918. Output: translation ; a 3 component vector
  1919. scale ; a 3 component vector
  1920. skew ; skew factors XY,XZ,YZ represented as a 3 component vector
  1921. perspective ; a 4 component vector
  1922. quaternion ; a 4 component vector
  1923. Returns false if the matrix cannot be decomposed, true if it can
  1924. References:
  1925. https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
  1926. https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
  1927. http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
  1928. */
  1929. function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
  1930. //normalize, if not possible then bail out early
  1931. if (!normalize(tmp, matrix)) return false;
  1932. // perspectiveMatrix is used to solve for perspective, but it also provides
  1933. // an easy way to test for singularity of the upper 3x3 component.
  1934. glMatrix.mat4.copy(perspectiveMatrix, tmp);
  1935. perspectiveMatrix[3] = 0;
  1936. perspectiveMatrix[7] = 0;
  1937. perspectiveMatrix[11] = 0;
  1938. perspectiveMatrix[15] = 1;
  1939. // If the perspectiveMatrix is not invertible, we are also unable to
  1940. // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
  1941. if (Math.abs(glMatrix.mat4.determinant(perspectiveMatrix)) < 1e-8) return false;
  1942. var a03 = tmp[3],
  1943. a13 = tmp[7],
  1944. a23 = tmp[11],
  1945. a30 = tmp[12],
  1946. a31 = tmp[13],
  1947. a32 = tmp[14],
  1948. a33 = tmp[15];
  1949. // First, isolate perspective.
  1950. if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
  1951. tmpVec4[0] = a03;
  1952. tmpVec4[1] = a13;
  1953. tmpVec4[2] = a23;
  1954. tmpVec4[3] = a33;
  1955. // Solve the equation by inverting perspectiveMatrix and multiplying
  1956. // rightHandSide by the inverse.
  1957. // resuing the perspectiveMatrix here since it's no longer needed
  1958. var ret = glMatrix.mat4.invert(perspectiveMatrix, perspectiveMatrix);
  1959. if (!ret) return false;
  1960. glMatrix.mat4.transpose(perspectiveMatrix, perspectiveMatrix);
  1961. //multiply by transposed inverse perspective matrix, into perspective vec4
  1962. glMatrix.vec4.transformMat4(perspective, tmpVec4, perspectiveMatrix);
  1963. } else {
  1964. //no perspective
  1965. perspective[0] = perspective[1] = perspective[2] = 0;
  1966. perspective[3] = 1;
  1967. }
  1968. // Next take care of translation
  1969. translation[0] = a30;
  1970. translation[1] = a31;
  1971. translation[2] = a32;
  1972. // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
  1973. mat3from4(row, tmp);
  1974. // Compute X scale factor and normalize first row.
  1975. scale[0] = glMatrix.vec3.length(row[0]);
  1976. glMatrix.vec3.normalize(row[0], row[0]);
  1977. // Compute XY shear factor and make 2nd row orthogonal to 1st.
  1978. skew[0] = glMatrix.vec3.dot(row[0], row[1]);
  1979. combine(row[1], row[1], row[0], 1.0, -skew[0]);
  1980. // Now, compute Y scale and normalize 2nd row.
  1981. scale[1] = glMatrix.vec3.length(row[1]);
  1982. glMatrix.vec3.normalize(row[1], row[1]);
  1983. skew[0] /= scale[1];
  1984. // Compute XZ and YZ shears, orthogonalize 3rd row
  1985. skew[1] = glMatrix.vec3.dot(row[0], row[2]);
  1986. combine(row[2], row[2], row[0], 1.0, -skew[1]);
  1987. skew[2] = glMatrix.vec3.dot(row[1], row[2]);
  1988. combine(row[2], row[2], row[1], 1.0, -skew[2]);
  1989. // Next, get Z scale and normalize 3rd row.
  1990. scale[2] = glMatrix.vec3.length(row[2]);
  1991. glMatrix.vec3.normalize(row[2], row[2]);
  1992. skew[1] /= scale[2];
  1993. skew[2] /= scale[2];
  1994. // At this point, the matrix (in rows) is orthonormal.
  1995. // Check for a coordinate system flip. If the determinant
  1996. // is -1, then negate the matrix and the scaling factors.
  1997. glMatrix.vec3.cross(pdum3, row[1], row[2]);
  1998. if (glMatrix.vec3.dot(row[0], pdum3) < 0) {
  1999. for (var i = 0; i < 3; i++) {
  2000. scale[i] *= -1;
  2001. row[i][0] *= -1;
  2002. row[i][1] *= -1;
  2003. row[i][2] *= -1;
  2004. }
  2005. }
  2006. // Now, get the rotations out
  2007. quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0));
  2008. quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0));
  2009. quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0));
  2010. quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0));
  2011. if (row[2][1] > row[1][2]) quaternion[0] = -quaternion[0];
  2012. if (row[0][2] > row[2][0]) quaternion[1] = -quaternion[1];
  2013. if (row[1][0] > row[0][1]) quaternion[2] = -quaternion[2];
  2014. return true;
  2015. }
  2016. function normalize(out, mat) {
  2017. var m44 = mat[15];
  2018. // Cannot normalize.
  2019. if (m44 === 0) return false;
  2020. var scale = 1 / m44;
  2021. for (var i = 0; i < 16; i++) out[i] = mat[i] * scale;
  2022. return true;
  2023. }
  2024. //gets upper-left of a 4x4 matrix into a 3x3 of vectors
  2025. function mat3from4(out, mat4x4) {
  2026. out[0][0] = mat4x4[0];
  2027. out[0][1] = mat4x4[1];
  2028. out[0][2] = mat4x4[2];
  2029. out[1][0] = mat4x4[4];
  2030. out[1][1] = mat4x4[5];
  2031. out[1][2] = mat4x4[6];
  2032. out[2][0] = mat4x4[8];
  2033. out[2][1] = mat4x4[9];
  2034. out[2][2] = mat4x4[10];
  2035. }
  2036. function combine(out, a, b, scale1, scale2) {
  2037. out[0] = a[0] * scale1 + b[0] * scale2;
  2038. out[1] = a[1] * scale1 + b[1] * scale2;
  2039. out[2] = a[2] * scale1 + b[2] * scale2;
  2040. }
  2041. var tmpMat4 = glMatrix.mat4.create();
  2042. function parsedTransformToMat4(transform, object) {
  2043. if (transform && transform.length) {
  2044. var defX = 0;
  2045. var defY = 0;
  2046. if (object) {
  2047. defX = object.parsedStyle.defX || 0;
  2048. defY = object.parsedStyle.defY || 0;
  2049. // reset transform
  2050. object.resetLocalTransform();
  2051. object.setLocalPosition(defX, defY);
  2052. } else {
  2053. object = new DisplayObject({});
  2054. }
  2055. transform.forEach(function (parsed) {
  2056. var t = parsed.t,
  2057. d = parsed.d;
  2058. if (t === 'scale') {
  2059. // scale(1) scale(1, 1)
  2060. var newScale = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2061. return s.value;
  2062. })) || [1, 1];
  2063. object.scaleLocal(newScale[0], newScale[1], 1);
  2064. } else if (t === 'scalex') {
  2065. var _newScale = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2066. return s.value;
  2067. })) || [1];
  2068. object.scaleLocal(_newScale[0], 1, 1);
  2069. } else if (t === 'scaley') {
  2070. var _newScale2 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2071. return s.value;
  2072. })) || [1];
  2073. object.scaleLocal(1, _newScale2[0], 1);
  2074. } else if (t === 'scalez') {
  2075. var _newScale3 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2076. return s.value;
  2077. })) || [1];
  2078. object.scaleLocal(1, 1, _newScale3[0]);
  2079. } else if (t === 'scale3d') {
  2080. var _newScale4 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2081. return s.value;
  2082. })) || [1, 1, 1];
  2083. object.scaleLocal(_newScale4[0], _newScale4[1], _newScale4[2]);
  2084. } else if (t === 'translate') {
  2085. var newTranslation = d || [Opx, Opx];
  2086. object.translateLocal(newTranslation[0].value, newTranslation[1].value, 0);
  2087. } else if (t === 'translatex') {
  2088. var _newTranslation = d || [Opx];
  2089. object.translateLocal(_newTranslation[0].value, 0, 0);
  2090. } else if (t === 'translatey') {
  2091. var _newTranslation2 = d || [Opx];
  2092. object.translateLocal(0, _newTranslation2[0].value, 0);
  2093. } else if (t === 'translatez') {
  2094. var _newTranslation3 = d || [Opx];
  2095. object.translateLocal(0, 0, _newTranslation3[0].value);
  2096. } else if (t === 'translate3d') {
  2097. var _newTranslation4 = d || [Opx, Opx, Opx];
  2098. object.translateLocal(_newTranslation4[0].value, _newTranslation4[1].value, _newTranslation4[2].value);
  2099. } else if (t === 'rotate') {
  2100. var newAngles = d || [Odeg];
  2101. object.rotateLocal(0, 0, convertAngleUnit(newAngles[0]));
  2102. } else if (t === 'rotatex') {
  2103. var _newAngles = d || [Odeg];
  2104. object.rotateLocal(convertAngleUnit(_newAngles[0]), 0, 0);
  2105. } else if (t === 'rotatey') {
  2106. var _newAngles2 = d || [Odeg];
  2107. object.rotateLocal(0, convertAngleUnit(_newAngles2[0]), 0);
  2108. } else if (t === 'rotatez') {
  2109. var _newAngles3 = d || [Odeg];
  2110. object.rotateLocal(0, 0, convertAngleUnit(_newAngles3[0]));
  2111. } else if (t === 'rotate3d') ; else if (t === 'skew') {
  2112. var newSkew = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2113. return s.value;
  2114. })) || [0, 0];
  2115. object.setLocalSkew(deg2rad(newSkew[0]), deg2rad(newSkew[1]));
  2116. } else if (t === 'skewx') {
  2117. var _newSkew = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2118. return s.value;
  2119. })) || [0];
  2120. object.setLocalSkew(deg2rad(_newSkew[0]), object.getLocalSkew()[1]);
  2121. } else if (t === 'skewy') {
  2122. var _newSkew2 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
  2123. return s.value;
  2124. })) || [0];
  2125. object.setLocalSkew(object.getLocalSkew()[0], deg2rad(_newSkew2[0]));
  2126. } else if (t === 'matrix') {
  2127. var _d$map = d.map(function (s) {
  2128. return s.value;
  2129. }),
  2130. a = _d$map[0],
  2131. b = _d$map[1],
  2132. c = _d$map[2],
  2133. dd = _d$map[3],
  2134. tx = _d$map[4],
  2135. ty = _d$map[5];
  2136. object.setLocalTransform(glMatrix.mat4.set(tmpMat4, a, b, 0, 0, c, dd, 0, 0, 0, 0, 1, 0, tx + defX, ty + defY, 0, 1));
  2137. } else if (t === 'matrix3d') {
  2138. // @ts-ignore
  2139. glMatrix.mat4.set.apply(glMatrix.mat4, [tmpMat4].concat(d.map(function (s) {
  2140. return s.value;
  2141. })));
  2142. tmpMat4[12] += defX;
  2143. tmpMat4[13] += defY;
  2144. object.setLocalTransform(tmpMat4);
  2145. }
  2146. });
  2147. }
  2148. return object.getLocalTransform();
  2149. }
  2150. /**
  2151. * borrow from gradient-parser, but we delete some browser compatible prefix such as `-webkit-`
  2152. * @see https://github.com/rafaelcaricio/gradient-parser
  2153. */
  2154. function colorStopToString(colorStop) {
  2155. var type = colorStop.type,
  2156. value = colorStop.value;
  2157. if (type === 'hex') {
  2158. return "#" + value;
  2159. } else if (type === 'literal') {
  2160. return value;
  2161. } else if (type === 'rgb') {
  2162. return "rgb(" + value.join(',') + ")";
  2163. } else {
  2164. return "rgba(" + value.join(',') + ")";
  2165. }
  2166. }
  2167. var parseGradient = function () {
  2168. var tokens = {
  2169. linearGradient: /^(linear\-gradient)/i,
  2170. repeatingLinearGradient: /^(repeating\-linear\-gradient)/i,
  2171. radialGradient: /^(radial\-gradient)/i,
  2172. repeatingRadialGradient: /^(repeating\-radial\-gradient)/i,
  2173. /**
  2174. * @see https://projects.verou.me/conic-gradient/
  2175. */
  2176. conicGradient: /^(conic\-gradient)/i,
  2177. sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,
  2178. extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
  2179. positionKeywords: /^(left|center|right|top|bottom)/i,
  2180. pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
  2181. percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
  2182. emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
  2183. angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
  2184. startCall: /^\(/,
  2185. endCall: /^\)/,
  2186. comma: /^,/,
  2187. hexColor: /^\#([0-9a-fA-F]+)/,
  2188. literalColor: /^([a-zA-Z]+)/,
  2189. rgbColor: /^rgb/i,
  2190. rgbaColor: /^rgba/i,
  2191. number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
  2192. };
  2193. var input = '';
  2194. function error(msg) {
  2195. throw new Error(input + ': ' + msg);
  2196. }
  2197. function getAST() {
  2198. var ast = matchListDefinitions();
  2199. if (input.length > 0) {
  2200. error('Invalid input not EOF');
  2201. }
  2202. return ast;
  2203. }
  2204. function matchListDefinitions() {
  2205. return matchListing(matchDefinition);
  2206. }
  2207. function matchDefinition() {
  2208. return matchGradient('linear-gradient', tokens.linearGradient, matchLinearOrientation) || matchGradient('repeating-linear-gradient', tokens.repeatingLinearGradient, matchLinearOrientation) || matchGradient('radial-gradient', tokens.radialGradient, matchListRadialOrientations) || matchGradient('repeating-radial-gradient', tokens.repeatingRadialGradient, matchListRadialOrientations) || matchGradient('conic-gradient', tokens.conicGradient, matchListRadialOrientations);
  2209. }
  2210. function matchGradient(gradientType, pattern, orientationMatcher) {
  2211. return matchCall(pattern, function (captures) {
  2212. var orientation = orientationMatcher();
  2213. if (orientation) {
  2214. if (!scan(tokens.comma)) {
  2215. error('Missing comma before color stops');
  2216. }
  2217. }
  2218. return {
  2219. type: gradientType,
  2220. orientation: orientation,
  2221. colorStops: matchListing(matchColorStop)
  2222. };
  2223. });
  2224. }
  2225. function matchCall(pattern, callback) {
  2226. var captures = scan(pattern);
  2227. if (captures) {
  2228. if (!scan(tokens.startCall)) {
  2229. error('Missing (');
  2230. }
  2231. var result = callback(captures);
  2232. if (!scan(tokens.endCall)) {
  2233. error('Missing )');
  2234. }
  2235. return result;
  2236. }
  2237. }
  2238. function matchLinearOrientation() {
  2239. return matchSideOrCorner() || matchAngle();
  2240. }
  2241. function matchSideOrCorner() {
  2242. return match('directional', tokens.sideOrCorner, 1);
  2243. }
  2244. function matchAngle() {
  2245. return match('angular', tokens.angleValue, 1);
  2246. }
  2247. function matchListRadialOrientations() {
  2248. var radialOrientations,
  2249. radialOrientation = matchRadialOrientation(),
  2250. lookaheadCache;
  2251. if (radialOrientation) {
  2252. radialOrientations = [];
  2253. radialOrientations.push(radialOrientation);
  2254. lookaheadCache = input;
  2255. if (scan(tokens.comma)) {
  2256. radialOrientation = matchRadialOrientation();
  2257. if (radialOrientation) {
  2258. radialOrientations.push(radialOrientation);
  2259. } else {
  2260. input = lookaheadCache;
  2261. }
  2262. }
  2263. }
  2264. return radialOrientations;
  2265. }
  2266. function matchRadialOrientation() {
  2267. var radialType = matchCircle() || matchEllipse();
  2268. if (radialType) {
  2269. // @ts-ignore
  2270. radialType.at = matchAtPosition();
  2271. } else {
  2272. var extent = matchExtentKeyword();
  2273. if (extent) {
  2274. radialType = extent;
  2275. var positionAt = matchAtPosition();
  2276. if (positionAt) {
  2277. // @ts-ignore
  2278. radialType.at = positionAt;
  2279. }
  2280. } else {
  2281. var defaultPosition = matchPositioning();
  2282. if (defaultPosition) {
  2283. radialType = {
  2284. type: 'default-radial',
  2285. // @ts-ignore
  2286. at: defaultPosition
  2287. };
  2288. }
  2289. }
  2290. }
  2291. return radialType;
  2292. }
  2293. function matchCircle() {
  2294. var circle = match('shape', /^(circle)/i, 0);
  2295. if (circle) {
  2296. // @ts-ignore
  2297. circle.style = matchLength() || matchExtentKeyword();
  2298. }
  2299. return circle;
  2300. }
  2301. function matchEllipse() {
  2302. var ellipse = match('shape', /^(ellipse)/i, 0);
  2303. if (ellipse) {
  2304. // @ts-ignore
  2305. ellipse.style = matchDistance() || matchExtentKeyword();
  2306. }
  2307. return ellipse;
  2308. }
  2309. function matchExtentKeyword() {
  2310. return match('extent-keyword', tokens.extentKeywords, 1);
  2311. }
  2312. function matchAtPosition() {
  2313. if (match('position', /^at/, 0)) {
  2314. var positioning = matchPositioning();
  2315. if (!positioning) {
  2316. error('Missing positioning value');
  2317. }
  2318. return positioning;
  2319. }
  2320. }
  2321. function matchPositioning() {
  2322. var location = matchCoordinates();
  2323. if (location.x || location.y) {
  2324. return {
  2325. type: 'position',
  2326. value: location
  2327. };
  2328. }
  2329. }
  2330. function matchCoordinates() {
  2331. return {
  2332. x: matchDistance(),
  2333. y: matchDistance()
  2334. };
  2335. }
  2336. function matchListing(matcher) {
  2337. var captures = matcher();
  2338. var result = [];
  2339. if (captures) {
  2340. result.push(captures);
  2341. while (scan(tokens.comma)) {
  2342. captures = matcher();
  2343. if (captures) {
  2344. result.push(captures);
  2345. } else {
  2346. error('One extra comma');
  2347. }
  2348. }
  2349. }
  2350. return result;
  2351. }
  2352. function matchColorStop() {
  2353. var color = matchColor();
  2354. if (!color) {
  2355. error('Expected color definition');
  2356. }
  2357. color.length = matchDistance();
  2358. return color;
  2359. }
  2360. function matchColor() {
  2361. return matchHexColor() || matchRGBAColor() || matchRGBColor() || matchLiteralColor();
  2362. }
  2363. function matchLiteralColor() {
  2364. return match('literal', tokens.literalColor, 0);
  2365. }
  2366. function matchHexColor() {
  2367. return match('hex', tokens.hexColor, 1);
  2368. }
  2369. function matchRGBColor() {
  2370. return matchCall(tokens.rgbColor, function () {
  2371. return {
  2372. type: 'rgb',
  2373. value: matchListing(matchNumber)
  2374. };
  2375. });
  2376. }
  2377. function matchRGBAColor() {
  2378. return matchCall(tokens.rgbaColor, function () {
  2379. return {
  2380. type: 'rgba',
  2381. value: matchListing(matchNumber)
  2382. };
  2383. });
  2384. }
  2385. function matchNumber() {
  2386. return scan(tokens.number)[1];
  2387. }
  2388. function matchDistance() {
  2389. return match('%', tokens.percentageValue, 1) || matchPositionKeyword() || matchLength();
  2390. }
  2391. function matchPositionKeyword() {
  2392. return match('position-keyword', tokens.positionKeywords, 1);
  2393. }
  2394. function matchLength() {
  2395. return match('px', tokens.pixelValue, 1) || match('em', tokens.emValue, 1);
  2396. }
  2397. function match(type, pattern, captureIndex) {
  2398. var captures = scan(pattern);
  2399. if (captures) {
  2400. return {
  2401. type: type,
  2402. value: captures[captureIndex]
  2403. };
  2404. }
  2405. }
  2406. function scan(regexp) {
  2407. var blankCaptures = /^[\n\r\t\s]+/.exec(input);
  2408. if (blankCaptures) {
  2409. consume(blankCaptures[0].length);
  2410. }
  2411. var captures = regexp.exec(input);
  2412. if (captures) {
  2413. consume(captures[0].length);
  2414. }
  2415. return captures;
  2416. }
  2417. function consume(size) {
  2418. input = input.substring(size);
  2419. }
  2420. return function (code) {
  2421. input = code;
  2422. return getAST();
  2423. };
  2424. }();
  2425. function computeLinearGradient(width, height, angle) {
  2426. var rad = deg2rad(angle.value);
  2427. var rx = 0;
  2428. var ry = 0;
  2429. var rcx = rx + width / 2;
  2430. var rcy = ry + height / 2;
  2431. // get the length of gradient line
  2432. // @see https://observablehq.com/@danburzo/css-gradient-line
  2433. var length = Math.abs(width * Math.cos(rad)) + Math.abs(height * Math.sin(rad));
  2434. var x1 = rcx - Math.cos(rad) * length / 2;
  2435. var y1 = rcy - Math.sin(rad) * length / 2;
  2436. var x2 = rcx + Math.cos(rad) * length / 2;
  2437. var y2 = rcy + Math.sin(rad) * length / 2;
  2438. return {
  2439. x1: x1,
  2440. y1: y1,
  2441. x2: x2,
  2442. y2: y2
  2443. };
  2444. }
  2445. function computeRadialGradient(width, height, cx, cy, size) {
  2446. // 'px'
  2447. var x = cx.value;
  2448. var y = cy.value;
  2449. // TODO: 'em'
  2450. // '%'
  2451. if (cx.unit === exports.UnitType.kPercentage) {
  2452. x = cx.value / 100 * width;
  2453. }
  2454. if (cy.unit === exports.UnitType.kPercentage) {
  2455. y = cy.value / 100 * height;
  2456. }
  2457. // default to farthest-side
  2458. var r = Math.max(util.distanceSquareRoot([0, 0], [x, y]), util.distanceSquareRoot([0, height], [x, y]), util.distanceSquareRoot([width, height], [x, y]), util.distanceSquareRoot([width, 0], [x, y]));
  2459. if (size) {
  2460. if (size instanceof CSSUnitValue) {
  2461. r = size.value;
  2462. } else if (size instanceof CSSKeywordValue) {
  2463. // @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Images/Using_CSS_gradients#example_closest-side_for_circles
  2464. if (size.value === 'closest-side') {
  2465. r = Math.min(x, width - x, y, height - y);
  2466. } else if (size.value === 'farthest-side') {
  2467. r = Math.max(x, width - x, y, height - y);
  2468. } else if (size.value === 'closest-corner') {
  2469. r = Math.min(util.distanceSquareRoot([0, 0], [x, y]), util.distanceSquareRoot([0, height], [x, y]), util.distanceSquareRoot([width, height], [x, y]), util.distanceSquareRoot([width, 0], [x, y]));
  2470. }
  2471. }
  2472. }
  2473. return {
  2474. x: x,
  2475. y: y,
  2476. r: r
  2477. };
  2478. }
  2479. (function (Shape) {
  2480. Shape["GROUP"] = "g";
  2481. Shape["CIRCLE"] = "circle";
  2482. Shape["ELLIPSE"] = "ellipse";
  2483. Shape["IMAGE"] = "image";
  2484. Shape["RECT"] = "rect";
  2485. Shape["LINE"] = "line";
  2486. Shape["POLYLINE"] = "polyline";
  2487. Shape["POLYGON"] = "polygon";
  2488. Shape["TEXT"] = "text";
  2489. Shape["PATH"] = "path";
  2490. Shape["HTML"] = "html";
  2491. Shape["MESH"] = "mesh";
  2492. })(exports.Shape || (exports.Shape = {}));
  2493. function getOrCalculatePathTotalLength(path) {
  2494. if (path.parsedStyle.path.totalLength === 0) {
  2495. path.parsedStyle.path.totalLength = util.getTotalLength(path.parsedStyle.path.absolutePath);
  2496. }
  2497. return path.parsedStyle.path.totalLength;
  2498. }
  2499. function hasArcOrBezier(path) {
  2500. var hasArc = false;
  2501. var count = path.length;
  2502. for (var i = 0; i < count; i++) {
  2503. var params = path[i];
  2504. var cmd = params[0];
  2505. if (cmd === 'C' || cmd === 'A' || cmd === 'Q') {
  2506. hasArc = true;
  2507. break;
  2508. }
  2509. }
  2510. return hasArc;
  2511. }
  2512. function extractPolygons(pathArray) {
  2513. var polygons = [];
  2514. var polylines = [];
  2515. var points = []; // 防止第一个命令不是 'M'
  2516. for (var i = 0; i < pathArray.length; i++) {
  2517. var params = pathArray[i];
  2518. var cmd = params[0];
  2519. if (cmd === 'M') {
  2520. // 遇到 'M' 判定是否是新数组,新数组中没有点
  2521. if (points.length) {
  2522. // 如果存在点,则说明没有遇到 'Z',开始了一个新的多边形
  2523. polylines.push(points);
  2524. points = []; // 创建新的点
  2525. }
  2526. points.push([params[1], params[2]]);
  2527. } else if (cmd === 'Z') {
  2528. if (points.length) {
  2529. // 存在点
  2530. polygons.push(points);
  2531. points = []; // 开始新的点集合
  2532. }
  2533. // 如果不存在点,同时 'Z',则说明是错误,不处理
  2534. } else {
  2535. points.push([params[1], params[2]]);
  2536. }
  2537. }
  2538. // 说明 points 未放入 polygons 或者 polyline
  2539. // 仅当只有一个 M,没有 Z 时会发生这种情况
  2540. if (points.length > 0) {
  2541. polylines.push(points);
  2542. }
  2543. return {
  2544. polygons: polygons,
  2545. polylines: polylines
  2546. };
  2547. }
  2548. function isSamePoint(point1, point2) {
  2549. return point1[0] === point2[0] && point1[1] === point2[1];
  2550. }
  2551. function getPathBBox(segments, lineWidth) {
  2552. var xArr = [];
  2553. var yArr = [];
  2554. var segmentsWithAngle = [];
  2555. for (var i = 0; i < segments.length; i++) {
  2556. var segment = segments[i];
  2557. var currentPoint = segment.currentPoint,
  2558. params = segment.params,
  2559. prePoint = segment.prePoint;
  2560. var box = void 0;
  2561. switch (segment.command) {
  2562. case 'Q':
  2563. box = gMath.Quad.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4]);
  2564. break;
  2565. case 'C':
  2566. box = gMath.Cubic.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4], params[5], params[6]);
  2567. break;
  2568. case 'A':
  2569. var arcParams = segment.arcParams;
  2570. box = gMath.Arc.box(arcParams.cx, arcParams.cy, arcParams.rx, arcParams.ry, arcParams.xRotation, arcParams.startAngle, arcParams.endAngle);
  2571. break;
  2572. default:
  2573. xArr.push(currentPoint[0]);
  2574. yArr.push(currentPoint[1]);
  2575. break;
  2576. }
  2577. if (box) {
  2578. segment.box = box;
  2579. xArr.push(box.x, box.x + box.width);
  2580. yArr.push(box.y, box.y + box.height);
  2581. }
  2582. if (lineWidth && (segment.command === 'L' || segment.command === 'M') && segment.prePoint && segment.nextPoint) {
  2583. segmentsWithAngle.push(segment);
  2584. }
  2585. }
  2586. // bbox calculation should ignore NaN for path attribute
  2587. // ref: https://github.com/antvis/g/issues/210
  2588. // ref: https://github.com/antvis/G2/issues/3109
  2589. xArr = xArr.filter(function (item) {
  2590. return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
  2591. });
  2592. yArr = yArr.filter(function (item) {
  2593. return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
  2594. });
  2595. var minX = util.min(xArr);
  2596. var minY = util.min(yArr);
  2597. var maxX = util.max(xArr);
  2598. var maxY = util.max(yArr);
  2599. if (segmentsWithAngle.length === 0) {
  2600. return {
  2601. x: minX,
  2602. y: minY,
  2603. width: maxX - minX,
  2604. height: maxY - minY
  2605. };
  2606. }
  2607. for (var _i = 0; _i < segmentsWithAngle.length; _i++) {
  2608. var _segment = segmentsWithAngle[_i];
  2609. var _currentPoint = _segment.currentPoint;
  2610. var extra = void 0;
  2611. if (_currentPoint[0] === minX) {
  2612. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2613. minX = minX - extra.xExtra;
  2614. } else if (_currentPoint[0] === maxX) {
  2615. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2616. maxX = maxX + extra.xExtra;
  2617. }
  2618. if (_currentPoint[1] === minY) {
  2619. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2620. minY = minY - extra.yExtra;
  2621. } else if (_currentPoint[1] === maxY) {
  2622. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2623. maxY = maxY + extra.yExtra;
  2624. }
  2625. }
  2626. return {
  2627. x: minX,
  2628. y: minY,
  2629. width: maxX - minX,
  2630. height: maxY - minY
  2631. };
  2632. }
  2633. function getExtraFromSegmentWithAngle(segment, lineWidth) {
  2634. var prePoint = segment.prePoint,
  2635. currentPoint = segment.currentPoint,
  2636. nextPoint = segment.nextPoint;
  2637. var currentAndPre = Math.pow(currentPoint[0] - prePoint[0], 2) + Math.pow(currentPoint[1] - prePoint[1], 2);
  2638. var currentAndNext = Math.pow(currentPoint[0] - nextPoint[0], 2) + Math.pow(currentPoint[1] - nextPoint[1], 2);
  2639. var preAndNext = Math.pow(prePoint[0] - nextPoint[0], 2) + Math.pow(prePoint[1] - nextPoint[1], 2);
  2640. // 以 currentPoint 为顶点的夹角
  2641. var currentAngle = Math.acos((currentAndPre + currentAndNext - preAndNext) / (2 * Math.sqrt(currentAndPre) * Math.sqrt(currentAndNext)));
  2642. // 夹角为空、 0 或 PI 时,不需要计算夹角处的额外宽度
  2643. // 注意: 由于计算精度问题,夹角为 0 的情况计算出来的角度可能是一个很小的值,还需要判断其与 0 是否近似相等
  2644. if (!currentAngle || Math.sin(currentAngle) === 0 || util.isNumberEqual(currentAngle, 0)) {
  2645. return {
  2646. xExtra: 0,
  2647. yExtra: 0
  2648. };
  2649. }
  2650. var xAngle = Math.abs(Math.atan2(nextPoint[1] - currentPoint[1], nextPoint[0] - currentPoint[0]));
  2651. var yAngle = Math.abs(Math.atan2(nextPoint[0] - currentPoint[0], nextPoint[1] - currentPoint[1]));
  2652. // 将夹角转为锐角
  2653. xAngle = xAngle > Math.PI / 2 ? Math.PI - xAngle : xAngle;
  2654. yAngle = yAngle > Math.PI / 2 ? Math.PI - yAngle : yAngle;
  2655. // 这里不考虑在水平和垂直方向的投影,直接使用最大差值
  2656. // 由于上层统一加减了二分之一线宽,这里需要进行弥补
  2657. var extra = {
  2658. // 水平方向投影
  2659. xExtra: Math.cos(currentAngle / 2 - xAngle) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0,
  2660. // 垂直方向投影
  2661. yExtra: Math.cos(yAngle - currentAngle / 2) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0
  2662. };
  2663. return extra;
  2664. }
  2665. // 点对称
  2666. function toSymmetry(point, center) {
  2667. return [center[0] + (center[0] - point[0]), center[1] + (center[1] - point[1])];
  2668. }
  2669. var angleBetween = function angleBetween(v0, v1) {
  2670. var p = v0.x * v1.x + v0.y * v1.y;
  2671. var n = Math.sqrt((Math.pow(v0.x, 2) + Math.pow(v0.y, 2)) * (Math.pow(v1.x, 2) + Math.pow(v1.y, 2)));
  2672. var sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1 : 1;
  2673. var angle = sign * Math.acos(p / n);
  2674. return angle;
  2675. };
  2676. /**
  2677. * @see https://github.com/rveciana/svg-path-properties/blob/b6bd9a322966f6ef7a311872d80c56e3718de861/src/arc.ts#L121
  2678. */
  2679. var pointOnEllipticalArc = function pointOnEllipticalArc(p0, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p1, t) {
  2680. // In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
  2681. rx = Math.abs(rx);
  2682. ry = Math.abs(ry);
  2683. xAxisRotation = util.mod(xAxisRotation, 360);
  2684. var xAxisRotationRadians = deg2rad(xAxisRotation);
  2685. // If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
  2686. if (p0.x === p1.x && p0.y === p1.y) {
  2687. return {
  2688. x: p0.x,
  2689. y: p0.y,
  2690. ellipticalArcAngle: 0
  2691. }; // Check if angle is correct
  2692. }
  2693. // If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
  2694. if (rx === 0 || ry === 0) {
  2695. //return this.pointOnLine(p0, p1, t);
  2696. return {
  2697. x: 0,
  2698. y: 0,
  2699. ellipticalArcAngle: 0
  2700. }; // Check if angle is correct
  2701. }
  2702. // Following "Conversion from endpoint to center parameterization"
  2703. // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
  2704. // Step #1: Compute transformedPoint
  2705. var dx = (p0.x - p1.x) / 2;
  2706. var dy = (p0.y - p1.y) / 2;
  2707. var transformedPoint = {
  2708. x: Math.cos(xAxisRotationRadians) * dx + Math.sin(xAxisRotationRadians) * dy,
  2709. y: -Math.sin(xAxisRotationRadians) * dx + Math.cos(xAxisRotationRadians) * dy
  2710. };
  2711. // Ensure radii are large enough
  2712. var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
  2713. if (radiiCheck > 1) {
  2714. rx = Math.sqrt(radiiCheck) * rx;
  2715. ry = Math.sqrt(radiiCheck) * ry;
  2716. }
  2717. // Step #2: Compute transformedCenter
  2718. var cSquareNumerator = Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) - Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
  2719. var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
  2720. var cRadicand = cSquareNumerator / cSquareRootDenom;
  2721. // Make sure this never drops below zero because of precision
  2722. cRadicand = cRadicand < 0 ? 0 : cRadicand;
  2723. var cCoef = (largeArcFlag !== sweepFlag ? 1 : -1) * Math.sqrt(cRadicand);
  2724. var transformedCenter = {
  2725. x: cCoef * (rx * transformedPoint.y / ry),
  2726. y: cCoef * (-(ry * transformedPoint.x) / rx)
  2727. };
  2728. // Step #3: Compute center
  2729. var center = {
  2730. x: Math.cos(xAxisRotationRadians) * transformedCenter.x - Math.sin(xAxisRotationRadians) * transformedCenter.y + (p0.x + p1.x) / 2,
  2731. y: Math.sin(xAxisRotationRadians) * transformedCenter.x + Math.cos(xAxisRotationRadians) * transformedCenter.y + (p0.y + p1.y) / 2
  2732. };
  2733. // Step #4: Compute start/sweep angles
  2734. // Start angle of the elliptical arc prior to the stretch and rotate operations.
  2735. // Difference between the start and end angles
  2736. var startVector = {
  2737. x: (transformedPoint.x - transformedCenter.x) / rx,
  2738. y: (transformedPoint.y - transformedCenter.y) / ry
  2739. };
  2740. var startAngle = angleBetween({
  2741. x: 1,
  2742. y: 0
  2743. }, startVector);
  2744. var endVector = {
  2745. x: (-transformedPoint.x - transformedCenter.x) / rx,
  2746. y: (-transformedPoint.y - transformedCenter.y) / ry
  2747. };
  2748. var sweepAngle = angleBetween(startVector, endVector);
  2749. if (!sweepFlag && sweepAngle > 0) {
  2750. sweepAngle -= 2 * Math.PI;
  2751. } else if (sweepFlag && sweepAngle < 0) {
  2752. sweepAngle += 2 * Math.PI;
  2753. }
  2754. // We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
  2755. sweepAngle %= 2 * Math.PI;
  2756. // From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
  2757. var angle = startAngle + sweepAngle * t;
  2758. var ellipseComponentX = rx * Math.cos(angle);
  2759. var ellipseComponentY = ry * Math.sin(angle);
  2760. var point = {
  2761. x: Math.cos(xAxisRotationRadians) * ellipseComponentX - Math.sin(xAxisRotationRadians) * ellipseComponentY + center.x,
  2762. y: Math.sin(xAxisRotationRadians) * ellipseComponentX + Math.cos(xAxisRotationRadians) * ellipseComponentY + center.y,
  2763. ellipticalArcStartAngle: startAngle,
  2764. ellipticalArcEndAngle: startAngle + sweepAngle,
  2765. ellipticalArcAngle: angle,
  2766. ellipticalArcCenter: center,
  2767. resultantRx: rx,
  2768. resultantRy: ry
  2769. };
  2770. return point;
  2771. };
  2772. function path2Segments(path) {
  2773. var segments = [];
  2774. var currentPoint = null; // 当前图形
  2775. var nextParams = null; // 下一节点的 path 参数
  2776. var startMovePoint = null; // 开始 M 的点,可能会有多个
  2777. var lastStartMovePointIndex = 0; // 最近一个开始点 M 的索引
  2778. var count = path.length;
  2779. for (var i = 0; i < count; i++) {
  2780. var params = path[i];
  2781. nextParams = path[i + 1];
  2782. var command = params[0];
  2783. // 数学定义上的参数,便于后面的计算
  2784. var segment = {
  2785. command: command,
  2786. prePoint: currentPoint,
  2787. params: params,
  2788. startTangent: null,
  2789. endTangent: null,
  2790. currentPoint: null,
  2791. nextPoint: null,
  2792. arcParams: null,
  2793. box: null,
  2794. cubicParams: null
  2795. };
  2796. switch (command) {
  2797. case 'M':
  2798. startMovePoint = [params[1], params[2]];
  2799. lastStartMovePointIndex = i;
  2800. break;
  2801. case 'A':
  2802. var arcParams = getArcParams(currentPoint, params);
  2803. segment.arcParams = arcParams;
  2804. break;
  2805. }
  2806. if (command === 'Z') {
  2807. // 有了 Z 后,当前节点从开始 M 的点开始
  2808. currentPoint = startMovePoint;
  2809. // 如果当前点的命令为 Z,相当于当前点为最近一个 M 点,则下一个点直接指向最近一个 M 点的下一个点
  2810. nextParams = path[lastStartMovePointIndex + 1];
  2811. } else {
  2812. var len = params.length;
  2813. currentPoint = [params[len - 2], params[len - 1]];
  2814. }
  2815. if (nextParams && nextParams[0] === 'Z') {
  2816. // 如果下一个点的命令为 Z,则下一个点直接指向最近一个 M 点
  2817. nextParams = path[lastStartMovePointIndex];
  2818. if (segments[lastStartMovePointIndex]) {
  2819. // 如果下一个点的命令为 Z,则最近一个 M 点的前一个点为当前点
  2820. segments[lastStartMovePointIndex].prePoint = currentPoint;
  2821. }
  2822. }
  2823. segment.currentPoint = currentPoint;
  2824. // 如果当前点与最近一个 M 点相同,则最近一个 M 点的前一个点为当前点的前一个点
  2825. if (segments[lastStartMovePointIndex] && isSamePoint(currentPoint, segments[lastStartMovePointIndex].currentPoint)) {
  2826. segments[lastStartMovePointIndex].prePoint = segment.prePoint;
  2827. }
  2828. var nextPoint = nextParams ? [nextParams[nextParams.length - 2], nextParams[nextParams.length - 1]] : null;
  2829. segment.nextPoint = nextPoint;
  2830. // Add startTangent and endTangent
  2831. var prePoint = segment.prePoint;
  2832. if (['L', 'H', 'V'].includes(command)) {
  2833. segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
  2834. segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
  2835. } else if (command === 'Q') {
  2836. // 二次贝塞尔曲线只有一个控制点
  2837. var cp = [params[1], params[2]];
  2838. // 二次贝塞尔曲线的终点为 currentPoint
  2839. segment.startTangent = [prePoint[0] - cp[0], prePoint[1] - cp[1]];
  2840. segment.endTangent = [currentPoint[0] - cp[0], currentPoint[1] - cp[1]];
  2841. } else if (command === 'T') {
  2842. var preSegment = segments[i - 1];
  2843. var _cp = toSymmetry(preSegment.currentPoint, prePoint);
  2844. if (preSegment.command === 'Q') {
  2845. segment.command = 'Q';
  2846. segment.startTangent = [prePoint[0] - _cp[0], prePoint[1] - _cp[1]];
  2847. segment.endTangent = [currentPoint[0] - _cp[0], currentPoint[1] - _cp[1]];
  2848. } else {
  2849. // @ts-ignore
  2850. segment.command = 'TL';
  2851. segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
  2852. segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
  2853. }
  2854. } else if (command === 'C') {
  2855. // 三次贝塞尔曲线有两个控制点
  2856. var cp1 = [params[1], params[2]];
  2857. var cp2 = [params[3], params[4]];
  2858. segment.startTangent = [prePoint[0] - cp1[0], prePoint[1] - cp1[1]];
  2859. segment.endTangent = [currentPoint[0] - cp2[0], currentPoint[1] - cp2[1]];
  2860. // horizontal line, eg. ['C', 100, 100, 100, 100, 200, 200]
  2861. if (segment.startTangent[0] === 0 && segment.startTangent[1] === 0) {
  2862. segment.startTangent = [cp1[0] - cp2[0], cp1[1] - cp2[1]];
  2863. }
  2864. if (segment.endTangent[0] === 0 && segment.endTangent[1] === 0) {
  2865. segment.endTangent = [cp2[0] - cp1[0], cp2[1] - cp1[1]];
  2866. }
  2867. } else if (command === 'S') {
  2868. var _preSegment = segments[i - 1];
  2869. var _cp2 = toSymmetry(_preSegment.currentPoint, prePoint);
  2870. var _cp3 = [params[1], params[2]];
  2871. if (_preSegment.command === 'C') {
  2872. segment.command = 'C'; // 将 S 命令变换为 C 命令
  2873. segment.startTangent = [prePoint[0] - _cp2[0], prePoint[1] - _cp2[1]];
  2874. segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
  2875. } else {
  2876. // @ts-ignore
  2877. segment.command = 'SQ'; // 将 S 命令变换为 SQ 命令
  2878. segment.startTangent = [prePoint[0] - _cp3[0], prePoint[1] - _cp3[1]];
  2879. segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
  2880. }
  2881. } else if (command === 'A') {
  2882. var _getTangentAtRatio = getTangentAtRatio(segment, 0),
  2883. dx1 = _getTangentAtRatio.x,
  2884. dy1 = _getTangentAtRatio.y;
  2885. var _getTangentAtRatio2 = getTangentAtRatio(segment, 1, false),
  2886. dx2 = _getTangentAtRatio2.x,
  2887. dy2 = _getTangentAtRatio2.y;
  2888. segment.startTangent = [dx1, dy1];
  2889. segment.endTangent = [dx2, dy2];
  2890. }
  2891. segments.push(segment);
  2892. }
  2893. return segments;
  2894. }
  2895. /**
  2896. * Use length instead of ratio
  2897. */
  2898. function getTangentAtRatio(segment, ratio, sign) {
  2899. if (sign === void 0) {
  2900. sign = true;
  2901. }
  2902. var _segment$arcParams = segment.arcParams,
  2903. _segment$arcParams$rx = _segment$arcParams.rx,
  2904. rx = _segment$arcParams$rx === void 0 ? 0 : _segment$arcParams$rx,
  2905. _segment$arcParams$ry = _segment$arcParams.ry,
  2906. ry = _segment$arcParams$ry === void 0 ? 0 : _segment$arcParams$ry,
  2907. xRotation = _segment$arcParams.xRotation,
  2908. arcFlag = _segment$arcParams.arcFlag,
  2909. sweepFlag = _segment$arcParams.sweepFlag;
  2910. var p1 = pointOnEllipticalArc({
  2911. x: segment.prePoint[0],
  2912. y: segment.prePoint[1]
  2913. }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
  2914. x: segment.currentPoint[0],
  2915. y: segment.currentPoint[1]
  2916. }, ratio);
  2917. var p2 = pointOnEllipticalArc({
  2918. x: segment.prePoint[0],
  2919. y: segment.prePoint[1]
  2920. }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
  2921. x: segment.currentPoint[0],
  2922. y: segment.currentPoint[1]
  2923. }, sign ? ratio + 0.005 : ratio - 0.005);
  2924. var xDist = p2.x - p1.x;
  2925. var yDist = p2.y - p1.y;
  2926. var dist = Math.sqrt(xDist * xDist + yDist * yDist);
  2927. return {
  2928. x: -xDist / dist,
  2929. y: -yDist / dist
  2930. };
  2931. }
  2932. // 向量长度
  2933. function vMag(v) {
  2934. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  2935. }
  2936. // u.v/|u||v|,计算夹角的余弦值
  2937. function vRatio(u, v) {
  2938. // 当存在一个向量的长度为 0 时,夹角也为 0,即夹角的余弦值为 1
  2939. return vMag(u) * vMag(v) ? (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)) : 1;
  2940. }
  2941. // 向量角度
  2942. function vAngle(u, v) {
  2943. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
  2944. }
  2945. function getArcParams(startPoint, params) {
  2946. var rx = params[1];
  2947. var ry = params[2];
  2948. var xRotation = util.mod(deg2rad(params[3]), Math.PI * 2);
  2949. var arcFlag = params[4];
  2950. var sweepFlag = params[5];
  2951. // 弧形起点坐标
  2952. var x1 = startPoint[0];
  2953. var y1 = startPoint[1];
  2954. // 弧形终点坐标
  2955. var x2 = params[6];
  2956. var y2 = params[7];
  2957. var xp = Math.cos(xRotation) * (x1 - x2) / 2.0 + Math.sin(xRotation) * (y1 - y2) / 2.0;
  2958. var yp = -1 * Math.sin(xRotation) * (x1 - x2) / 2.0 + Math.cos(xRotation) * (y1 - y2) / 2.0;
  2959. var lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
  2960. if (lambda > 1) {
  2961. rx *= Math.sqrt(lambda);
  2962. ry *= Math.sqrt(lambda);
  2963. }
  2964. var diff = rx * rx * (yp * yp) + ry * ry * (xp * xp);
  2965. var f = diff ? Math.sqrt((rx * rx * (ry * ry) - diff) / diff) : 1;
  2966. if (arcFlag === sweepFlag) {
  2967. f *= -1;
  2968. }
  2969. if (isNaN(f)) {
  2970. f = 0;
  2971. }
  2972. // 旋转前的起点坐标,且当长半轴和短半轴的长度为 0 时,坐标按 (0, 0) 处理
  2973. var cxp = ry ? f * rx * yp / ry : 0;
  2974. var cyp = rx ? f * -ry * xp / rx : 0;
  2975. // 椭圆圆心坐标
  2976. var cx = (x1 + x2) / 2.0 + Math.cos(xRotation) * cxp - Math.sin(xRotation) * cyp;
  2977. var cy = (y1 + y2) / 2.0 + Math.sin(xRotation) * cxp + Math.cos(xRotation) * cyp;
  2978. // 起始点的单位向量
  2979. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  2980. // 终止点的单位向量
  2981. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  2982. // 计算起始点和圆心的连线,与 x 轴正方向的夹角
  2983. var theta = vAngle([1, 0], u);
  2984. // 计算圆弧起始点和终止点与椭圆圆心连线的夹角
  2985. var dTheta = vAngle(u, v);
  2986. if (vRatio(u, v) <= -1) {
  2987. dTheta = Math.PI;
  2988. }
  2989. if (vRatio(u, v) >= 1) {
  2990. dTheta = 0;
  2991. }
  2992. if (sweepFlag === 0 && dTheta > 0) {
  2993. dTheta = dTheta - 2 * Math.PI;
  2994. }
  2995. if (sweepFlag === 1 && dTheta < 0) {
  2996. dTheta = dTheta + 2 * Math.PI;
  2997. }
  2998. return {
  2999. cx: cx,
  3000. cy: cy,
  3001. // 弧形的起点和终点相同时,长轴和短轴的长度按 0 处理
  3002. rx: isSamePoint(startPoint, [x2, y2]) ? 0 : rx,
  3003. ry: isSamePoint(startPoint, [x2, y2]) ? 0 : ry,
  3004. startAngle: theta,
  3005. endAngle: theta + dTheta,
  3006. xRotation: xRotation,
  3007. arcFlag: arcFlag,
  3008. sweepFlag: sweepFlag
  3009. };
  3010. }
  3011. function commandsToPathString(commands, object, transform) {
  3012. var _object$parsedStyle = object.parsedStyle,
  3013. _object$parsedStyle$d = _object$parsedStyle.defX,
  3014. defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
  3015. _object$parsedStyle$d2 = _object$parsedStyle.defY,
  3016. defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
  3017. return commands.reduce(function (prev, cur) {
  3018. var path = '';
  3019. if (cur[0] === 'M' || cur[0] === 'L') {
  3020. var p = glMatrix.vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
  3021. if (transform) {
  3022. glMatrix.vec3.transformMat4(p, p, transform);
  3023. }
  3024. path = "" + cur[0] + p[0] + "," + p[1];
  3025. } else if (cur[0] === 'Z') {
  3026. path = cur[0];
  3027. } else if (cur[0] === 'C') {
  3028. var p1 = glMatrix.vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
  3029. var p2 = glMatrix.vec3.fromValues(cur[3] - defX, cur[4] - defY, 0);
  3030. var p3 = glMatrix.vec3.fromValues(cur[5] - defX, cur[6] - defY, 0);
  3031. if (transform) {
  3032. glMatrix.vec3.transformMat4(p1, p1, transform);
  3033. glMatrix.vec3.transformMat4(p2, p2, transform);
  3034. glMatrix.vec3.transformMat4(p3, p3, transform);
  3035. }
  3036. path = "" + cur[0] + p1[0] + "," + p1[1] + "," + p2[0] + "," + p2[1] + "," + p3[0] + "," + p3[1];
  3037. } else if (cur[0] === 'A') {
  3038. var c = glMatrix.vec3.fromValues(cur[6] - defX, cur[7] - defY, 0);
  3039. if (transform) {
  3040. glMatrix.vec3.transformMat4(c, c, transform);
  3041. }
  3042. path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "," + cur[5] + "," + c[0] + "," + c[1];
  3043. } else if (cur[0] === 'Q') {
  3044. var _p = glMatrix.vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
  3045. var _p2 = glMatrix.vec3.fromValues(cur[3] - defX, cur[4] - defY, 0);
  3046. if (transform) {
  3047. glMatrix.vec3.transformMat4(_p, _p, transform);
  3048. glMatrix.vec3.transformMat4(_p2, _p2, transform);
  3049. }
  3050. path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "}";
  3051. }
  3052. return prev += path;
  3053. }, '');
  3054. }
  3055. function lineToCommands(x1, y1, x2, y2) {
  3056. return [['M', x1, y1], ['L', x2, y2]];
  3057. }
  3058. function ellipseToCommands(rx, ry, cx, cy) {
  3059. var factor = (-1 + Math.sqrt(2)) / 3 * 4;
  3060. var dx = rx * factor;
  3061. var dy = ry * factor;
  3062. var left = cx - rx;
  3063. var right = cx + rx;
  3064. var top = cy - ry;
  3065. var bottom = cy + ry;
  3066. return [['M', left, cy], ['C', left, cy - dy, cx - dx, top, cx, top], ['C', cx + dx, top, right, cy - dy, right, cy], ['C', right, cy + dy, cx + dx, bottom, cx, bottom], ['C', cx - dx, bottom, left, cy + dy, left, cy], ['Z']];
  3067. }
  3068. function polygonToCommands(points, closed) {
  3069. var result = points.map(function (point, i) {
  3070. return [i === 0 ? 'M' : 'L', point[0], point[1]];
  3071. });
  3072. if (closed) {
  3073. result.push(['Z']);
  3074. }
  3075. return result;
  3076. }
  3077. function rectToCommands(width, height, x, y, radius) {
  3078. // @see https://gist.github.com/danielpquinn/dd966af424030d47e476
  3079. if (radius) {
  3080. var tlr = radius[0],
  3081. trr = radius[1],
  3082. brr = radius[2],
  3083. blr = radius[3];
  3084. var signX = width > 0 ? 1 : -1;
  3085. var signY = height > 0 ? 1 : -1;
  3086. // sweep-flag @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths#arcs
  3087. var sweepFlag = signX + signY !== 0 ? 1 : 0;
  3088. return [['M', signX * tlr + x, y], ['L', width - signX * trr + x, y], trr ? ['A', trr, trr, 0, 0, sweepFlag, width + x, signY * trr + y] : null, ['L', width + x, height - signY * brr + y], brr ? ['A', brr, brr, 0, 0, sweepFlag, width + x - signX * brr, height + y] : null, ['L', x + signX * blr, height + y], blr ? ['A', blr, blr, 0, 0, sweepFlag, x, height + y - signY * blr] : null, ['L', x, signY * tlr + y], tlr ? ['A', tlr, tlr, 0, 0, sweepFlag, signX * tlr + x, y] : null, ['Z']].filter(function (command) {
  3089. return command;
  3090. });
  3091. }
  3092. return [['M', x, y], ['L', x + width, y], ['L', x + width, y + height], ['L', x, y + height], ['Z']];
  3093. }
  3094. /**
  3095. * convert object to path, should account for:
  3096. * * transform & origin
  3097. * * anchor
  3098. * * lineWidth
  3099. */
  3100. function convertToPath(object, transform) {
  3101. if (transform === void 0) {
  3102. transform = object.getLocalTransform();
  3103. }
  3104. var commands = [];
  3105. switch (object.nodeName) {
  3106. case exports.Shape.LINE:
  3107. var _object$parsedStyle2 = object.parsedStyle,
  3108. x1 = _object$parsedStyle2.x1,
  3109. y1 = _object$parsedStyle2.y1,
  3110. x2 = _object$parsedStyle2.x2,
  3111. y2 = _object$parsedStyle2.y2;
  3112. commands = lineToCommands(x1, y1, x2, y2);
  3113. break;
  3114. case exports.Shape.CIRCLE:
  3115. {
  3116. var _object$parsedStyle3 = object.parsedStyle,
  3117. r = _object$parsedStyle3.r,
  3118. cx = _object$parsedStyle3.cx,
  3119. cy = _object$parsedStyle3.cy;
  3120. commands = ellipseToCommands(r, r, cx, cy);
  3121. break;
  3122. }
  3123. case exports.Shape.ELLIPSE:
  3124. {
  3125. var _object$parsedStyle4 = object.parsedStyle,
  3126. rx = _object$parsedStyle4.rx,
  3127. ry = _object$parsedStyle4.ry,
  3128. _cx = _object$parsedStyle4.cx,
  3129. _cy = _object$parsedStyle4.cy;
  3130. commands = ellipseToCommands(rx, ry, _cx, _cy);
  3131. break;
  3132. }
  3133. case exports.Shape.POLYLINE:
  3134. case exports.Shape.POLYGON:
  3135. var points = object.parsedStyle.points;
  3136. commands = polygonToCommands(points.points, object.nodeName === exports.Shape.POLYGON);
  3137. break;
  3138. case exports.Shape.RECT:
  3139. var _object$parsedStyle5 = object.parsedStyle,
  3140. width = _object$parsedStyle5.width,
  3141. height = _object$parsedStyle5.height,
  3142. x = _object$parsedStyle5.x,
  3143. y = _object$parsedStyle5.y,
  3144. radius = _object$parsedStyle5.radius;
  3145. var hasRadius = radius && radius.some(function (r) {
  3146. return r !== 0;
  3147. });
  3148. commands = rectToCommands(width, height, x, y, hasRadius && radius.map(function (r) {
  3149. return util.clamp(r, 0, Math.min(Math.abs(width) / 2, Math.abs(height) / 2));
  3150. }));
  3151. break;
  3152. case exports.Shape.PATH:
  3153. var absolutePath = object.parsedStyle.path.absolutePath;
  3154. commands = [].concat(absolutePath);
  3155. break;
  3156. }
  3157. if (commands.length) {
  3158. return commandsToPathString(commands, object, transform);
  3159. }
  3160. }
  3161. function translatePathToString(absolutePath, defX, defY, startOffsetX, startOffsetY, endOffsetX, endOffsetY) {
  3162. if (startOffsetX === void 0) {
  3163. startOffsetX = 0;
  3164. }
  3165. if (startOffsetY === void 0) {
  3166. startOffsetY = 0;
  3167. }
  3168. if (endOffsetX === void 0) {
  3169. endOffsetX = 0;
  3170. }
  3171. if (endOffsetY === void 0) {
  3172. endOffsetY = 0;
  3173. }
  3174. var newValue = absolutePath.map(function (params, i) {
  3175. var command = params[0];
  3176. var nextSegment = absolutePath[i + 1];
  3177. var useStartOffset = i === 0 && (startOffsetX !== 0 || startOffsetY !== 0);
  3178. var useEndOffset = (i === absolutePath.length - 1 || nextSegment && (nextSegment[0] === 'M' || nextSegment[0] === 'Z')) && endOffsetX !== 0 && endOffsetY !== 0;
  3179. switch (command) {
  3180. case 'M':
  3181. // Use start marker offset
  3182. if (useStartOffset) {
  3183. return "M " + (params[1] - defX + startOffsetX) + "," + (params[2] - defY + startOffsetY) + " L " + (params[1] - defX) + "," + (params[2] - defY);
  3184. } else {
  3185. return "M " + (params[1] - defX) + "," + (params[2] - defY);
  3186. }
  3187. case 'L':
  3188. return "L " + (params[1] - defX + (useEndOffset ? endOffsetX : 0)) + "," + (params[2] - defY + (useEndOffset ? endOffsetY : 0));
  3189. case 'Q':
  3190. return "Q " + (params[1] - defX) + " " + (params[2] - defY) + "," + (params[3] - defX) + " " + (params[4] - defY) + (useEndOffset ? " L " + (params[3] - defX + endOffsetX) + "," + (params[4] - defY + endOffsetY) : '');
  3191. case 'C':
  3192. return "C " + (params[1] - defX) + " " + (params[2] - defY) + "," + (params[3] - defX) + " " + (params[4] - defY) + "," + (params[5] - defX) + " " + (params[6] - defY) + (useEndOffset ? " L " + (params[5] - defX + endOffsetX) + "," + (params[6] - defY + endOffsetY) : '');
  3193. case 'A':
  3194. return "A " + params[1] + " " + params[2] + " " + params[3] + " " + params[4] + " " + params[5] + " " + (params[6] - defX) + " " + (params[7] - defY) + (useEndOffset ? " L " + (params[6] - defX + endOffsetX) + "," + (params[7] - defY + endOffsetY) : '');
  3195. case 'Z':
  3196. return 'Z';
  3197. }
  3198. }).join(' ');
  3199. if (~newValue.indexOf('NaN')) {
  3200. return '';
  3201. }
  3202. return newValue;
  3203. }
  3204. function isFillOrStrokeAffected(pointerEvents, fill, stroke) {
  3205. // account for pointerEvents
  3206. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
  3207. var hasFill = false;
  3208. var hasStroke = false;
  3209. var isFillOtherThanNone = !!fill && !fill.isNone;
  3210. var isStrokeOtherThanNone = !!stroke && !stroke.isNone;
  3211. if (pointerEvents === 'visiblepainted' || pointerEvents === 'painted' || pointerEvents === 'auto') {
  3212. hasFill = isFillOtherThanNone;
  3213. hasStroke = isStrokeOtherThanNone;
  3214. } else if (pointerEvents === 'visiblefill' || pointerEvents === 'fill') {
  3215. hasFill = true;
  3216. } else if (pointerEvents === 'visiblestroke' || pointerEvents === 'stroke') {
  3217. hasStroke = true;
  3218. } else if (pointerEvents === 'visible' || pointerEvents === 'all') {
  3219. // The values of the fill and stroke do not affect event processing.
  3220. hasFill = true;
  3221. hasStroke = true;
  3222. }
  3223. return [hasFill, hasStroke];
  3224. }
  3225. var AsyncParallelHook = /*#__PURE__*/function () {
  3226. function AsyncParallelHook() {
  3227. this.callbacks = [];
  3228. }
  3229. var _proto = AsyncParallelHook.prototype;
  3230. _proto.getCallbacksNum = function getCallbacksNum() {
  3231. return this.callbacks.length;
  3232. };
  3233. _proto.tapPromise = function tapPromise(options, fn) {
  3234. this.callbacks.push(fn);
  3235. };
  3236. _proto.promise = function promise() {
  3237. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3238. args[_key] = arguments[_key];
  3239. }
  3240. return Promise.all(this.callbacks.map(function (callback) {
  3241. return callback.apply(void 0, args);
  3242. }));
  3243. };
  3244. return AsyncParallelHook;
  3245. }();
  3246. var AsyncSeriesWaterfallHook = /*#__PURE__*/function () {
  3247. function AsyncSeriesWaterfallHook() {
  3248. this.callbacks = [];
  3249. }
  3250. var _proto = AsyncSeriesWaterfallHook.prototype;
  3251. _proto.tapPromise = function tapPromise(options, fn) {
  3252. this.callbacks.push(fn);
  3253. };
  3254. _proto.promise = /*#__PURE__*/function () {
  3255. var _promise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
  3256. var _this$callbacks,
  3257. result,
  3258. i,
  3259. callback,
  3260. _args = arguments;
  3261. return _regeneratorRuntime().wrap(function _callee$(_context) {
  3262. while (1) switch (_context.prev = _context.next) {
  3263. case 0:
  3264. if (!this.callbacks.length) {
  3265. _context.next = 14;
  3266. break;
  3267. }
  3268. _context.next = 3;
  3269. return (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, _args);
  3270. case 3:
  3271. result = _context.sent;
  3272. i = 0;
  3273. case 5:
  3274. if (!(i < this.callbacks.length - 1)) {
  3275. _context.next = 13;
  3276. break;
  3277. }
  3278. callback = this.callbacks[i]; // @ts-ignore
  3279. _context.next = 9;
  3280. return callback(result);
  3281. case 9:
  3282. result = _context.sent;
  3283. case 10:
  3284. i++;
  3285. _context.next = 5;
  3286. break;
  3287. case 13:
  3288. return _context.abrupt("return", result);
  3289. case 14:
  3290. return _context.abrupt("return", null);
  3291. case 15:
  3292. case "end":
  3293. return _context.stop();
  3294. }
  3295. }, _callee, this);
  3296. }));
  3297. function promise() {
  3298. return _promise.apply(this, arguments);
  3299. }
  3300. return promise;
  3301. }();
  3302. return AsyncSeriesWaterfallHook;
  3303. }();
  3304. var SyncHook = /*#__PURE__*/function () {
  3305. function SyncHook() {
  3306. this.callbacks = [];
  3307. }
  3308. var _proto = SyncHook.prototype;
  3309. _proto.tap = function tap(options, fn) {
  3310. this.callbacks.push(fn);
  3311. };
  3312. _proto.call = function call() {
  3313. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3314. args[_key] = arguments[_key];
  3315. }
  3316. this.callbacks.forEach(function (callback) {
  3317. callback.apply(void 0, args);
  3318. });
  3319. };
  3320. return SyncHook;
  3321. }();
  3322. var SyncWaterfallHook = /*#__PURE__*/function () {
  3323. function SyncWaterfallHook() {
  3324. this.callbacks = [];
  3325. }
  3326. var _proto = SyncWaterfallHook.prototype;
  3327. _proto.tap = function tap(options, fn) {
  3328. this.callbacks.push(fn);
  3329. };
  3330. _proto.call = function call() {
  3331. if (this.callbacks.length) {
  3332. var _this$callbacks;
  3333. var result = (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, arguments);
  3334. for (var i = 0; i < this.callbacks.length - 1; i++) {
  3335. var callback = this.callbacks[i];
  3336. // @ts-ignore
  3337. result = callback(result);
  3338. }
  3339. return result;
  3340. }
  3341. return null;
  3342. };
  3343. return SyncWaterfallHook;
  3344. }();
  3345. var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui'];
  3346. var stringRegExp = /([\"\'])[^\'\"]+\1/;
  3347. function toFontString(attributes) {
  3348. var fontSize = attributes.fontSize,
  3349. fontFamily = attributes.fontFamily,
  3350. fontStyle = attributes.fontStyle,
  3351. fontVariant = attributes.fontVariant,
  3352. fontWeight = attributes.fontWeight;
  3353. // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
  3354. // const fontSizeString: string = isNumber(fontSize) ? `${fontSize}px` : fontSize.toString();
  3355. var fontSizeString = util.isNumber(fontSize) && fontSize + "px" || '16px';
  3356. // Clean-up fontFamily property by quoting each font name
  3357. // this will support font names with spaces
  3358. var fontFamilies = fontFamily.split(',');
  3359. for (var i = fontFamilies.length - 1; i >= 0; i--) {
  3360. // Trim any extra white-space
  3361. var _fontFamily = fontFamilies[i].trim();
  3362. // Check if font already contains strings
  3363. if (!stringRegExp.test(_fontFamily) && genericFontFamilies.indexOf(_fontFamily) < 0) {
  3364. _fontFamily = "\"" + _fontFamily + "\"";
  3365. }
  3366. fontFamilies[i] = _fontFamily;
  3367. }
  3368. return fontStyle + " " + fontVariant + " " + fontWeight + " " + fontSizeString + " " + fontFamilies.join(',');
  3369. }
  3370. /**
  3371. * Thanks for following contributor of codes
  3372. * https://gist.github.com/1866474
  3373. * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  3374. * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  3375. * https://github.com/Financial-Times/polyfill-library/blob/master/polyfills/requestAnimationFrame/polyfill.js
  3376. **/
  3377. var uId = 1;
  3378. var uniqueId = function uniqueId() {
  3379. return uId++;
  3380. };
  3381. // We use `self` instead of `window` for `WebWorker` support.
  3382. var root = typeof self === 'object' && self.self == self ? self :
  3383. // @ts-ignore
  3384. typeof global === 'object' && global.global == global ?
  3385. // @ts-ignore
  3386. global : {};
  3387. var nowOffset = Date.now();
  3388. // use performance api if exist, otherwise use Date.now.
  3389. // Date.now polyfill required.
  3390. var pnow = function pnow() {
  3391. if (root.performance && typeof root.performance.now === 'function') {
  3392. return root.performance.now();
  3393. }
  3394. // fallback
  3395. return Date.now() - nowOffset;
  3396. };
  3397. var reservedCBs = {};
  3398. var lastTime = Date.now();
  3399. var polyfillRaf = function polyfillRaf(callback) {
  3400. if (typeof callback !== 'function') {
  3401. throw new TypeError(callback + ' is not a function');
  3402. }
  3403. var currentTime = Date.now();
  3404. var gap = currentTime - lastTime;
  3405. var delay = gap > 16 ? 0 : 16 - gap;
  3406. var id = uniqueId();
  3407. reservedCBs[id] = callback;
  3408. // keys(reservedCBs).length > 1 의미는 이미 setTimeout 이 걸려있는 경우.
  3409. // 함께 callback 이 실행될 수 있게 reservedCBs 에만 추가해주고 return
  3410. if (Object.keys(reservedCBs).length > 1) return id;
  3411. setTimeout(function () {
  3412. lastTime = currentTime;
  3413. var copied = reservedCBs;
  3414. reservedCBs = {};
  3415. Object.keys(copied).forEach(function (key) {
  3416. return copied[key](pnow());
  3417. });
  3418. }, delay);
  3419. return id;
  3420. };
  3421. var polyfillCaf = function polyfillCaf(id) {
  3422. delete reservedCBs[id];
  3423. };
  3424. var vendorPrefixes = ['', 'webkit', 'moz', 'ms', 'o'];
  3425. var getRequestAnimationFrame = function getRequestAnimationFrame(vp) {
  3426. if (typeof vp !== 'string') return polyfillRaf;
  3427. if (vp === '') return root['requestAnimationFrame'];
  3428. return root[vp + 'RequestAnimationFrame'];
  3429. };
  3430. var getCancelAnimationFrame = function getCancelAnimationFrame(vp) {
  3431. if (typeof vp !== 'string') return polyfillCaf;
  3432. if (vp === '') return root['cancelAnimationFrame'];
  3433. return root[vp + 'CancelAnimationFrame'] || root[vp + 'CancelRequestAnimationFrame'];
  3434. };
  3435. var find = function find(arr, predicate) {
  3436. var i = 0;
  3437. while (arr[i] !== void 0) {
  3438. if (predicate(arr[i])) return arr[i];
  3439. i = i + 1;
  3440. }
  3441. };
  3442. var vp = find(vendorPrefixes, function (vp) {
  3443. return !!getRequestAnimationFrame(vp);
  3444. });
  3445. var raf = getRequestAnimationFrame(vp);
  3446. var caf = getCancelAnimationFrame(vp);
  3447. root.requestAnimationFrame = raf;
  3448. root.cancelAnimationFrame = caf;
  3449. var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i;
  3450. var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i;
  3451. var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i;
  3452. var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/gi;
  3453. function spaceColorStops(colorStops) {
  3454. var _colorStops$length;
  3455. var length = colorStops.length;
  3456. colorStops[length - 1].length = (_colorStops$length = colorStops[length - 1].length) !== null && _colorStops$length !== void 0 ? _colorStops$length : {
  3457. type: '%',
  3458. value: '100'
  3459. };
  3460. if (length > 1) {
  3461. var _colorStops$0$length;
  3462. colorStops[0].length = (_colorStops$0$length = colorStops[0].length) !== null && _colorStops$0$length !== void 0 ? _colorStops$0$length : {
  3463. type: '%',
  3464. value: '0'
  3465. };
  3466. }
  3467. var previousIndex = 0;
  3468. var previousOffset = Number(colorStops[0].length.value);
  3469. for (var i = 1; i < length; i++) {
  3470. var _colorStops$i$length;
  3471. // support '%' & 'px'
  3472. var offset = (_colorStops$i$length = colorStops[i].length) === null || _colorStops$i$length === void 0 ? void 0 : _colorStops$i$length.value;
  3473. if (!util.isNil(offset) && !util.isNil(previousOffset)) {
  3474. for (var j = 1; j < i - previousIndex; j++) colorStops[previousIndex + j].length = {
  3475. type: '%',
  3476. value: "" + (previousOffset + (Number(offset) - previousOffset) * j / (i - previousIndex))
  3477. };
  3478. previousIndex = i;
  3479. previousOffset = Number(offset);
  3480. }
  3481. }
  3482. }
  3483. // The position of the gradient line's starting point.
  3484. // different from CSS side(to top) @see https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#values
  3485. var SideOrCornerToDegMap = {
  3486. left: 270 - 90,
  3487. top: 0 - 90,
  3488. bottom: 180 - 90,
  3489. right: 90 - 90,
  3490. 'left top': 315 - 90,
  3491. 'top left': 315 - 90,
  3492. 'left bottom': 225 - 90,
  3493. 'bottom left': 225 - 90,
  3494. 'right top': 45 - 90,
  3495. 'top right': 45 - 90,
  3496. 'right bottom': 135 - 90,
  3497. 'bottom right': 135 - 90
  3498. };
  3499. var angleToDeg = memoize(function (orientation) {
  3500. var angle;
  3501. if (orientation.type === 'angular') {
  3502. angle = Number(orientation.value);
  3503. } else {
  3504. angle = SideOrCornerToDegMap[orientation.value] || 0;
  3505. }
  3506. return getOrCreateUnitValue(angle, 'deg');
  3507. });
  3508. var positonToCSSUnitValue = memoize(function (position) {
  3509. var cx = 50;
  3510. var cy = 50;
  3511. var unitX = '%';
  3512. var unitY = '%';
  3513. if ((position === null || position === void 0 ? void 0 : position.type) === 'position') {
  3514. var _position$value = position.value,
  3515. x = _position$value.x,
  3516. y = _position$value.y;
  3517. if ((x === null || x === void 0 ? void 0 : x.type) === 'position-keyword') {
  3518. if (x.value === 'left') {
  3519. cx = 0;
  3520. } else if (x.value === 'center') {
  3521. cx = 50;
  3522. } else if (x.value === 'right') {
  3523. cx = 100;
  3524. } else if (x.value === 'top') {
  3525. cy = 0;
  3526. } else if (x.value === 'bottom') {
  3527. cy = 100;
  3528. }
  3529. }
  3530. if ((y === null || y === void 0 ? void 0 : y.type) === 'position-keyword') {
  3531. if (y.value === 'left') {
  3532. cx = 0;
  3533. } else if (y.value === 'center') {
  3534. cy = 50;
  3535. } else if (y.value === 'right') {
  3536. cx = 100;
  3537. } else if (y.value === 'top') {
  3538. cy = 0;
  3539. } else if (y.value === 'bottom') {
  3540. cy = 100;
  3541. }
  3542. }
  3543. if ((x === null || x === void 0 ? void 0 : x.type) === 'px' || (x === null || x === void 0 ? void 0 : x.type) === '%' || (x === null || x === void 0 ? void 0 : x.type) === 'em') {
  3544. unitX = x === null || x === void 0 ? void 0 : x.type;
  3545. cx = Number(x.value);
  3546. }
  3547. if ((y === null || y === void 0 ? void 0 : y.type) === 'px' || (y === null || y === void 0 ? void 0 : y.type) === '%' || (y === null || y === void 0 ? void 0 : y.type) === 'em') {
  3548. unitY = y === null || y === void 0 ? void 0 : y.type;
  3549. cy = Number(y.value);
  3550. }
  3551. }
  3552. return {
  3553. cx: getOrCreateUnitValue(cx, unitX),
  3554. cy: getOrCreateUnitValue(cy, unitY)
  3555. };
  3556. });
  3557. var parseGradient$1 = memoize(function (colorStr) {
  3558. if (colorStr.indexOf('linear') > -1 || colorStr.indexOf('radial') > -1) {
  3559. var ast = parseGradient(colorStr);
  3560. return ast.map(function (_ref) {
  3561. var type = _ref.type,
  3562. orientation = _ref.orientation,
  3563. colorStops = _ref.colorStops;
  3564. spaceColorStops(colorStops);
  3565. var steps = colorStops.map(function (colorStop) {
  3566. // TODO: only support % for now, should calc percentage of axis length when using px/em
  3567. return {
  3568. offset: getOrCreateUnitValue(Number(colorStop.length.value), '%'),
  3569. color: colorStopToString(colorStop)
  3570. };
  3571. });
  3572. if (type === 'linear-gradient') {
  3573. return new CSSGradientValue(exports.GradientType.LinearGradient, {
  3574. angle: orientation ? angleToDeg(orientation) : Odeg,
  3575. steps: steps
  3576. });
  3577. } else if (type === 'radial-gradient') {
  3578. if (!orientation) {
  3579. orientation = [{
  3580. type: 'shape',
  3581. value: 'circle'
  3582. }];
  3583. }
  3584. if (orientation[0].type === 'shape' && orientation[0].value === 'circle') {
  3585. var _positonToCSSUnitValu = positonToCSSUnitValue(orientation[0].at),
  3586. cx = _positonToCSSUnitValu.cx,
  3587. cy = _positonToCSSUnitValu.cy;
  3588. var size;
  3589. if (orientation[0].style) {
  3590. var _orientation$0$style = orientation[0].style,
  3591. _type = _orientation$0$style.type,
  3592. value = _orientation$0$style.value;
  3593. if (_type === 'extent-keyword') {
  3594. size = getOrCreateKeyword(value);
  3595. } else {
  3596. size = getOrCreateUnitValue(value, _type);
  3597. }
  3598. }
  3599. return new CSSGradientValue(exports.GradientType.RadialGradient, {
  3600. cx: cx,
  3601. cy: cy,
  3602. size: size,
  3603. steps: steps
  3604. });
  3605. }
  3606. // TODO: support ellipse shape
  3607. // TODO: repeating-linear-gradient & repeating-radial-gradient
  3608. // } else if (type === 'repeating-linear-gradient') {
  3609. // } else if (type === 'repeating-radial-gradient') {
  3610. }
  3611. });
  3612. }
  3613. // legacy format, should be deprecated later
  3614. var type = colorStr[0];
  3615. if (colorStr[1] === '(' || colorStr[2] === '(') {
  3616. if (type === 'l') {
  3617. var arr = regexLG.exec(colorStr);
  3618. if (arr) {
  3619. var _arr$2$match;
  3620. var steps = ((_arr$2$match = arr[2].match(regexColorStop)) === null || _arr$2$match === void 0 ? void 0 : _arr$2$match.map(function (stop) {
  3621. return stop.split(':');
  3622. })) || [];
  3623. return [new CSSGradientValue(exports.GradientType.LinearGradient, {
  3624. angle: getOrCreateUnitValue(parseFloat(arr[1]), 'deg'),
  3625. steps: steps.map(function (_ref2) {
  3626. var offset = _ref2[0],
  3627. color = _ref2[1];
  3628. return {
  3629. offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
  3630. color: color
  3631. };
  3632. })
  3633. })];
  3634. }
  3635. } else if (type === 'r') {
  3636. var parsedRadialGradient = parseRadialGradient(colorStr);
  3637. if (parsedRadialGradient) {
  3638. if (util.isString(parsedRadialGradient)) {
  3639. colorStr = parsedRadialGradient;
  3640. } else {
  3641. return [new CSSGradientValue(exports.GradientType.RadialGradient, parsedRadialGradient)];
  3642. }
  3643. }
  3644. } else if (type === 'p') {
  3645. return parsePattern(colorStr);
  3646. }
  3647. }
  3648. });
  3649. function parseRadialGradient(gradientStr) {
  3650. var arr = regexRG.exec(gradientStr);
  3651. if (arr) {
  3652. var _arr$4$match;
  3653. var steps = ((_arr$4$match = arr[4].match(regexColorStop)) === null || _arr$4$match === void 0 ? void 0 : _arr$4$match.map(function (stop) {
  3654. return stop.split(':');
  3655. })) || [];
  3656. return {
  3657. cx: getOrCreateUnitValue(50, '%'),
  3658. cy: getOrCreateUnitValue(50, '%'),
  3659. steps: steps.map(function (_ref3) {
  3660. var offset = _ref3[0],
  3661. color = _ref3[1];
  3662. return {
  3663. offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
  3664. color: color
  3665. };
  3666. })
  3667. };
  3668. }
  3669. return null;
  3670. }
  3671. function parsePattern(patternStr) {
  3672. var arr = regexPR.exec(patternStr);
  3673. if (arr) {
  3674. var repetition = arr[1];
  3675. var src = arr[2];
  3676. switch (repetition) {
  3677. case 'a':
  3678. repetition = 'repeat';
  3679. break;
  3680. case 'x':
  3681. repetition = 'repeat-x';
  3682. break;
  3683. case 'y':
  3684. repetition = 'repeat-y';
  3685. break;
  3686. case 'n':
  3687. repetition = 'no-repeat';
  3688. break;
  3689. default:
  3690. repetition = 'no-repeat';
  3691. }
  3692. return {
  3693. image: src,
  3694. // @ts-ignore
  3695. repetition: repetition
  3696. };
  3697. }
  3698. return null;
  3699. }
  3700. function isCSSGradientValue(object) {
  3701. return !!object.type && !!object.value;
  3702. }
  3703. function isPattern(object) {
  3704. return object && !!object.image;
  3705. }
  3706. function isCSSRGB(object) {
  3707. return object && !util.isNil(object.r) && !util.isNil(object.g) && !util.isNil(object.b);
  3708. }
  3709. /**
  3710. * @see https://github.com/WebKit/WebKit/blob/main/Source/WebCore/css/parser/CSSParser.cpp#L97
  3711. */
  3712. var parseColor = memoize(function (colorStr) {
  3713. if (isPattern(colorStr)) {
  3714. return _extends({
  3715. repetition: 'repeat'
  3716. }, colorStr);
  3717. }
  3718. if (util.isNil(colorStr)) {
  3719. colorStr = '';
  3720. }
  3721. if (colorStr === 'transparent') {
  3722. // transparent black
  3723. return transparentColor;
  3724. } else if (colorStr === 'currentColor') {
  3725. // @see https://github.com/adobe-webplatform/Snap.svg/issues/526
  3726. colorStr = 'black';
  3727. }
  3728. // support CSS gradient syntax
  3729. var g = parseGradient$1(colorStr);
  3730. if (g) {
  3731. return g;
  3732. }
  3733. // constants
  3734. var color = d3.color(colorStr);
  3735. var rgba = [0, 0, 0, 0];
  3736. if (color !== null) {
  3737. rgba[0] = color.r || 0;
  3738. rgba[1] = color.g || 0;
  3739. rgba[2] = color.b || 0;
  3740. rgba[3] = color.opacity;
  3741. }
  3742. // return new CSSRGB(...rgba);
  3743. return getOrCreateRGBA.apply(void 0, rgba);
  3744. });
  3745. function mergeColors(left, right) {
  3746. // only support constant value, exclude gradient & pattern
  3747. if (!isCSSRGB(left) || !isCSSRGB(right)) {
  3748. return;
  3749. }
  3750. return [[Number(left.r), Number(left.g), Number(left.b), Number(left.alpha)], [Number(right.r), Number(right.g), Number(right.b), Number(right.alpha)], function (color) {
  3751. var rgba = color.slice();
  3752. if (rgba[3]) {
  3753. for (var i = 0; i < 3; i++) rgba[i] = Math.round(util.clamp(rgba[i], 0, 255));
  3754. }
  3755. rgba[3] = util.clamp(rgba[3], 0, 1);
  3756. return "rgba(" + rgba.join(',') + ")";
  3757. }];
  3758. }
  3759. function parseDimension(unitRegExp, string) {
  3760. if (util.isNil(string)) {
  3761. return getOrCreateUnitValue(0, 'px');
  3762. }
  3763. string = ("" + string).trim().toLowerCase();
  3764. if (isFinite(Number(string))) {
  3765. if ('px'.search(unitRegExp) >= 0) {
  3766. return getOrCreateUnitValue(Number(string), 'px');
  3767. } else if ('deg'.search(unitRegExp) >= 0) {
  3768. return getOrCreateUnitValue(Number(string), 'deg');
  3769. }
  3770. }
  3771. var matchedUnits = [];
  3772. string = string.replace(unitRegExp, function (match) {
  3773. matchedUnits.push(match);
  3774. return 'U' + match;
  3775. });
  3776. var taggedUnitRegExp = 'U(' + unitRegExp.source + ')';
  3777. return matchedUnits.map(function (unit) {
  3778. return getOrCreateUnitValue(Number(string.replace(new RegExp('U' + unit, 'g'), '').replace(new RegExp(taggedUnitRegExp, 'g'), '*0')), unit);
  3779. })[0];
  3780. }
  3781. /**
  3782. * <length>
  3783. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length
  3784. * length with only absolute unit, eg. 1px
  3785. */
  3786. var parseLength = memoize(function (css) {
  3787. return parseDimension(new RegExp('px', 'g'), css);
  3788. });
  3789. /**
  3790. * <percentage>
  3791. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage
  3792. */
  3793. var parserPercentage = memoize(function (css) {
  3794. return parseDimension(new RegExp('%', 'g'), css);
  3795. });
  3796. /**
  3797. * length with absolute or relative unit,
  3798. * eg. 1px, 0.7em, 50%, calc(100% - 200px);
  3799. *
  3800. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length-percentage
  3801. */
  3802. // export const parseLengthOrPercentage = memoize((css: string): CSSUnitValue => {
  3803. // if (isNumber(css) || isFinite(Number(css))) {
  3804. // return getOrCreateUnitValue(Number(css), 'px');
  3805. // }
  3806. // return parseDimension(new RegExp('px|%|em|rem', 'g'), css) as CSSUnitValue;
  3807. // });
  3808. var parseLengthOrPercentage = function parseLengthOrPercentage(css) {
  3809. if (util.isNumber(css) || isFinite(Number(css))) {
  3810. // Number(css) is NaN
  3811. return getOrCreateUnitValue(Number(css) || 0, 'px');
  3812. // return Number(css);
  3813. }
  3814. return parseDimension(new RegExp('px|%|em|rem', 'g'), css);
  3815. };
  3816. var parseAngle = memoize(function (css) {
  3817. return parseDimension(new RegExp('deg|rad|grad|turn', 'g'), css);
  3818. });
  3819. /**
  3820. * merge CSSUnitValue
  3821. *
  3822. * @example
  3823. * 10px + 20px = 30px
  3824. * 10deg + 10rad
  3825. * 10% + 20% = 30%
  3826. */
  3827. function mergeDimensions(left, right, target, nonNegative, index) {
  3828. if (index === void 0) {
  3829. index = 0;
  3830. }
  3831. var unit = '';
  3832. var leftValue = left.value || 0;
  3833. var rightValue = right.value || 0;
  3834. var canonicalUnit = toCanonicalUnit(left.unit);
  3835. var leftCanonicalUnitValue = left.convertTo(canonicalUnit);
  3836. var rightCanonicalUnitValue = right.convertTo(canonicalUnit);
  3837. if (leftCanonicalUnitValue && rightCanonicalUnitValue) {
  3838. leftValue = leftCanonicalUnitValue.value;
  3839. rightValue = rightCanonicalUnitValue.value;
  3840. unit = unitTypeToString(left.unit);
  3841. } else {
  3842. // format '%' to 'px'
  3843. if (CSSUnitValue.isLength(left.unit) || CSSUnitValue.isLength(right.unit)) {
  3844. leftValue = convertPercentUnit(left, index, target);
  3845. rightValue = convertPercentUnit(right, index, target);
  3846. unit = 'px';
  3847. }
  3848. }
  3849. // // format 'rad' 'turn' to 'deg'
  3850. // if (CSSUnitValue.isAngle(left.unit) || CSSUnitValue.isAngle(right.unit)) {
  3851. // leftValue = convertAngleUnit(left);
  3852. // rightValue = convertAngleUnit(right);
  3853. // unit = 'deg';
  3854. // }
  3855. return [leftValue, rightValue, function (value) {
  3856. if (nonNegative) {
  3857. value = Math.max(value, 0);
  3858. }
  3859. return value + unit;
  3860. }];
  3861. }
  3862. function convertAngleUnit(value) {
  3863. var deg = 0;
  3864. if (value.unit === exports.UnitType.kDegrees) {
  3865. deg = value.value;
  3866. } else if (value.unit === exports.UnitType.kRadians) {
  3867. deg = rad2deg(Number(value.value));
  3868. } else if (value.unit === exports.UnitType.kTurns) {
  3869. deg = turn2deg(Number(value.value));
  3870. }
  3871. return deg;
  3872. }
  3873. function parseDimensionArrayFormat(string, size) {
  3874. var parsed;
  3875. if (Array.isArray(string)) {
  3876. // [1, '2px', 3]
  3877. parsed = string.map(function (segment) {
  3878. return Number(segment);
  3879. });
  3880. } else if (util.isString(string)) {
  3881. parsed = string.split(' ').map(function (segment) {
  3882. return Number(segment);
  3883. });
  3884. } else if (util.isNumber(string)) {
  3885. parsed = [string];
  3886. }
  3887. if (size === 2) {
  3888. if (parsed.length === 1) {
  3889. return [parsed[0], parsed[0]];
  3890. } else {
  3891. return [parsed[0], parsed[1]];
  3892. }
  3893. } else {
  3894. if (parsed.length === 1) {
  3895. return [parsed[0], parsed[0], parsed[0], parsed[0]];
  3896. } else if (parsed.length === 2) {
  3897. return [parsed[0], parsed[1], parsed[0], parsed[1]];
  3898. } else if (parsed.length === 3) {
  3899. return [parsed[0], parsed[1], parsed[2], parsed[1]];
  3900. } else {
  3901. return [parsed[0], parsed[1], parsed[2], parsed[3]];
  3902. }
  3903. }
  3904. }
  3905. function parseDimensionArray(string) {
  3906. if (util.isString(string)) {
  3907. // "1px 2px 3px"
  3908. return string.split(' ').map(function (segment) {
  3909. return parseLengthOrPercentage(segment);
  3910. });
  3911. } else {
  3912. // [1, '2px', 3]
  3913. return string.map(function (segment) {
  3914. return parseLengthOrPercentage(segment.toString());
  3915. });
  3916. }
  3917. }
  3918. // export function mergeDimensionList(
  3919. // left: CSSUnitValue[],
  3920. // right: CSSUnitValue[],
  3921. // target: IElement | null,
  3922. // ): [number[], number[], (list: number[]) => string] | undefined {
  3923. // if (left.length !== right.length) {
  3924. // return;
  3925. // }
  3926. // const unit = left[0].unit;
  3927. // return [
  3928. // left.map((l) => l.value),
  3929. // right.map((l) => l.value),
  3930. // (values: number[]) => {
  3931. // return values.map((n) => new CSSUnitValue(n, unit)).join(' ');
  3932. // },
  3933. // ];
  3934. // }
  3935. function convertPercentUnit(valueWithUnit, vec3Index, target) {
  3936. if (valueWithUnit.value === 0) {
  3937. return 0;
  3938. }
  3939. if (valueWithUnit.unit === exports.UnitType.kPixels) {
  3940. return Number(valueWithUnit.value);
  3941. } else if (valueWithUnit.unit === exports.UnitType.kPercentage && target) {
  3942. var bounds = target.nodeName === exports.Shape.GROUP ? target.getLocalBounds() :
  3943. // : target.getGeometryBounds();
  3944. target.geometry.contentBounds;
  3945. return valueWithUnit.value / 100 * bounds.halfExtents[vec3Index] * 2;
  3946. }
  3947. return 0;
  3948. }
  3949. var parseParam = function parseParam(css) {
  3950. return parseDimension(/deg|rad|grad|turn|px|%/g, css);
  3951. };
  3952. var supportedFilters = ['blur', 'brightness', 'drop-shadow', 'contrast', 'grayscale', 'sepia', 'saturate', 'hue-rotate', 'invert'];
  3953. function parseFilter(filterStr) {
  3954. if (filterStr === void 0) {
  3955. filterStr = '';
  3956. }
  3957. filterStr = filterStr.toLowerCase().trim();
  3958. if (filterStr === 'none') {
  3959. return [];
  3960. }
  3961. var filterRegExp = /\s*([\w-]+)\(([^)]*)\)/g;
  3962. var result = [];
  3963. var match;
  3964. var prevLastIndex = 0;
  3965. while (match = filterRegExp.exec(filterStr)) {
  3966. if (match.index !== prevLastIndex) {
  3967. return [];
  3968. }
  3969. prevLastIndex = match.index + match[0].length;
  3970. if (supportedFilters.indexOf(match[1]) > -1) {
  3971. result.push({
  3972. name: match[1],
  3973. params: match[2].split(' ').map(function (p) {
  3974. return parseParam(p) || parseColor(p);
  3975. })
  3976. });
  3977. }
  3978. if (filterRegExp.lastIndex === filterStr.length) {
  3979. return result;
  3980. }
  3981. }
  3982. return [];
  3983. }
  3984. function numberToString(x) {
  3985. // scale(0.00000001) -> scale(0)
  3986. // return x.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
  3987. return x.toString();
  3988. }
  3989. /**
  3990. * parse string or number to CSSUnitValue(numeric)
  3991. *
  3992. * eg.
  3993. * * 0 -> CSSUnitValue(0)
  3994. * * '2' -> CSSUnitValue(2)
  3995. */
  3996. var parseNumber = memoize(function (string) {
  3997. if (typeof string === 'number') {
  3998. return getOrCreateUnitValue(string);
  3999. }
  4000. if (/^\s*[-+]?(\d*\.)?\d+\s*$/.test(string)) {
  4001. return getOrCreateUnitValue(Number(string));
  4002. } else {
  4003. return getOrCreateUnitValue(0);
  4004. }
  4005. });
  4006. /**
  4007. * separate string to array
  4008. * eg.
  4009. * * [0.5, 0.5] -> [CSSUnitValue, CSSUnitValue]
  4010. */
  4011. var parseNumberList = memoize(function (string) {
  4012. if (util.isString(string)) {
  4013. return string.split(' ').map(parseNumber);
  4014. } else {
  4015. return string.map(parseNumber);
  4016. }
  4017. });
  4018. function mergeNumbers(left, right) {
  4019. return [left, right, numberToString];
  4020. }
  4021. function clampedMergeNumbers(min, max) {
  4022. return function (left, right) {
  4023. return [left, right, function (x) {
  4024. return numberToString(util.clamp(x, min, max));
  4025. }];
  4026. };
  4027. }
  4028. function mergeNumberLists(left, right) {
  4029. if (left.length !== right.length) {
  4030. return;
  4031. }
  4032. return [left, right, function (numberList) {
  4033. return numberList;
  4034. }];
  4035. }
  4036. var internalParsePath = function internalParsePath(path) {
  4037. // empty path
  4038. if (path === '' || Array.isArray(path) && path.length === 0) {
  4039. return {
  4040. absolutePath: [],
  4041. hasArc: false,
  4042. segments: [],
  4043. polygons: [],
  4044. polylines: [],
  4045. curve: null,
  4046. totalLength: 0,
  4047. rect: {
  4048. x: 0,
  4049. y: 0,
  4050. width: 0,
  4051. height: 0
  4052. }
  4053. };
  4054. }
  4055. var absolutePath;
  4056. try {
  4057. absolutePath = util.normalizePath(path);
  4058. } catch (e) {
  4059. absolutePath = util.normalizePath('');
  4060. console.error("[g]: Invalid SVG Path definition: " + path);
  4061. }
  4062. var hasArc = hasArcOrBezier(absolutePath);
  4063. var _extractPolygons = extractPolygons(absolutePath),
  4064. polygons = _extractPolygons.polygons,
  4065. polylines = _extractPolygons.polylines;
  4066. // for later use
  4067. var segments = path2Segments(absolutePath);
  4068. // Only calculate bbox here since we don't need length now.
  4069. var _getPathBBox = getPathBBox(segments, 0),
  4070. x = _getPathBBox.x,
  4071. y = _getPathBBox.y,
  4072. width = _getPathBBox.width,
  4073. height = _getPathBBox.height;
  4074. return {
  4075. absolutePath: absolutePath,
  4076. hasArc: hasArc,
  4077. segments: segments,
  4078. polygons: polygons,
  4079. polylines: polylines,
  4080. // curve,
  4081. // Delay the calculation of length.
  4082. totalLength: 0,
  4083. rect: {
  4084. x: Number.isFinite(x) ? x : 0,
  4085. y: Number.isFinite(y) ? y : 0,
  4086. width: Number.isFinite(width) ? width : 0,
  4087. height: Number.isFinite(height) ? height : 0
  4088. }
  4089. };
  4090. };
  4091. var memoizedParsePath = memoize(internalParsePath);
  4092. function parsePath(path, object) {
  4093. var result = util.isString(path) ? memoizedParsePath(path) : internalParsePath(path);
  4094. if (object) {
  4095. object.parsedStyle.defX = result.rect.x;
  4096. object.parsedStyle.defY = result.rect.y;
  4097. }
  4098. return result;
  4099. }
  4100. function mergePaths(left, right, object) {
  4101. var curve1 = left.curve;
  4102. var curve2 = right.curve;
  4103. if (!curve1 || curve1.length === 0) {
  4104. // convert to curves to do morphing & picking later
  4105. // @see http://thednp.github.io/kute.js/svgCubicMorph.html
  4106. curve1 = util.path2Curve(left.absolutePath, false);
  4107. left.curve = curve1;
  4108. }
  4109. if (!curve2 || curve2.length === 0) {
  4110. curve2 = util.path2Curve(right.absolutePath, false);
  4111. right.curve = curve2;
  4112. }
  4113. var curves = [curve1, curve2];
  4114. if (curve1.length !== curve2.length) {
  4115. curves = util.equalizeSegments(curve1, curve2);
  4116. }
  4117. var curve0 = util.getDrawDirection(curves[0]) !== util.getDrawDirection(curves[1]) ? util.reverseCurve(curves[0]) : util.clonePath(curves[0]);
  4118. return [curve0, util.getRotatedCurve(curves[1], curve0), function (pathArray) {
  4119. // need converting to path string?
  4120. return pathArray;
  4121. }];
  4122. }
  4123. /**
  4124. * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/points
  4125. *
  4126. * @example
  4127. * points="100,10 250,150 200,110"
  4128. */
  4129. function parsePoints(pointsOrStr, object) {
  4130. var points;
  4131. if (util.isString(pointsOrStr)) {
  4132. points = pointsOrStr.split(' ').map(function (pointStr) {
  4133. var _pointStr$split = pointStr.split(','),
  4134. x = _pointStr$split[0],
  4135. y = _pointStr$split[1];
  4136. return [Number(x), Number(y)];
  4137. });
  4138. } else {
  4139. points = pointsOrStr;
  4140. }
  4141. var segments = [];
  4142. var tempLength = 0;
  4143. var segmentT;
  4144. var segmentL;
  4145. var totalLength = gMath.Polyline.length(points);
  4146. points.forEach(function (p, i) {
  4147. if (points[i + 1]) {
  4148. segmentT = [0, 0];
  4149. segmentT[0] = tempLength / totalLength;
  4150. segmentL = gMath.Line.length(p[0], p[1], points[i + 1][0], points[i + 1][1]);
  4151. tempLength += segmentL;
  4152. segmentT[1] = tempLength / totalLength;
  4153. segments.push(segmentT);
  4154. }
  4155. });
  4156. var minX = Math.min.apply(Math, points.map(function (point) {
  4157. return point[0];
  4158. }));
  4159. var minY = Math.min.apply(Math, points.map(function (point) {
  4160. return point[1];
  4161. }));
  4162. if (object) {
  4163. object.parsedStyle.defX = minX;
  4164. object.parsedStyle.defY = minY;
  4165. }
  4166. return {
  4167. points: points,
  4168. totalLength: totalLength,
  4169. segments: segments
  4170. };
  4171. }
  4172. function mergePoints(left, right) {
  4173. return [left.points, right.points, function (points) {
  4174. return points;
  4175. }];
  4176. }
  4177. var _ = null;
  4178. function cast(pattern) {
  4179. return function (contents) {
  4180. var i = 0;
  4181. return pattern.map(function (x) {
  4182. return x === _ ? contents[i++] : x;
  4183. });
  4184. };
  4185. }
  4186. function id(x) {
  4187. return x;
  4188. }
  4189. // type: [argTypes, convertTo3D, convertTo2D]
  4190. // In the argument types string, lowercase characters represent optional arguments
  4191. var transformFunctions = {
  4192. // @ts-ignore
  4193. matrix: ['NNNNNN', [_, _, 0, 0, _, _, 0, 0, 0, 0, 1, 0, _, _, 0, 1], id],
  4194. matrix3d: ['NNNNNNNNNNNNNNNN', id],
  4195. rotate: ['A'],
  4196. rotatex: ['A'],
  4197. rotatey: ['A'],
  4198. rotatez: ['A'],
  4199. rotate3d: ['NNNA'],
  4200. perspective: ['L'],
  4201. scale: ['Nn', cast([_, _, new CSSUnitValue(1)]), id],
  4202. scalex: ['N', cast([_, new CSSUnitValue(1), new CSSUnitValue(1)]), cast([_, new CSSUnitValue(1)])],
  4203. scaley: ['N', cast([new CSSUnitValue(1), _, new CSSUnitValue(1)]), cast([new CSSUnitValue(1), _])],
  4204. scalez: ['N', cast([new CSSUnitValue(1), new CSSUnitValue(1), _])],
  4205. scale3d: ['NNN', id],
  4206. skew: ['Aa', null, id],
  4207. skewx: ['A', null, cast([_, Odeg])],
  4208. skewy: ['A', null, cast([Odeg, _])],
  4209. translate: ['Tt', cast([_, _, Opx]), id],
  4210. translatex: ['T', cast([_, Opx, Opx]), cast([_, Opx])],
  4211. translatey: ['T', cast([Opx, _, Opx]), cast([Opx, _])],
  4212. translatez: ['L', cast([Opx, Opx, _])],
  4213. translate3d: ['TTL', id]
  4214. };
  4215. /**
  4216. * none
  4217. * scale(1) scale(1, 2)
  4218. * scaleX(1)
  4219. */
  4220. function parseTransform(string) {
  4221. string = (string || 'none').toLowerCase().trim();
  4222. if (string === 'none') {
  4223. return [];
  4224. }
  4225. var transformRegExp = /\s*(\w+)\(([^)]*)\)/g;
  4226. var result = [];
  4227. var match;
  4228. var prevLastIndex = 0;
  4229. while (match = transformRegExp.exec(string)) {
  4230. if (match.index !== prevLastIndex) {
  4231. return [];
  4232. }
  4233. prevLastIndex = match.index + match[0].length;
  4234. var functionName = match[1]; // scale
  4235. var functionData = transformFunctions[functionName]; // scale(1, 2)
  4236. if (!functionData) {
  4237. // invalid, eg. scale()
  4238. return [];
  4239. }
  4240. var args = match[2].split(','); // 1,2
  4241. var argTypes = functionData[0]; // Nn
  4242. if (argTypes.length < args.length) {
  4243. // scale(N, n)
  4244. return [];
  4245. }
  4246. var parsedArgs = [];
  4247. for (var i = 0; i < argTypes.length; i++) {
  4248. var arg = args[i];
  4249. var type = argTypes[i];
  4250. var parsedArg = void 0;
  4251. if (!arg) {
  4252. // @ts-ignore
  4253. parsedArg = {
  4254. a: Odeg,
  4255. n: parsedArgs[0],
  4256. t: Opx
  4257. }[type];
  4258. } else {
  4259. // @ts-ignore
  4260. parsedArg = {
  4261. A: function A(s) {
  4262. return s.trim() === '0' ? Odeg : parseAngle(s);
  4263. },
  4264. N: parseNumber,
  4265. T: parseLengthOrPercentage,
  4266. L: parseLength
  4267. }[type.toUpperCase()](arg);
  4268. }
  4269. if (parsedArg === undefined) {
  4270. return [];
  4271. }
  4272. parsedArgs.push(parsedArg);
  4273. }
  4274. result.push({
  4275. t: functionName,
  4276. d: parsedArgs
  4277. }); // { t: scale, d: [1, 2] }
  4278. if (transformRegExp.lastIndex === string.length) {
  4279. return result;
  4280. }
  4281. }
  4282. return [];
  4283. }
  4284. function convertItemToMatrix(item) {
  4285. var x;
  4286. var y;
  4287. var z;
  4288. var angle;
  4289. switch (item.t) {
  4290. case 'rotatex':
  4291. angle = deg2rad(convertAngleUnit(item.d[0]));
  4292. return [1, 0, 0, 0, 0, Math.cos(angle), Math.sin(angle), 0, 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0, 0, 1];
  4293. case 'rotatey':
  4294. angle = deg2rad(convertAngleUnit(item.d[0]));
  4295. return [Math.cos(angle), 0, -Math.sin(angle), 0, 0, 1, 0, 0, Math.sin(angle), 0, Math.cos(angle), 0, 0, 0, 0, 1];
  4296. case 'rotate':
  4297. case 'rotatez':
  4298. angle = deg2rad(convertAngleUnit(item.d[0]));
  4299. return [Math.cos(angle), Math.sin(angle), 0, 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4300. case 'rotate3d':
  4301. x = item.d[0].value;
  4302. y = item.d[1].value;
  4303. z = item.d[2].value;
  4304. angle = deg2rad(convertAngleUnit(item.d[3]));
  4305. var sqrLength = x * x + y * y + z * z;
  4306. if (sqrLength === 0) {
  4307. x = 1;
  4308. y = 0;
  4309. z = 0;
  4310. } else if (sqrLength !== 1) {
  4311. var length = Math.sqrt(sqrLength);
  4312. x /= length;
  4313. y /= length;
  4314. z /= length;
  4315. }
  4316. var s = Math.sin(angle / 2);
  4317. var sc = s * Math.cos(angle / 2);
  4318. var sq = s * s;
  4319. return [1 - 2 * (y * y + z * z) * sq, 2 * (x * y * sq + z * sc), 2 * (x * z * sq - y * sc), 0, 2 * (x * y * sq - z * sc), 1 - 2 * (x * x + z * z) * sq, 2 * (y * z * sq + x * sc), 0, 2 * (x * z * sq + y * sc), 2 * (y * z * sq - x * sc), 1 - 2 * (x * x + y * y) * sq, 0, 0, 0, 0, 1];
  4320. case 'scale':
  4321. return [item.d[0].value, 0, 0, 0, 0, item.d[1].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4322. case 'scalex':
  4323. return [item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4324. case 'scaley':
  4325. return [1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4326. case 'scalez':
  4327. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1];
  4328. case 'scale3d':
  4329. return [item.d[0].value, 0, 0, 0, 0, item.d[1].value, 0, 0, 0, 0, item.d[2].value, 0, 0, 0, 0, 1];
  4330. case 'skew':
  4331. var xAngle = deg2rad(convertAngleUnit(item.d[0]));
  4332. var yAngle = deg2rad(convertAngleUnit(item.d[1]));
  4333. return [1, Math.tan(yAngle), 0, 0, Math.tan(xAngle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4334. case 'skewx':
  4335. angle = deg2rad(convertAngleUnit(item.d[0]));
  4336. return [1, 0, 0, 0, Math.tan(angle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4337. case 'skewy':
  4338. angle = deg2rad(convertAngleUnit(item.d[0]));
  4339. return [1, Math.tan(angle), 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4340. case 'translate':
  4341. // TODO: pass target
  4342. x = convertPercentUnit(item.d[0], 0, null) || 0;
  4343. y = convertPercentUnit(item.d[1], 0, null) || 0;
  4344. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1];
  4345. case 'translatex':
  4346. x = convertPercentUnit(item.d[0], 0, null) || 0;
  4347. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1];
  4348. case 'translatey':
  4349. y = convertPercentUnit(item.d[0], 0, null) || 0;
  4350. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, y, 0, 1];
  4351. case 'translatez':
  4352. z = convertPercentUnit(item.d[0], 0, null) || 0;
  4353. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, z, 1];
  4354. case 'translate3d':
  4355. x = convertPercentUnit(item.d[0], 0, null) || 0;
  4356. y = convertPercentUnit(item.d[1], 0, null) || 0;
  4357. z = convertPercentUnit(item.d[2], 0, null) || 0;
  4358. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
  4359. case 'perspective':
  4360. var t = convertPercentUnit(item.d[0], 0, null) || 0;
  4361. var p = t ? -1 / t : 0;
  4362. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, p, 0, 0, 0, 1];
  4363. case 'matrix':
  4364. return [item.d[0].value, item.d[1].value, 0, 0, item.d[2].value, item.d[3].value, 0, 0, 0, 0, 1, 0, item.d[4].value, item.d[5].value, 0, 1];
  4365. case 'matrix3d':
  4366. return item.d.map(function (d) {
  4367. return d.value;
  4368. });
  4369. }
  4370. }
  4371. function multiplyMatrices(a, b) {
  4372. return [a[0] * b[0] + a[4] * b[1] + a[8] * b[2] + a[12] * b[3], a[1] * b[0] + a[5] * b[1] + a[9] * b[2] + a[13] * b[3], a[2] * b[0] + a[6] * b[1] + a[10] * b[2] + a[14] * b[3], a[3] * b[0] + a[7] * b[1] + a[11] * b[2] + a[15] * b[3], a[0] * b[4] + a[4] * b[5] + a[8] * b[6] + a[12] * b[7], a[1] * b[4] + a[5] * b[5] + a[9] * b[6] + a[13] * b[7], a[2] * b[4] + a[6] * b[5] + a[10] * b[6] + a[14] * b[7], a[3] * b[4] + a[7] * b[5] + a[11] * b[6] + a[15] * b[7], a[0] * b[8] + a[4] * b[9] + a[8] * b[10] + a[12] * b[11], a[1] * b[8] + a[5] * b[9] + a[9] * b[10] + a[13] * b[11], a[2] * b[8] + a[6] * b[9] + a[10] * b[10] + a[14] * b[11], a[3] * b[8] + a[7] * b[9] + a[11] * b[10] + a[15] * b[11], a[0] * b[12] + a[4] * b[13] + a[8] * b[14] + a[12] * b[15], a[1] * b[12] + a[5] * b[13] + a[9] * b[14] + a[13] * b[15], a[2] * b[12] + a[6] * b[13] + a[10] * b[14] + a[14] * b[15], a[3] * b[12] + a[7] * b[13] + a[11] * b[14] + a[15] * b[15]];
  4373. }
  4374. function convertToMatrix(transformList) {
  4375. if (transformList.length === 0) {
  4376. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4377. }
  4378. return transformList.map(convertItemToMatrix).reduce(multiplyMatrices);
  4379. }
  4380. function makeMatrixDecomposition(transformList) {
  4381. var translate = [0, 0, 0];
  4382. var scale = [1, 1, 1];
  4383. var skew = [0, 0, 0];
  4384. var perspective = [0, 0, 0, 1];
  4385. var quaternion = [0, 0, 0, 1];
  4386. // @ts-ignore
  4387. decomposeMat4(convertToMatrix(transformList), translate, scale, skew, perspective, quaternion);
  4388. return [[translate, scale, skew, quaternion, perspective]];
  4389. }
  4390. var composeMatrix = function () {
  4391. function multiply(a, b) {
  4392. var result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
  4393. for (var i = 0; i < 4; i++) {
  4394. for (var j = 0; j < 4; j++) {
  4395. for (var k = 0; k < 4; k++) {
  4396. result[i][j] += b[i][k] * a[k][j];
  4397. }
  4398. }
  4399. }
  4400. return result;
  4401. }
  4402. function is2D(m) {
  4403. return m[0][2] == 0 && m[0][3] == 0 && m[1][2] == 0 && m[1][3] == 0 && m[2][0] == 0 && m[2][1] == 0 && m[2][2] == 1 && m[2][3] == 0 && m[3][2] == 0 && m[3][3] == 1;
  4404. }
  4405. function composeMatrix(translate, scale, skew, quat, perspective) {
  4406. var matrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
  4407. for (var i = 0; i < 4; i++) {
  4408. matrix[i][3] = perspective[i];
  4409. }
  4410. for (var _i = 0; _i < 3; _i++) {
  4411. for (var j = 0; j < 3; j++) {
  4412. matrix[3][_i] += translate[j] * matrix[j][_i];
  4413. }
  4414. }
  4415. var x = quat[0],
  4416. y = quat[1],
  4417. z = quat[2],
  4418. w = quat[3];
  4419. var rotMatrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
  4420. rotMatrix[0][0] = 1 - 2 * (y * y + z * z);
  4421. rotMatrix[0][1] = 2 * (x * y - z * w);
  4422. rotMatrix[0][2] = 2 * (x * z + y * w);
  4423. rotMatrix[1][0] = 2 * (x * y + z * w);
  4424. rotMatrix[1][1] = 1 - 2 * (x * x + z * z);
  4425. rotMatrix[1][2] = 2 * (y * z - x * w);
  4426. rotMatrix[2][0] = 2 * (x * z - y * w);
  4427. rotMatrix[2][1] = 2 * (y * z + x * w);
  4428. rotMatrix[2][2] = 1 - 2 * (x * x + y * y);
  4429. matrix = multiply(matrix, rotMatrix);
  4430. var temp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
  4431. if (skew[2]) {
  4432. temp[2][1] = skew[2];
  4433. matrix = multiply(matrix, temp);
  4434. }
  4435. if (skew[1]) {
  4436. temp[2][1] = 0;
  4437. temp[2][0] = skew[0];
  4438. matrix = multiply(matrix, temp);
  4439. }
  4440. if (skew[0]) {
  4441. temp[2][0] = 0;
  4442. temp[1][0] = skew[0];
  4443. matrix = multiply(matrix, temp);
  4444. }
  4445. for (var _i2 = 0; _i2 < 3; _i2++) {
  4446. for (var _j = 0; _j < 3; _j++) {
  4447. matrix[_i2][_j] *= scale[_i2];
  4448. }
  4449. }
  4450. if (is2D(matrix)) {
  4451. return [matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1], matrix[3][0], matrix[3][1]];
  4452. }
  4453. return matrix[0].concat(matrix[1], matrix[2], matrix[3]);
  4454. }
  4455. return composeMatrix;
  4456. }();
  4457. function numberToLongString(x) {
  4458. return x.toFixed(6).replace('.000000', '');
  4459. }
  4460. function mergeMatrices(left, right) {
  4461. var leftArgs;
  4462. var rightArgs;
  4463. // @ts-ignore
  4464. if (left.decompositionPair !== right) {
  4465. // @ts-ignore
  4466. left.decompositionPair = right;
  4467. // @ts-ignore
  4468. leftArgs = makeMatrixDecomposition(left);
  4469. }
  4470. // @ts-ignore
  4471. if (right.decompositionPair !== left) {
  4472. // @ts-ignore
  4473. right.decompositionPair = left;
  4474. // @ts-ignore
  4475. rightArgs = makeMatrixDecomposition(right);
  4476. }
  4477. if (leftArgs[0] === null || rightArgs[0] === null) return [
  4478. // @ts-ignore
  4479. [false],
  4480. // @ts-ignore
  4481. [true],
  4482. // @ts-ignore
  4483. function (x) {
  4484. return x ? right[0].d : left[0].d;
  4485. }];
  4486. leftArgs[0].push(0);
  4487. rightArgs[0].push(1);
  4488. return [leftArgs, rightArgs,
  4489. // @ts-ignore
  4490. function (list) {
  4491. // @ts-ignore
  4492. var q = quat(leftArgs[0][3], rightArgs[0][3], list[5]);
  4493. var mat = composeMatrix(list[0], list[1], list[2], q, list[4]);
  4494. var stringifiedArgs = mat.map(numberToLongString).join(',');
  4495. return stringifiedArgs;
  4496. }];
  4497. }
  4498. function dot(v1, v2) {
  4499. var result = 0;
  4500. for (var i = 0; i < v1.length; i++) {
  4501. result += v1[i] * v2[i];
  4502. }
  4503. return result;
  4504. }
  4505. function quat(fromQ, toQ, f) {
  4506. var product = dot(fromQ, toQ);
  4507. product = util.clamp(product, -1.0, 1.0);
  4508. var quat = [];
  4509. if (product === 1.0) {
  4510. quat = fromQ;
  4511. } else {
  4512. var theta = Math.acos(product);
  4513. var w = Math.sin(f * theta) * 1 / Math.sqrt(1 - product * product);
  4514. for (var i = 0; i < 4; i++) {
  4515. quat.push(fromQ[i] * (Math.cos(f * theta) - product * w) + toQ[i] * w);
  4516. }
  4517. }
  4518. return quat;
  4519. }
  4520. // scalex/y/z -> scale
  4521. function typeTo2D(type) {
  4522. return type.replace(/[xy]/, '');
  4523. }
  4524. // scalex/y/z -> scale3d
  4525. function typeTo3D(type) {
  4526. return type.replace(/(x|y|z|3d)?$/, '3d');
  4527. }
  4528. var isMatrixOrPerspective = function isMatrixOrPerspective(lt, rt) {
  4529. return lt === 'perspective' && rt === 'perspective' || (lt === 'matrix' || lt === 'matrix3d') && (rt === 'matrix' || rt === 'matrix3d');
  4530. };
  4531. function mergeTransforms(left, right, target) {
  4532. var flipResults = false;
  4533. // padding empty transform, eg. merge 'scale(10)' with 'none' -> scale(1)
  4534. if (!left.length || !right.length) {
  4535. if (!left.length) {
  4536. flipResults = true;
  4537. left = right;
  4538. right = [];
  4539. }
  4540. var _loop = function _loop() {
  4541. var _left$i = left[i],
  4542. type = _left$i.t,
  4543. args = _left$i.d;
  4544. // none -> scale(1)/translateX(0)
  4545. var defaultValue = type.substring(0, 5) === 'scale' ? 1 : 0;
  4546. right.push({
  4547. t: type,
  4548. d: args.map(function (arg) {
  4549. if (typeof arg === 'number') {
  4550. return getOrCreateUnitValue(defaultValue);
  4551. }
  4552. return getOrCreateUnitValue(defaultValue, arg.unit);
  4553. // {
  4554. // unit: arg.unit,
  4555. // value: defaultValue,
  4556. // };
  4557. })
  4558. });
  4559. };
  4560. for (var i = 0; i < left.length; i++) {
  4561. _loop();
  4562. }
  4563. }
  4564. var leftResult = [];
  4565. var rightResult = [];
  4566. var types = [];
  4567. // merge matrix() with matrix3d()
  4568. if (left.length !== right.length) {
  4569. var merged = mergeMatrices(left, right);
  4570. // @ts-ignore
  4571. leftResult = [merged[0]];
  4572. // @ts-ignore
  4573. rightResult = [merged[1]];
  4574. types = [['matrix', [merged[2]]]];
  4575. } else {
  4576. for (var _i3 = 0; _i3 < left.length; _i3++) {
  4577. var leftType = left[_i3].t;
  4578. var rightType = right[_i3].t;
  4579. var leftArgs = left[_i3].d;
  4580. var rightArgs = right[_i3].d;
  4581. var leftFunctionData = transformFunctions[leftType];
  4582. var rightFunctionData = transformFunctions[rightType];
  4583. var type = void 0;
  4584. if (isMatrixOrPerspective(leftType, rightType)) {
  4585. var _merged = mergeMatrices([left[_i3]], [right[_i3]]);
  4586. // @ts-ignore
  4587. leftResult.push(_merged[0]);
  4588. // @ts-ignore
  4589. rightResult.push(_merged[1]);
  4590. types.push(['matrix', [_merged[2]]]);
  4591. continue;
  4592. } else if (leftType === rightType) {
  4593. type = leftType;
  4594. } else if (leftFunctionData[2] && rightFunctionData[2] && typeTo2D(leftType) === typeTo2D(rightType)) {
  4595. type = typeTo2D(leftType);
  4596. // @ts-ignore
  4597. leftArgs = leftFunctionData[2](leftArgs);
  4598. // @ts-ignore
  4599. rightArgs = rightFunctionData[2](rightArgs);
  4600. } else if (leftFunctionData[1] && rightFunctionData[1] && typeTo3D(leftType) === typeTo3D(rightType)) {
  4601. type = typeTo3D(leftType);
  4602. // @ts-ignore
  4603. leftArgs = leftFunctionData[1](leftArgs);
  4604. // @ts-ignore
  4605. rightArgs = rightFunctionData[1](rightArgs);
  4606. } else {
  4607. var _merged2 = mergeMatrices(left, right);
  4608. // @ts-ignore
  4609. leftResult = [_merged2[0]];
  4610. // @ts-ignore
  4611. rightResult = [_merged2[1]];
  4612. types = [['matrix', [_merged2[2]]]];
  4613. break;
  4614. }
  4615. var leftArgsCopy = [];
  4616. var rightArgsCopy = [];
  4617. var stringConversions = [];
  4618. for (var j = 0; j < leftArgs.length; j++) {
  4619. // const merge = leftArgs[j].unit === UnitType.kNumber ? mergeDimensions : mergeDimensions;
  4620. var _merged3 = mergeDimensions(leftArgs[j], rightArgs[j], target, false, j);
  4621. leftArgsCopy[j] = _merged3[0];
  4622. rightArgsCopy[j] = _merged3[1];
  4623. stringConversions.push(_merged3[2]);
  4624. }
  4625. leftResult.push(leftArgsCopy);
  4626. rightResult.push(rightArgsCopy);
  4627. types.push([type, stringConversions]);
  4628. }
  4629. }
  4630. if (flipResults) {
  4631. var tmp = leftResult;
  4632. leftResult = rightResult;
  4633. rightResult = tmp;
  4634. }
  4635. return [leftResult, rightResult, function (list) {
  4636. return list.map(function (args, i) {
  4637. var stringifiedArgs = args.map(function (arg, j) {
  4638. return types[i][1][j](arg);
  4639. }).join(',');
  4640. if (types[i][0] === 'matrix' && stringifiedArgs.split(',').length === 16) {
  4641. types[i][0] = 'matrix3d';
  4642. }
  4643. if (types[i][0] === 'matrix3d' && stringifiedArgs.split(',').length === 6) {
  4644. types[i][0] = 'matrix';
  4645. }
  4646. return types[i][0] + '(' + stringifiedArgs + ')';
  4647. }).join(' ');
  4648. }];
  4649. }
  4650. /**
  4651. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
  4652. * eg. 'center' 'top left' '50px 50px'
  4653. */
  4654. var parseTransformOrigin = memoize(function (value) {
  4655. if (util.isString(value)) {
  4656. if (value === 'text-anchor') {
  4657. return [getOrCreateUnitValue(0, 'px'), getOrCreateUnitValue(0, 'px')];
  4658. }
  4659. var values = value.split(' ');
  4660. if (values.length === 1) {
  4661. if (values[0] === 'top' || values[0] === 'bottom') {
  4662. // 'top' -> 'center top'
  4663. values[1] = values[0];
  4664. values[0] = 'center';
  4665. } else {
  4666. // '50px' -> '50px center'
  4667. values[1] = 'center';
  4668. }
  4669. }
  4670. if (values.length !== 2) {
  4671. return null;
  4672. }
  4673. // eg. center bottom
  4674. return [parseLengthOrPercentage(convertKeyword2Percent(values[0])), parseLengthOrPercentage(convertKeyword2Percent(values[1]))];
  4675. } else {
  4676. return [getOrCreateUnitValue(value[0] || 0, 'px'), getOrCreateUnitValue(value[1] || 0, 'px')];
  4677. }
  4678. });
  4679. function convertKeyword2Percent(keyword) {
  4680. if (keyword === 'center') {
  4681. return '50%';
  4682. } else if (keyword === 'left' || keyword === 'top') {
  4683. return '0';
  4684. } else if (keyword === 'right' || keyword === 'bottom') {
  4685. return '100%';
  4686. }
  4687. return keyword;
  4688. }
  4689. var CSSPropertyAngle = /*#__PURE__*/function () {
  4690. function CSSPropertyAngle() {
  4691. this.parser = parseAngle;
  4692. this.parserWithCSSDisabled = null;
  4693. this.mixer = mergeNumbers;
  4694. }
  4695. var _proto = CSSPropertyAngle.prototype;
  4696. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  4697. return convertAngleUnit(parsed);
  4698. };
  4699. return CSSPropertyAngle;
  4700. }();
  4701. /**
  4702. * clipPath / textPath / offsetPath
  4703. */
  4704. var CSSPropertyClipPath = /*#__PURE__*/function () {
  4705. function CSSPropertyClipPath() {}
  4706. var _proto = CSSPropertyClipPath.prototype;
  4707. _proto.calculator = function calculator(name, oldPath, newPath, object) {
  4708. // unset
  4709. if (newPath instanceof CSSKeywordValue) {
  4710. newPath = null;
  4711. }
  4712. runtime.sceneGraphService.updateDisplayObjectDependency(name, oldPath, newPath, object);
  4713. if (name === 'clipPath') {
  4714. // should affect children
  4715. object.forEach(function (leaf) {
  4716. if (leaf.childNodes.length === 0) {
  4717. runtime.sceneGraphService.dirtifyToRoot(leaf);
  4718. }
  4719. });
  4720. }
  4721. return newPath;
  4722. };
  4723. return CSSPropertyClipPath;
  4724. }();
  4725. var CSSPropertyColor = /*#__PURE__*/function () {
  4726. function CSSPropertyColor() {
  4727. this.parser = parseColor;
  4728. this.parserWithCSSDisabled = parseColor;
  4729. this.mixer = mergeColors;
  4730. }
  4731. var _proto = CSSPropertyColor.prototype;
  4732. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  4733. if (parsed instanceof CSSKeywordValue) {
  4734. // 'unset' 'none'
  4735. return parsed.value === 'none' ? noneColor : transparentColor;
  4736. }
  4737. return parsed;
  4738. };
  4739. return CSSPropertyColor;
  4740. }();
  4741. var CSSPropertyFilter = /*#__PURE__*/function () {
  4742. function CSSPropertyFilter() {
  4743. this.parser = parseFilter;
  4744. }
  4745. var _proto = CSSPropertyFilter.prototype;
  4746. _proto.calculator = function calculator(name, oldParsed, parsed) {
  4747. // unset or none
  4748. if (parsed instanceof CSSKeywordValue) {
  4749. return [];
  4750. }
  4751. return parsed;
  4752. };
  4753. return CSSPropertyFilter;
  4754. }();
  4755. function getFontSize(object) {
  4756. var fontSize = object.parsedStyle.fontSize;
  4757. return util.isNil(fontSize) ? null : fontSize;
  4758. }
  4759. /**
  4760. * <length> & <percentage>
  4761. */
  4762. var CSSPropertyLengthOrPercentage = /*#__PURE__*/function () {
  4763. function CSSPropertyLengthOrPercentage() {
  4764. this.parser = parseLengthOrPercentage;
  4765. this.parserWithCSSDisabled = null;
  4766. this.mixer = mergeNumbers;
  4767. }
  4768. var _proto = CSSPropertyLengthOrPercentage.prototype;
  4769. /**
  4770. * according to parent's bounds
  4771. *
  4772. * @example
  4773. * CSS.percent(50) -> CSS.px(0.5 * parent.width)
  4774. */
  4775. _proto.calculator = function calculator(name, oldParsed, computed, object, registry) {
  4776. if (util.isNumber(computed)) {
  4777. return computed;
  4778. }
  4779. if (CSSUnitValue.isRelativeUnit(computed.unit)) {
  4780. if (computed.unit === exports.UnitType.kPercentage) {
  4781. // TODO: merge dimensions
  4782. return 0;
  4783. } else if (computed.unit === exports.UnitType.kEms) {
  4784. if (object.parentNode) {
  4785. var fontSize = getFontSize(object.parentNode);
  4786. if (fontSize) {
  4787. fontSize *= computed.value;
  4788. return fontSize;
  4789. } else {
  4790. registry.addUnresolveProperty(object, name);
  4791. }
  4792. } else {
  4793. registry.addUnresolveProperty(object, name);
  4794. }
  4795. return 0;
  4796. } else if (computed.unit === exports.UnitType.kRems) {
  4797. var _object$ownerDocument;
  4798. if (object === null || object === void 0 ? void 0 : (_object$ownerDocument = object.ownerDocument) === null || _object$ownerDocument === void 0 ? void 0 : _object$ownerDocument.documentElement) {
  4799. var _fontSize = getFontSize(object.ownerDocument.documentElement);
  4800. if (_fontSize) {
  4801. _fontSize *= computed.value;
  4802. return _fontSize;
  4803. } else {
  4804. registry.addUnresolveProperty(object, name);
  4805. }
  4806. } else {
  4807. registry.addUnresolveProperty(object, name);
  4808. }
  4809. return 0;
  4810. }
  4811. } else {
  4812. // remove listener if exists
  4813. // registry.unregisterParentGeometryBoundsChangedHandler(object, name);
  4814. // return absolute value
  4815. return computed.value;
  4816. }
  4817. };
  4818. return CSSPropertyLengthOrPercentage;
  4819. }();
  4820. /**
  4821. * format to Tuple2<CSSUnitValue>
  4822. *
  4823. * @example
  4824. * rect.style.lineDash = 10;
  4825. * rect.style.lineDash = [10, 10];
  4826. * rect.style.lineDash = '10 10';
  4827. */
  4828. var CSSPropertyLengthOrPercentage12 = /*#__PURE__*/function () {
  4829. function CSSPropertyLengthOrPercentage12() {
  4830. this.mixer = mergeNumberLists;
  4831. }
  4832. var _proto = CSSPropertyLengthOrPercentage12.prototype;
  4833. _proto.parser = function parser(radius) {
  4834. var parsed = parseDimensionArray(util.isNumber(radius) ? [radius] : radius);
  4835. var formatted;
  4836. if (parsed.length === 1) {
  4837. formatted = [parsed[0], parsed[0]];
  4838. } else {
  4839. formatted = [parsed[0], parsed[1]];
  4840. }
  4841. return formatted;
  4842. };
  4843. _proto.calculator = function calculator(name, oldParsed, computed) {
  4844. return computed.map(function (c) {
  4845. return c.value;
  4846. });
  4847. };
  4848. return CSSPropertyLengthOrPercentage12;
  4849. }();
  4850. /**
  4851. * used in rounded rect
  4852. *
  4853. * @example
  4854. * rect.style.radius = 10;
  4855. * rect.style.radius = '10 10';
  4856. * rect.style.radius = '10 10 10 10';
  4857. */
  4858. var CSSPropertyLengthOrPercentage14 = /*#__PURE__*/function () {
  4859. function CSSPropertyLengthOrPercentage14() {
  4860. this.mixer = mergeNumberLists;
  4861. }
  4862. var _proto = CSSPropertyLengthOrPercentage14.prototype;
  4863. _proto.parser = function parser(radius) {
  4864. var parsed = parseDimensionArray(util.isNumber(radius) ? [radius] : radius);
  4865. var formatted;
  4866. // format to Tuple<CSSUnitValue>
  4867. if (parsed.length === 1) {
  4868. formatted = [parsed[0], parsed[0], parsed[0], parsed[0]];
  4869. } else if (parsed.length === 2) {
  4870. formatted = [parsed[0], parsed[1], parsed[0], parsed[1]];
  4871. } else if (parsed.length === 3) {
  4872. formatted = [parsed[0], parsed[1], parsed[2], parsed[1]];
  4873. } else {
  4874. formatted = [parsed[0], parsed[1], parsed[2], parsed[3]];
  4875. }
  4876. return formatted;
  4877. };
  4878. _proto.calculator = function calculator(name, oldParsed, computed) {
  4879. return computed.map(function (c) {
  4880. return c.value;
  4881. });
  4882. };
  4883. return CSSPropertyLengthOrPercentage14;
  4884. }();
  4885. /**
  4886. * local position
  4887. */
  4888. var CSSPropertyLocalPosition = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
  4889. _inheritsLoose(CSSPropertyLocalPosition, _CSSPropertyLengthOrP);
  4890. function CSSPropertyLocalPosition() {
  4891. return _CSSPropertyLengthOrP.apply(this, arguments) || this;
  4892. }
  4893. var _proto = CSSPropertyLocalPosition.prototype;
  4894. /**
  4895. * update local position
  4896. */
  4897. _proto.postProcessor = function postProcessor(object, attributes) {
  4898. var x;
  4899. var y;
  4900. var z;
  4901. switch (object.nodeName) {
  4902. case exports.Shape.CIRCLE:
  4903. case exports.Shape.ELLIPSE:
  4904. var _object$parsedStyle = object.parsedStyle,
  4905. cx = _object$parsedStyle.cx,
  4906. cy = _object$parsedStyle.cy,
  4907. cz = _object$parsedStyle.cz;
  4908. if (!util.isNil(cx)) {
  4909. x = cx;
  4910. }
  4911. if (!util.isNil(cy)) {
  4912. y = cy;
  4913. }
  4914. if (!util.isNil(cz)) {
  4915. z = cz;
  4916. }
  4917. break;
  4918. case exports.Shape.LINE:
  4919. var _object$parsedStyle2 = object.parsedStyle,
  4920. x1 = _object$parsedStyle2.x1,
  4921. x2 = _object$parsedStyle2.x2,
  4922. y1 = _object$parsedStyle2.y1,
  4923. y2 = _object$parsedStyle2.y2;
  4924. var minX = Math.min(x1, x2);
  4925. var minY = Math.min(y1, y2);
  4926. x = minX;
  4927. y = minY;
  4928. z = 0;
  4929. break;
  4930. case exports.Shape.RECT:
  4931. case exports.Shape.IMAGE:
  4932. case exports.Shape.GROUP:
  4933. case exports.Shape.HTML:
  4934. case exports.Shape.TEXT:
  4935. case exports.Shape.MESH:
  4936. if (!util.isNil(object.parsedStyle.x)) {
  4937. x = object.parsedStyle.x;
  4938. }
  4939. if (!util.isNil(object.parsedStyle.y)) {
  4940. y = object.parsedStyle.y;
  4941. }
  4942. if (!util.isNil(object.parsedStyle.z)) {
  4943. z = object.parsedStyle.z;
  4944. }
  4945. break;
  4946. }
  4947. if (object.nodeName !== exports.Shape.PATH && object.nodeName !== exports.Shape.POLYLINE && object.nodeName !== exports.Shape.POLYGON) {
  4948. object.parsedStyle.defX = x || 0;
  4949. object.parsedStyle.defY = y || 0;
  4950. }
  4951. var needResetLocalPosition = !util.isNil(x) || !util.isNil(y) || !util.isNil(z);
  4952. // only if `transform` won't be processed later
  4953. if (needResetLocalPosition && attributes.indexOf('transform') === -1) {
  4954. // account for current transform if needed
  4955. var transform = object.parsedStyle.transform;
  4956. if (transform && transform.length) {
  4957. parsedTransformToMat4(transform, object);
  4958. } else {
  4959. var _object$getLocalPosit = object.getLocalPosition(),
  4960. ox = _object$getLocalPosit[0],
  4961. oy = _object$getLocalPosit[1],
  4962. oz = _object$getLocalPosit[2];
  4963. object.setLocalPosition(util.isNil(x) ? ox : x, util.isNil(y) ? oy : y, util.isNil(z) ? oz : z);
  4964. }
  4965. }
  4966. };
  4967. return CSSPropertyLocalPosition;
  4968. }(CSSPropertyLengthOrPercentage);
  4969. var CSSPropertyMarker = /*#__PURE__*/function () {
  4970. function CSSPropertyMarker() {}
  4971. var _proto = CSSPropertyMarker.prototype;
  4972. _proto.calculator = function calculator(name, oldMarker, newMarker, object) {
  4973. var _newMarker;
  4974. // unset
  4975. if (newMarker instanceof CSSKeywordValue) {
  4976. newMarker = null;
  4977. }
  4978. var cloned = (_newMarker = newMarker) === null || _newMarker === void 0 ? void 0 : _newMarker.cloneNode(true);
  4979. if (cloned) {
  4980. // FIXME: SVG should not inherit parent's style, add a flag here
  4981. cloned.style.isMarker = true;
  4982. }
  4983. return cloned;
  4984. };
  4985. return CSSPropertyMarker;
  4986. }();
  4987. var CSSPropertyNumber = /*#__PURE__*/function () {
  4988. function CSSPropertyNumber() {
  4989. this.mixer = mergeNumbers;
  4990. this.parser = parseNumber;
  4991. this.parserWithCSSDisabled = null;
  4992. }
  4993. var _proto = CSSPropertyNumber.prototype;
  4994. _proto.calculator = function calculator(name, oldParsed, computed) {
  4995. return computed.value;
  4996. };
  4997. return CSSPropertyNumber;
  4998. }();
  4999. var CSSPropertyOffsetDistance = /*#__PURE__*/function () {
  5000. function CSSPropertyOffsetDistance() {
  5001. this.parser = parseNumber;
  5002. this.parserWithCSSDisabled = null;
  5003. this.mixer = clampedMergeNumbers(0, 1);
  5004. }
  5005. var _proto = CSSPropertyOffsetDistance.prototype;
  5006. _proto.calculator = function calculator(name, oldParsed, computed) {
  5007. return computed.value;
  5008. };
  5009. _proto.postProcessor = function postProcessor(object) {
  5010. var _object$parsedStyle = object.parsedStyle,
  5011. offsetPath = _object$parsedStyle.offsetPath,
  5012. offsetDistance = _object$parsedStyle.offsetDistance;
  5013. if (!offsetPath) {
  5014. return;
  5015. }
  5016. var nodeName = offsetPath.nodeName;
  5017. if (nodeName === exports.Shape.LINE || nodeName === exports.Shape.PATH || nodeName === exports.Shape.POLYLINE) {
  5018. // set position in world space
  5019. var point = offsetPath.getPoint(offsetDistance);
  5020. if (point) {
  5021. object.parsedStyle.defX = point.x;
  5022. object.parsedStyle.defY = point.y;
  5023. object.setLocalPosition(point.x, point.y);
  5024. }
  5025. }
  5026. };
  5027. return CSSPropertyOffsetDistance;
  5028. }();
  5029. /**
  5030. * opacity
  5031. */
  5032. var CSSPropertyOpacity = /*#__PURE__*/function () {
  5033. function CSSPropertyOpacity() {
  5034. this.parser = parseNumber;
  5035. this.parserWithCSSDisabled = null;
  5036. this.mixer = clampedMergeNumbers(0, 1);
  5037. }
  5038. var _proto = CSSPropertyOpacity.prototype;
  5039. _proto.calculator = function calculator(name, oldParsed, computed) {
  5040. return computed.value;
  5041. };
  5042. return CSSPropertyOpacity;
  5043. }();
  5044. /**
  5045. * Axis-Aligned Bounding Box
  5046. * 为了便于后续 Frustum Culling,通过查找表定义 p-vertex 和 n-vertex
  5047. * @see https://github.com/antvis/GWebGPUEngine/issues/3
  5048. */
  5049. var AABB = /*#__PURE__*/function () {
  5050. function AABB() {
  5051. this.center = [0, 0, 0];
  5052. this.halfExtents = [0, 0, 0];
  5053. this.min = [0, 0, 0];
  5054. this.max = [0, 0, 0];
  5055. }
  5056. AABB.isEmpty = function isEmpty(aabb) {
  5057. return !aabb || aabb.halfExtents[0] === 0 && aabb.halfExtents[1] === 0 && aabb.halfExtents[2] === 0;
  5058. };
  5059. var _proto = AABB.prototype;
  5060. // center: vec3 = vec3.create();
  5061. // halfExtents: vec3 = vec3.create();
  5062. // min: vec3 = vec3.create();
  5063. // max: vec3 = vec3.create();
  5064. _proto.update = function update(center, halfExtents) {
  5065. copyVec3(this.center, center);
  5066. copyVec3(this.halfExtents, halfExtents);
  5067. subVec3(this.min, this.center, this.halfExtents);
  5068. addVec3(this.max, this.center, this.halfExtents);
  5069. // vec3.copy(this.center, center);
  5070. // vec3.copy(this.halfExtents, halfExtents);
  5071. // vec3.sub(this.min, this.center, this.halfExtents);
  5072. // vec3.add(this.max, this.center, this.halfExtents);
  5073. };
  5074. _proto.setMinMax = function setMinMax(min, max) {
  5075. // vec3.add(this.center, max, min);
  5076. // vec3.scale(this.center, this.center, 0.5);
  5077. // vec3.sub(this.halfExtents, max, min);
  5078. // vec3.scale(this.halfExtents, this.halfExtents, 0.5);
  5079. // vec3.copy(this.min, min);
  5080. // vec3.copy(this.max, max);
  5081. addVec3(this.center, max, min);
  5082. scaleVec3(this.center, this.center, 0.5);
  5083. subVec3(this.halfExtents, max, min);
  5084. scaleVec3(this.halfExtents, this.halfExtents, 0.5);
  5085. copyVec3(this.min, min);
  5086. copyVec3(this.max, max);
  5087. };
  5088. _proto.getMin = function getMin() {
  5089. return this.min;
  5090. };
  5091. _proto.getMax = function getMax() {
  5092. return this.max;
  5093. };
  5094. _proto.add = function add(aabb) {
  5095. if (AABB.isEmpty(aabb)) {
  5096. return;
  5097. }
  5098. if (AABB.isEmpty(this)) {
  5099. this.setMinMax(aabb.getMin(), aabb.getMax());
  5100. return;
  5101. }
  5102. var tc = this.center;
  5103. var tcx = tc[0];
  5104. var tcy = tc[1];
  5105. var tcz = tc[2];
  5106. var th = this.halfExtents;
  5107. var thx = th[0];
  5108. var thy = th[1];
  5109. var thz = th[2];
  5110. var tminx = tcx - thx;
  5111. var tmaxx = tcx + thx;
  5112. var tminy = tcy - thy;
  5113. var tmaxy = tcy + thy;
  5114. var tminz = tcz - thz;
  5115. var tmaxz = tcz + thz;
  5116. var oc = aabb.center;
  5117. var ocx = oc[0];
  5118. var ocy = oc[1];
  5119. var ocz = oc[2];
  5120. var oh = aabb.halfExtents;
  5121. var ohx = oh[0];
  5122. var ohy = oh[1];
  5123. var ohz = oh[2];
  5124. var ominx = ocx - ohx;
  5125. var omaxx = ocx + ohx;
  5126. var ominy = ocy - ohy;
  5127. var omaxy = ocy + ohy;
  5128. var ominz = ocz - ohz;
  5129. var omaxz = ocz + ohz;
  5130. if (ominx < tminx) {
  5131. tminx = ominx;
  5132. }
  5133. if (omaxx > tmaxx) {
  5134. tmaxx = omaxx;
  5135. }
  5136. if (ominy < tminy) {
  5137. tminy = ominy;
  5138. }
  5139. if (omaxy > tmaxy) {
  5140. tmaxy = omaxy;
  5141. }
  5142. if (ominz < tminz) {
  5143. tminz = ominz;
  5144. }
  5145. if (omaxz > tmaxz) {
  5146. tmaxz = omaxz;
  5147. }
  5148. tc[0] = (tminx + tmaxx) * 0.5;
  5149. tc[1] = (tminy + tmaxy) * 0.5;
  5150. tc[2] = (tminz + tmaxz) * 0.5;
  5151. th[0] = (tmaxx - tminx) * 0.5;
  5152. th[1] = (tmaxy - tminy) * 0.5;
  5153. th[2] = (tmaxz - tminz) * 0.5;
  5154. this.min[0] = tminx;
  5155. this.min[1] = tminy;
  5156. this.min[2] = tminz;
  5157. this.max[0] = tmaxx;
  5158. this.max[1] = tmaxy;
  5159. this.max[2] = tmaxz;
  5160. };
  5161. _proto.setFromTransformedAABB = function setFromTransformedAABB(aabb, m) {
  5162. var bc = this.center;
  5163. var br = this.halfExtents;
  5164. var ac = aabb.center;
  5165. var ar = aabb.halfExtents;
  5166. var mx0 = m[0];
  5167. var mx1 = m[4];
  5168. var mx2 = m[8];
  5169. var my0 = m[1];
  5170. var my1 = m[5];
  5171. var my2 = m[9];
  5172. var mz0 = m[2];
  5173. var mz1 = m[6];
  5174. var mz2 = m[10];
  5175. var mx0a = Math.abs(mx0);
  5176. var mx1a = Math.abs(mx1);
  5177. var mx2a = Math.abs(mx2);
  5178. var my0a = Math.abs(my0);
  5179. var my1a = Math.abs(my1);
  5180. var my2a = Math.abs(my2);
  5181. var mz0a = Math.abs(mz0);
  5182. var mz1a = Math.abs(mz1);
  5183. var mz2a = Math.abs(mz2);
  5184. bc[0] = m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2];
  5185. bc[1] = m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2];
  5186. bc[2] = m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2];
  5187. // vec3.set(
  5188. // bc,
  5189. // m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
  5190. // m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
  5191. // m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2],
  5192. // );
  5193. br[0] = mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2];
  5194. br[1] = my0a * ar[0] + my1a * ar[1] + my2a * ar[2];
  5195. br[2] = mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2];
  5196. // vec3.set(
  5197. // br,
  5198. // mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
  5199. // my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
  5200. // mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2],
  5201. // );
  5202. // this.min = vec3.sub(this.min, bc, br);
  5203. // this.max = vec3.add(this.max, bc, br);
  5204. subVec3(this.min, bc, br);
  5205. addVec3(this.max, bc, br);
  5206. };
  5207. _proto.intersects = function intersects(aabb) {
  5208. var aMax = this.getMax();
  5209. var aMin = this.getMin();
  5210. var bMax = aabb.getMax();
  5211. var bMin = aabb.getMin();
  5212. return aMin[0] <= bMax[0] && aMax[0] >= bMin[0] && aMin[1] <= bMax[1] && aMax[1] >= bMin[1] && aMin[2] <= bMax[2] && aMax[2] >= bMin[2];
  5213. };
  5214. _proto.intersection = function intersection(aabb) {
  5215. if (!this.intersects(aabb)) {
  5216. return null;
  5217. }
  5218. var intersection = new AABB();
  5219. // const min = vec3.max(vec3.create(), this.getMin(), aabb.getMin());
  5220. // const max = vec3.min(vec3.create(), this.getMax(), aabb.getMax());
  5221. var min = maxVec3([0, 0, 0], this.getMin(), aabb.getMin());
  5222. var max = minVec3([0, 0, 0], this.getMax(), aabb.getMax());
  5223. intersection.setMinMax(min, max);
  5224. return intersection;
  5225. }
  5226. // containsPoint(point: vec3) {
  5227. // const min = this.getMin();
  5228. // const max = this.getMax();
  5229. // return !(
  5230. // point[0] < min[0] ||
  5231. // point[0] > max[0] ||
  5232. // point[1] < min[1] ||
  5233. // point[1] > max[1] ||
  5234. // point[2] < min[2] ||
  5235. // point[2] > max[2]
  5236. // );
  5237. // }
  5238. /**
  5239. * get n-vertex
  5240. * @param plane plane of CullingVolume
  5241. */;
  5242. _proto.getNegativeFarPoint = function getNegativeFarPoint(plane) {
  5243. if (plane.pnVertexFlag === 0x111) {
  5244. return copyVec3([0, 0, 0], this.min);
  5245. // return vec3.copy(vec3.create(), this.min);
  5246. } else if (plane.pnVertexFlag === 0x110) {
  5247. return [this.min[0], this.min[1], this.max[2]];
  5248. // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
  5249. } else if (plane.pnVertexFlag === 0x101) {
  5250. return [this.min[0], this.max[1], this.min[2]];
  5251. // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
  5252. } else if (plane.pnVertexFlag === 0x100) {
  5253. return [this.min[0], this.max[1], this.max[2]];
  5254. // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
  5255. } else if (plane.pnVertexFlag === 0x011) {
  5256. return [this.max[0], this.min[1], this.min[2]];
  5257. // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
  5258. } else if (plane.pnVertexFlag === 0x010) {
  5259. return [this.max[0], this.min[1], this.max[2]];
  5260. // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
  5261. } else if (plane.pnVertexFlag === 0x001) {
  5262. return [this.max[0], this.max[1], this.min[2]];
  5263. // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
  5264. } else {
  5265. return [this.max[0], this.max[1], this.max[2]];
  5266. // return vec3.fromValues(this.max[0], this.max[1], this.max[2]);
  5267. }
  5268. }
  5269. /**
  5270. * get p-vertex
  5271. * @param plane plane of CullingVolume
  5272. */;
  5273. _proto.getPositiveFarPoint = function getPositiveFarPoint(plane) {
  5274. if (plane.pnVertexFlag === 0x111) {
  5275. return copyVec3([0, 0, 0], this.max);
  5276. // return vec3.copy(vec3.create(), this.max);
  5277. } else if (plane.pnVertexFlag === 0x110) {
  5278. return [this.max[0], this.max[1], this.min[2]];
  5279. // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
  5280. } else if (plane.pnVertexFlag === 0x101) {
  5281. return [this.max[0], this.min[1], this.max[2]];
  5282. // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
  5283. } else if (plane.pnVertexFlag === 0x100) {
  5284. return [this.max[0], this.min[1], this.min[2]];
  5285. // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
  5286. } else if (plane.pnVertexFlag === 0x011) {
  5287. return [this.min[0], this.max[1], this.max[2]];
  5288. // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
  5289. } else if (plane.pnVertexFlag === 0x010) {
  5290. return [this.min[0], this.max[1], this.min[2]];
  5291. // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
  5292. } else if (plane.pnVertexFlag === 0x001) {
  5293. return [this.min[0], this.min[1], this.max[2]];
  5294. // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
  5295. } else {
  5296. return [this.min[0], this.min[1], this.min[2]];
  5297. // return vec3.fromValues(this.min[0], this.min[1], this.min[2]);
  5298. }
  5299. };
  5300. return AABB;
  5301. }();
  5302. var Plane = /*#__PURE__*/function () {
  5303. function Plane(distance, normal) {
  5304. this.distance = void 0;
  5305. this.normal = void 0;
  5306. /**
  5307. * lookup table for p-vertex & n-vertex when doing frustum culling
  5308. */
  5309. this.pnVertexFlag = void 0;
  5310. this.distance = distance || 0;
  5311. this.normal = normal || glMatrix.vec3.fromValues(0, 1, 0);
  5312. this.updatePNVertexFlag();
  5313. }
  5314. var _proto = Plane.prototype;
  5315. _proto.updatePNVertexFlag = function updatePNVertexFlag() {
  5316. this.pnVertexFlag = (Number(this.normal[0] >= 0) << 8) + (Number(this.normal[1] >= 0) << 4) + Number(this.normal[2] >= 0);
  5317. };
  5318. _proto.distanceToPoint = function distanceToPoint(point) {
  5319. return glMatrix.vec3.dot(point, this.normal) - this.distance;
  5320. };
  5321. _proto.normalize = function normalize() {
  5322. var invLen = 1 / glMatrix.vec3.len(this.normal);
  5323. glMatrix.vec3.scale(this.normal, this.normal, invLen);
  5324. this.distance *= invLen;
  5325. };
  5326. _proto.intersectsLine = function intersectsLine(start, end, point) {
  5327. var d0 = this.distanceToPoint(start);
  5328. var d1 = this.distanceToPoint(end);
  5329. var t = d0 / (d0 - d1);
  5330. var intersects = t >= 0 && t <= 1;
  5331. if (intersects && point) {
  5332. glMatrix.vec3.lerp(point, start, end, t);
  5333. }
  5334. return intersects;
  5335. };
  5336. return Plane;
  5337. }();
  5338. (function (Mask) {
  5339. Mask[Mask["OUTSIDE"] = 4294967295] = "OUTSIDE";
  5340. Mask[Mask["INSIDE"] = 0] = "INSIDE";
  5341. Mask[Mask["INDETERMINATE"] = 2147483647] = "INDETERMINATE";
  5342. })(exports.Mask || (exports.Mask = {}));
  5343. var Frustum = /*#__PURE__*/function () {
  5344. function Frustum(planes) {
  5345. this.planes = [];
  5346. if (planes) {
  5347. this.planes = planes;
  5348. } else {
  5349. for (var i = 0; i < 6; i++) {
  5350. this.planes.push(new Plane());
  5351. }
  5352. }
  5353. }
  5354. /**
  5355. * extract 6 planes from projectionMatrix
  5356. * @see http://www8.cs.umu.se/kurser/5DV051/HT12/lab/plane_extraction.pdf
  5357. */
  5358. var _proto = Frustum.prototype;
  5359. _proto.extractFromVPMatrix = function extractFromVPMatrix(projectionMatrix) {
  5360. // @ts-ignore
  5361. var m0 = projectionMatrix[0],
  5362. m1 = projectionMatrix[1],
  5363. m2 = projectionMatrix[2],
  5364. m3 = projectionMatrix[3],
  5365. m4 = projectionMatrix[4],
  5366. m5 = projectionMatrix[5],
  5367. m6 = projectionMatrix[6],
  5368. m7 = projectionMatrix[7],
  5369. m8 = projectionMatrix[8],
  5370. m9 = projectionMatrix[9],
  5371. m10 = projectionMatrix[10],
  5372. m11 = projectionMatrix[11],
  5373. m12 = projectionMatrix[12],
  5374. m13 = projectionMatrix[13],
  5375. m14 = projectionMatrix[14],
  5376. m15 = projectionMatrix[15];
  5377. // right
  5378. glMatrix.vec3.set(this.planes[0].normal, m3 - m0, m7 - m4, m11 - m8);
  5379. this.planes[0].distance = m15 - m12;
  5380. // left
  5381. glMatrix.vec3.set(this.planes[1].normal, m3 + m0, m7 + m4, m11 + m8);
  5382. this.planes[1].distance = m15 + m12;
  5383. // bottom
  5384. glMatrix.vec3.set(this.planes[2].normal, m3 + m1, m7 + m5, m11 + m9);
  5385. this.planes[2].distance = m15 + m13;
  5386. // top
  5387. glMatrix.vec3.set(this.planes[3].normal, m3 - m1, m7 - m5, m11 - m9);
  5388. this.planes[3].distance = m15 - m13;
  5389. // far
  5390. glMatrix.vec3.set(this.planes[4].normal, m3 - m2, m7 - m6, m11 - m10);
  5391. this.planes[4].distance = m15 - m14;
  5392. // near
  5393. glMatrix.vec3.set(this.planes[5].normal, m3 + m2, m7 + m6, m11 + m10);
  5394. this.planes[5].distance = m15 + m14;
  5395. this.planes.forEach(function (plane) {
  5396. plane.normalize();
  5397. plane.updatePNVertexFlag();
  5398. });
  5399. };
  5400. return Frustum;
  5401. }();
  5402. var Point = /*#__PURE__*/function () {
  5403. function Point(x, y) {
  5404. if (x === void 0) {
  5405. x = 0;
  5406. }
  5407. if (y === void 0) {
  5408. y = 0;
  5409. }
  5410. this.x = 0;
  5411. this.y = 0;
  5412. this.x = x;
  5413. this.y = y;
  5414. }
  5415. var _proto = Point.prototype;
  5416. _proto.clone = function clone() {
  5417. return new Point(this.x, this.y);
  5418. };
  5419. _proto.copyFrom = function copyFrom(p) {
  5420. this.x = p.x;
  5421. this.y = p.y;
  5422. };
  5423. return Point;
  5424. }();
  5425. var Rectangle = /*#__PURE__*/function () {
  5426. function Rectangle(x, y, width, height) {
  5427. this.x = void 0;
  5428. this.y = void 0;
  5429. this.width = void 0;
  5430. this.height = void 0;
  5431. this.left = void 0;
  5432. this.right = void 0;
  5433. this.top = void 0;
  5434. this.bottom = void 0;
  5435. this.x = x;
  5436. this.y = y;
  5437. this.width = width;
  5438. this.height = height;
  5439. this.left = x;
  5440. this.right = x + width;
  5441. this.top = y;
  5442. this.bottom = y + height;
  5443. }
  5444. var _proto = Rectangle.prototype;
  5445. _proto.toJSON = function toJSON() {};
  5446. return Rectangle;
  5447. }();
  5448. var CSSPropertyPath = /*#__PURE__*/function () {
  5449. function CSSPropertyPath() {
  5450. /**
  5451. * path2Curve
  5452. */
  5453. this.parser = parsePath;
  5454. this.parserWithCSSDisabled = parsePath;
  5455. this.mixer = mergePaths;
  5456. }
  5457. var _proto = CSSPropertyPath.prototype;
  5458. _proto.calculator = function calculator(name, oldParsed, parsed) {
  5459. // unset
  5460. if (parsed instanceof CSSKeywordValue && parsed.value === 'unset') {
  5461. return {
  5462. absolutePath: [],
  5463. hasArc: false,
  5464. segments: [],
  5465. polygons: [],
  5466. polylines: [],
  5467. curve: null,
  5468. totalLength: 0,
  5469. rect: new Rectangle(0, 0, 0, 0)
  5470. };
  5471. }
  5472. return parsed;
  5473. };
  5474. /**
  5475. * update local position
  5476. */
  5477. _proto.postProcessor = function postProcessor(object, attributes) {
  5478. if (object.nodeName === exports.Shape.PATH && attributes.indexOf('transform') === -1) {
  5479. var _object$parsedStyle = object.parsedStyle,
  5480. _object$parsedStyle$d = _object$parsedStyle.defX,
  5481. defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
  5482. _object$parsedStyle$d2 = _object$parsedStyle.defY,
  5483. defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
  5484. object.setLocalPosition(defX, defY);
  5485. }
  5486. };
  5487. return CSSPropertyPath;
  5488. }();
  5489. var CSSPropertyPoints = /*#__PURE__*/function () {
  5490. function CSSPropertyPoints() {
  5491. this.parser = parsePoints;
  5492. this.mixer = mergePoints;
  5493. }
  5494. var _proto = CSSPropertyPoints.prototype;
  5495. /**
  5496. * update local position
  5497. */
  5498. _proto.postProcessor = function postProcessor(object, attributes) {
  5499. if ((object.nodeName === exports.Shape.POLYGON || object.nodeName === exports.Shape.POLYLINE) && attributes.indexOf('transform') === -1) {
  5500. var _object$parsedStyle = object.parsedStyle,
  5501. defX = _object$parsedStyle.defX,
  5502. defY = _object$parsedStyle.defY;
  5503. object.setLocalPosition(defX, defY);
  5504. }
  5505. };
  5506. return CSSPropertyPoints;
  5507. }();
  5508. var CSSPropertyShadowBlur = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
  5509. _inheritsLoose(CSSPropertyShadowBlur, _CSSPropertyLengthOrP);
  5510. function CSSPropertyShadowBlur() {
  5511. var _this;
  5512. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5513. args[_key] = arguments[_key];
  5514. }
  5515. _this = _CSSPropertyLengthOrP.call.apply(_CSSPropertyLengthOrP, [this].concat(args)) || this;
  5516. _this.mixer = clampedMergeNumbers(0, Infinity);
  5517. return _this;
  5518. }
  5519. return CSSPropertyShadowBlur;
  5520. }(CSSPropertyLengthOrPercentage);
  5521. var CSSPropertyText = /*#__PURE__*/function () {
  5522. function CSSPropertyText() {}
  5523. var _proto = CSSPropertyText.prototype;
  5524. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  5525. if (parsed instanceof CSSKeywordValue) {
  5526. if (parsed.value === 'unset') {
  5527. return '';
  5528. } else {
  5529. return parsed.value;
  5530. }
  5531. }
  5532. // allow number as valid text content
  5533. return "" + parsed;
  5534. };
  5535. _proto.postProcessor = function postProcessor(object) {
  5536. object.nodeValue = "" + object.parsedStyle.text || '';
  5537. };
  5538. return CSSPropertyText;
  5539. }();
  5540. /**
  5541. * it must transform after text get parsed
  5542. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform
  5543. */
  5544. var CSSPropertyTextTransform = /*#__PURE__*/function () {
  5545. function CSSPropertyTextTransform() {}
  5546. var _proto = CSSPropertyTextTransform.prototype;
  5547. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  5548. var rawText = object.getAttribute('text');
  5549. if (rawText) {
  5550. var transformedText = rawText;
  5551. if (parsed.value === 'capitalize') {
  5552. transformedText = rawText.charAt(0).toUpperCase() + rawText.slice(1);
  5553. } else if (parsed.value === 'lowercase') {
  5554. transformedText = rawText.toLowerCase();
  5555. } else if (parsed.value === 'uppercase') {
  5556. transformedText = rawText.toUpperCase();
  5557. }
  5558. object.parsedStyle.text = transformedText;
  5559. }
  5560. return parsed.value;
  5561. };
  5562. return CSSPropertyTextTransform;
  5563. }();
  5564. /**
  5565. * @see /zh/docs/api/animation#支持变换的属性
  5566. *
  5567. * support the following formats like CSS Transform:
  5568. *
  5569. * scale
  5570. * * scale(x, y)
  5571. * * scaleX(x)
  5572. * * scaleY(x)
  5573. * * scaleZ(z)
  5574. * * scale3d(x, y, z)
  5575. *
  5576. * translate (unit: none, px, %(relative to its bounds))
  5577. * * translate(x, y) eg. translate(0, 0) translate(0, 30px) translate(100%, 100%)
  5578. * * translateX(0)
  5579. * * translateY(0)
  5580. * * translateZ(0)
  5581. * * translate3d(0, 0, 0)
  5582. *
  5583. * rotate (unit: deg rad turn)
  5584. * * rotate(0.5turn) rotate(30deg) rotate(1rad)
  5585. *
  5586. * none
  5587. *
  5588. * unsupported for now:
  5589. * * calc() eg. translate(calc(100% + 10px))
  5590. * * matrix/matrix3d()
  5591. * * skew/skewX/skewY
  5592. * * perspective
  5593. */
  5594. var CSSPropertyTransform = /*#__PURE__*/function () {
  5595. function CSSPropertyTransform() {
  5596. this.parser = parseTransform;
  5597. this.parserWithCSSDisabled = parseTransform;
  5598. this.mixer = mergeTransforms;
  5599. }
  5600. var _proto = CSSPropertyTransform.prototype;
  5601. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  5602. // 'none'
  5603. if (parsed instanceof CSSKeywordValue) {
  5604. return [];
  5605. }
  5606. return parsed;
  5607. };
  5608. _proto.postProcessor = function postProcessor(object) {
  5609. var transform = object.parsedStyle.transform;
  5610. parsedTransformToMat4(transform, object);
  5611. };
  5612. return CSSPropertyTransform;
  5613. }();
  5614. /**
  5615. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
  5616. * @example
  5617. * [10px, 10px] [10%, 10%]
  5618. */
  5619. var CSSPropertyTransformOrigin = function CSSPropertyTransformOrigin() {
  5620. this.parser = parseTransformOrigin;
  5621. };
  5622. /**
  5623. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
  5624. */
  5625. (function (Strategy) {
  5626. Strategy[Strategy["Standard"] = 0] = "Standard";
  5627. })(exports.Strategy || (exports.Strategy = {}));
  5628. (function (SortReason) {
  5629. SortReason[SortReason["ADDED"] = 0] = "ADDED";
  5630. SortReason[SortReason["REMOVED"] = 1] = "REMOVED";
  5631. SortReason[SortReason["Z_INDEX_CHANGED"] = 2] = "Z_INDEX_CHANGED";
  5632. })(exports.SortReason || (exports.SortReason = {}));
  5633. var CSSPropertyZIndex = /*#__PURE__*/function () {
  5634. function CSSPropertyZIndex() {
  5635. this.parser = parseNumber;
  5636. }
  5637. var _proto = CSSPropertyZIndex.prototype;
  5638. _proto.calculator = function calculator(name, oldParsed, computed, object) {
  5639. return computed.value;
  5640. };
  5641. _proto.postProcessor = function postProcessor(object) {
  5642. if (object.parentNode) {
  5643. var parentEntity = object.parentNode;
  5644. var parentRenderable = parentEntity.renderable;
  5645. var parentSortable = parentEntity.sortable;
  5646. if (parentRenderable) {
  5647. parentRenderable.dirty = true;
  5648. }
  5649. // need re-sort on parent
  5650. if (parentSortable) {
  5651. parentSortable.dirty = true;
  5652. parentSortable.dirtyReason = exports.SortReason.Z_INDEX_CHANGED;
  5653. }
  5654. }
  5655. };
  5656. return CSSPropertyZIndex;
  5657. }();
  5658. /**
  5659. * canvas.customElements
  5660. *
  5661. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
  5662. */
  5663. var CustomElementRegistry = /*#__PURE__*/function () {
  5664. function CustomElementRegistry() {
  5665. this.registry = {};
  5666. this.define(exports.Shape.CIRCLE, Circle);
  5667. this.define(exports.Shape.ELLIPSE, Ellipse);
  5668. this.define(exports.Shape.RECT, Rect);
  5669. this.define(exports.Shape.IMAGE, Image);
  5670. this.define(exports.Shape.LINE, Line);
  5671. this.define(exports.Shape.GROUP, Group);
  5672. this.define(exports.Shape.PATH, Path);
  5673. this.define(exports.Shape.POLYGON, Polygon);
  5674. this.define(exports.Shape.POLYLINE, Polyline);
  5675. this.define(exports.Shape.TEXT, Text);
  5676. this.define(exports.Shape.HTML, HTML);
  5677. }
  5678. var _proto = CustomElementRegistry.prototype;
  5679. _proto.define = function define(name, constructor) {
  5680. this.registry[name] = constructor;
  5681. }
  5682. /**
  5683. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/get
  5684. */;
  5685. _proto.get = function get(name) {
  5686. return this.registry[name];
  5687. };
  5688. return CustomElementRegistry;
  5689. }();
  5690. function isFederatedEvent(value) {
  5691. return !!value.type;
  5692. }
  5693. /**
  5694. * An DOM-compatible synthetic event implementation that is "forwarded" on behalf of an original
  5695. * FederatedEvent or native {@link https://dom.spec.whatwg.org/#event Event}.
  5696. */
  5697. var FederatedEvent = /*#__PURE__*/function () {
  5698. /**
  5699. * The event boundary which manages this event. Propagation can only occur
  5700. * within the boundary's jurisdiction.
  5701. */
  5702. function FederatedEvent(manager) {
  5703. /**
  5704. * The type of event, supports the following:
  5705. * * pointerdown
  5706. * * touchstart
  5707. * * mousedown
  5708. * * rightdown
  5709. * * ...
  5710. */
  5711. this.type = void 0;
  5712. /**
  5713. * The propagation phase.
  5714. * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
  5715. */
  5716. this.eventPhase = FederatedEvent.prototype.NONE;
  5717. /**
  5718. * can be used to implement event delegation
  5719. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
  5720. */
  5721. this.target = void 0;
  5722. /**
  5723. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles
  5724. */
  5725. this.bubbles = true;
  5726. /**
  5727. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/cancelBubble
  5728. */
  5729. this.cancelBubble = true;
  5730. /**
  5731. * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
  5732. */
  5733. this.cancelable = false;
  5734. /** the event target when listeners binded */
  5735. this.currentTarget = void 0;
  5736. /** Flags whether the default response of the user agent was prevent through this event. */
  5737. this.defaultPrevented = false;
  5738. /**
  5739. * timestamp when the event created
  5740. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/timeStamp
  5741. */
  5742. this.timeStamp = void 0;
  5743. /**
  5744. * the original event.
  5745. */
  5746. this.nativeEvent = void 0;
  5747. /** The original event that caused this event, if any. */
  5748. this.originalEvent = void 0;
  5749. /** Flags whether propagation was stopped. */
  5750. this.propagationStopped = false;
  5751. /** Flags whether propagation was immediately stopped. */
  5752. this.propagationImmediatelyStopped = false;
  5753. this.manager = void 0;
  5754. /** Event-specific detail */
  5755. this.detail = void 0;
  5756. /**
  5757. * The coordinates of the evnet relative to the nearest DOM layer.
  5758. * This is a non-standard property.
  5759. */
  5760. this.layer = new Point();
  5761. /**
  5762. * The coordinates of the event relative to the DOM document.
  5763. * This is a non-standard property.
  5764. * relative to the DOM document.
  5765. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/pageX
  5766. */
  5767. this.page = new Point();
  5768. /**
  5769. * relative to Canvas, origin is left-top
  5770. */
  5771. this.canvas = new Point();
  5772. /**
  5773. * relative to Viewport, account for Camera
  5774. */
  5775. this.viewport = new Point();
  5776. this.path = void 0;
  5777. /**
  5778. * @see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
  5779. */
  5780. this.view = void 0;
  5781. this.which = void 0;
  5782. this.returnValue = void 0;
  5783. this.srcElement = void 0;
  5784. this.composed = false;
  5785. this.isTrusted = void 0;
  5786. this.NONE = 0;
  5787. this.CAPTURING_PHASE = 1;
  5788. this.AT_TARGET = 2;
  5789. this.BUBBLING_PHASE = 3;
  5790. this.manager = manager;
  5791. }
  5792. var _proto = FederatedEvent.prototype;
  5793. /**
  5794. * The propagation path for this event
  5795. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/composedPath
  5796. *
  5797. * So composedPath()[0] represents the original target.
  5798. * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events#retargeting
  5799. */
  5800. _proto.composedPath = function composedPath() {
  5801. if (this.manager && (!this.path || this.path[0] !== this.target)) {
  5802. this.path = this.target ? this.manager.propagationPath(this.target) : [];
  5803. }
  5804. return this.path;
  5805. }
  5806. /**
  5807. * @deprecated
  5808. */;
  5809. /**
  5810. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
  5811. */
  5812. _proto.preventDefault = function preventDefault() {
  5813. if (this.nativeEvent instanceof Event && this.nativeEvent.cancelable) {
  5814. this.nativeEvent.preventDefault();
  5815. }
  5816. this.defaultPrevented = true;
  5817. }
  5818. /**
  5819. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopImmediatePropagation
  5820. */;
  5821. _proto.stopImmediatePropagation = function stopImmediatePropagation() {
  5822. this.propagationImmediatelyStopped = true;
  5823. }
  5824. /**
  5825. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation
  5826. */;
  5827. _proto.stopPropagation = function stopPropagation() {
  5828. this.propagationStopped = true;
  5829. };
  5830. /**
  5831. * added for compatibility with DOM Event,
  5832. * deprecated props and methods
  5833. */
  5834. _proto.initEvent = function initEvent() {};
  5835. _proto.initUIEvent = function initUIEvent() {};
  5836. _proto.clone = function clone() {
  5837. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  5838. };
  5839. _createClass(FederatedEvent, [{
  5840. key: "name",
  5841. get:
  5842. /**
  5843. * @deprecated
  5844. */
  5845. function get() {
  5846. return this.type;
  5847. }
  5848. }, {
  5849. key: "layerX",
  5850. get: function get() {
  5851. return this.layer.x;
  5852. }
  5853. }, {
  5854. key: "layerY",
  5855. get: function get() {
  5856. return this.layer.y;
  5857. }
  5858. }, {
  5859. key: "pageX",
  5860. get: function get() {
  5861. return this.page.x;
  5862. }
  5863. }, {
  5864. key: "pageY",
  5865. get: function get() {
  5866. return this.page.y;
  5867. }
  5868. }, {
  5869. key: "x",
  5870. get: function get() {
  5871. return this.canvas.x;
  5872. }
  5873. }, {
  5874. key: "y",
  5875. get: function get() {
  5876. return this.canvas.y;
  5877. }
  5878. }, {
  5879. key: "canvasX",
  5880. get: function get() {
  5881. return this.canvas.x;
  5882. }
  5883. }, {
  5884. key: "canvasY",
  5885. get: function get() {
  5886. return this.canvas.y;
  5887. }
  5888. }, {
  5889. key: "viewportX",
  5890. get: function get() {
  5891. return this.viewport.x;
  5892. }
  5893. }, {
  5894. key: "viewportY",
  5895. get: function get() {
  5896. return this.viewport.y;
  5897. }
  5898. }, {
  5899. key: "propagationPath",
  5900. get: function get() {
  5901. return this.composedPath();
  5902. }
  5903. }]);
  5904. return FederatedEvent;
  5905. }();
  5906. /**
  5907. * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
  5908. *
  5909. * @example
  5910. const event = new CustomEvent('build', { detail: { prop1: 'xx' } });
  5911. circle.addEventListener('build', (e) => {
  5912. e.target; // circle
  5913. e.detail; // { prop1: 'xx' }
  5914. });
  5915. circle.dispatchEvent(event);
  5916. */
  5917. var CustomEvent = /*#__PURE__*/function (_FederatedEvent) {
  5918. _inheritsLoose(CustomEvent, _FederatedEvent);
  5919. // eslint-disable-next-line @typescript-eslint/ban-types
  5920. function CustomEvent(eventName, object) {
  5921. var _this;
  5922. _this = _FederatedEvent.call(this, null) || this;
  5923. _this.type = eventName;
  5924. _this.detail = object;
  5925. // compatible with G 3.0
  5926. Object.assign(_assertThisInitialized(_this), object);
  5927. return _this;
  5928. }
  5929. return CustomEvent;
  5930. }(FederatedEvent);
  5931. var DELEGATION_SPLITTER = ':';
  5932. /**
  5933. * Objects that can receive events and may have listeners for them.
  5934. * eg. Element, Canvas, DisplayObject
  5935. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
  5936. */
  5937. var EventTarget = /*#__PURE__*/function () {
  5938. function EventTarget() {
  5939. /**
  5940. * event emitter
  5941. */
  5942. this.emitter = new EventEmitter__default['default']();
  5943. }
  5944. var _proto = EventTarget.prototype;
  5945. /**
  5946. * @deprecated
  5947. * @alias addEventListener
  5948. */
  5949. _proto.on = function on(type, listener, options) {
  5950. this.addEventListener(type, listener, options);
  5951. return this;
  5952. }
  5953. /**
  5954. * support `capture` & `once` in options
  5955. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
  5956. */;
  5957. _proto.addEventListener = function addEventListener(type, listener, options) {
  5958. var capture = util.isBoolean(options) && options || util.isObject(options) && options.capture;
  5959. var once = util.isObject(options) && options.once;
  5960. var context = isFunction(listener) ? undefined : listener;
  5961. // compatible with G 3.0
  5962. // support using delegate name in event type, eg. 'node:click'
  5963. var useDelegatedName = false;
  5964. var delegatedName = '';
  5965. if (type.indexOf(DELEGATION_SPLITTER) > -1) {
  5966. var _type$split = type.split(DELEGATION_SPLITTER),
  5967. name = _type$split[0],
  5968. eventType = _type$split[1];
  5969. type = eventType;
  5970. delegatedName = name;
  5971. useDelegatedName = true;
  5972. }
  5973. type = capture ? type + "capture" : type;
  5974. listener = isFunction(listener) ? listener : listener.handleEvent;
  5975. // compatible with G 3.0
  5976. if (useDelegatedName) {
  5977. var originListener = listener;
  5978. listener = function listener() {
  5979. var _args$0$target;
  5980. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5981. args[_key] = arguments[_key];
  5982. }
  5983. if (((_args$0$target = args[0].target) === null || _args$0$target === void 0 ? void 0 : _args$0$target.name) !== delegatedName) {
  5984. return;
  5985. }
  5986. // @ts-ignore
  5987. originListener.apply(void 0, args);
  5988. };
  5989. }
  5990. if (once) {
  5991. this.emitter.once(type, listener, context);
  5992. } else {
  5993. this.emitter.on(type, listener, context);
  5994. }
  5995. return this;
  5996. }
  5997. /**
  5998. * @deprecated
  5999. * @alias removeEventListener
  6000. */;
  6001. _proto.off = function off(type, listener, options) {
  6002. if (type) {
  6003. this.removeEventListener(type, listener, options);
  6004. } else {
  6005. // remove all listeners
  6006. this.removeAllEventListeners();
  6007. }
  6008. return this;
  6009. };
  6010. _proto.removeAllEventListeners = function removeAllEventListeners() {
  6011. this.emitter.removeAllListeners();
  6012. };
  6013. _proto.removeEventListener = function removeEventListener(type, listener, options) {
  6014. var _listener;
  6015. var capture = util.isBoolean(options) && options || util.isObject(options) && options.capture;
  6016. var context = isFunction(listener) ? undefined : listener;
  6017. type = capture ? type + "capture" : type;
  6018. listener = isFunction(listener) ? listener : (_listener = listener) === null || _listener === void 0 ? void 0 : _listener.handleEvent;
  6019. this.emitter.off(type, listener, context);
  6020. return this;
  6021. }
  6022. /**
  6023. * @deprecated
  6024. * @alias dispatchEvent
  6025. */
  6026. // eslint-disable-next-line @typescript-eslint/ban-types
  6027. ;
  6028. _proto.emit = function emit(eventName, object) {
  6029. this.dispatchEvent(new CustomEvent(eventName, object));
  6030. }
  6031. /**
  6032. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
  6033. */;
  6034. _proto.dispatchEvent = function dispatchEvent(e, skipPropagate) {
  6035. if (skipPropagate === void 0) {
  6036. skipPropagate = false;
  6037. }
  6038. if (!isFederatedEvent(e)) {
  6039. throw new Error('DisplayObject cannot propagate events outside of the Federated Events API');
  6040. }
  6041. // should account for Element / Document / Canvas
  6042. var canvas;
  6043. // @ts-ignore
  6044. if (this.document) {
  6045. canvas = this;
  6046. // @ts-ignore
  6047. } else if (this.defaultView) {
  6048. canvas = this.defaultView;
  6049. } else {
  6050. var _this$ownerDocument;
  6051. canvas = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView;
  6052. }
  6053. // assign event manager
  6054. if (canvas) {
  6055. var _e$manager;
  6056. e.manager = canvas.getEventService() || null;
  6057. if (!e.manager) {
  6058. return false;
  6059. }
  6060. e.defaultPrevented = false;
  6061. e.path = [];
  6062. if (!skipPropagate) {
  6063. e.target = this;
  6064. }
  6065. (_e$manager = e.manager) === null || _e$manager === void 0 ? void 0 : _e$manager.dispatchEvent(e, e.type, skipPropagate);
  6066. }
  6067. return !e.defaultPrevented;
  6068. };
  6069. return EventTarget;
  6070. }();
  6071. /**
  6072. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node
  6073. */
  6074. var Node = /*#__PURE__*/function (_EventTarget) {
  6075. _inheritsLoose(Node, _EventTarget);
  6076. function Node() {
  6077. var _this;
  6078. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  6079. args[_key] = arguments[_key];
  6080. }
  6081. _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
  6082. _this.shadow = false;
  6083. /**
  6084. * points to canvas.document
  6085. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument
  6086. */
  6087. _this.ownerDocument = null;
  6088. /**
  6089. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isConnected
  6090. * @example
  6091. circle.isConnected; // false
  6092. canvas.appendChild(circle);
  6093. circle.isConnected; // true
  6094. */
  6095. _this.isConnected = false;
  6096. /**
  6097. * Returns node's node document's document base URL.
  6098. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node
  6099. */
  6100. _this.baseURI = '';
  6101. /**
  6102. * Returns the children.
  6103. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
  6104. */
  6105. _this.childNodes = [];
  6106. /**
  6107. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
  6108. */
  6109. _this.nodeType = 0;
  6110. /**
  6111. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeName
  6112. */
  6113. _this.nodeName = '';
  6114. /**
  6115. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeValue
  6116. */
  6117. _this.nodeValue = null;
  6118. /**
  6119. * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode
  6120. */
  6121. _this.parentNode = null;
  6122. return _this;
  6123. }
  6124. Node.isNode = function isNode(target) {
  6125. return !!target.childNodes;
  6126. };
  6127. var _proto = Node.prototype;
  6128. /**
  6129. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/getRootNode
  6130. */
  6131. _proto.getRootNode = function getRootNode(opts) {
  6132. if (opts === void 0) {
  6133. opts = {};
  6134. }
  6135. if (this.parentNode) {
  6136. return this.parentNode.getRootNode(opts);
  6137. }
  6138. if (opts.composed && this.host) {
  6139. return this.host.getRootNode(opts);
  6140. }
  6141. return this;
  6142. };
  6143. _proto.hasChildNodes = function hasChildNodes() {
  6144. return this.childNodes.length > 0;
  6145. };
  6146. _proto.isDefaultNamespace = function isDefaultNamespace(namespace) {
  6147. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6148. };
  6149. _proto.lookupNamespaceURI = function lookupNamespaceURI(prefix) {
  6150. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6151. };
  6152. _proto.lookupPrefix = function lookupPrefix(namespace) {
  6153. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6154. };
  6155. _proto.normalize = function normalize() {
  6156. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6157. }
  6158. /**
  6159. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isEqualNode
  6160. */;
  6161. _proto.isEqualNode = function isEqualNode(otherNode) {
  6162. // TODO: compare 2 nodes, not sameness
  6163. return this === otherNode;
  6164. };
  6165. _proto.isSameNode = function isSameNode(otherNode) {
  6166. return this.isEqualNode(otherNode);
  6167. };
  6168. /**
  6169. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
  6170. * @see https://github.com/b-fuze/deno-dom/blob/master/src/dom/node.ts#L338
  6171. */
  6172. _proto.compareDocumentPosition = function compareDocumentPosition(other) {
  6173. if (other === this) {
  6174. // same node
  6175. return 0;
  6176. }
  6177. // if (!(other instanceof Node)) {
  6178. // throw new TypeError(
  6179. // 'Node.compareDocumentPosition: Argument 1 does not implement interface Node.',
  6180. // );
  6181. // }
  6182. var node1Root = other;
  6183. // eslint-disable-next-line @typescript-eslint/no-this-alias
  6184. var node2Root = this;
  6185. var node1Hierarchy = [node1Root];
  6186. var node2Hierarchy = [node2Root];
  6187. while ((_node1Root$parentNode = node1Root.parentNode) !== null && _node1Root$parentNode !== void 0 ? _node1Root$parentNode : node2Root.parentNode) {
  6188. var _node1Root$parentNode;
  6189. node1Root = node1Root.parentNode ? (node1Hierarchy.push(node1Root.parentNode), node1Root.parentNode) : node1Root;
  6190. node2Root = node2Root.parentNode ? (node2Hierarchy.push(node2Root.parentNode), node2Root.parentNode) : node2Root;
  6191. }
  6192. // Check if they don't share the same root node
  6193. if (node1Root !== node2Root) {
  6194. return Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | Node.DOCUMENT_POSITION_PRECEDING;
  6195. }
  6196. var longerHierarchy = node1Hierarchy.length > node2Hierarchy.length ? node1Hierarchy : node2Hierarchy;
  6197. var shorterHierarchy = longerHierarchy === node1Hierarchy ? node2Hierarchy : node1Hierarchy;
  6198. // Check if either is a container of the other
  6199. if (longerHierarchy[longerHierarchy.length - shorterHierarchy.length] === shorterHierarchy[0]) {
  6200. return longerHierarchy === node1Hierarchy ?
  6201. // other is a child of this
  6202. Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING :
  6203. // this is a child of other
  6204. Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING;
  6205. }
  6206. // Find their first common ancestor and see whether they
  6207. // are preceding or following
  6208. var longerStart = longerHierarchy.length - shorterHierarchy.length;
  6209. for (var i = shorterHierarchy.length - 1; i >= 0; i--) {
  6210. var shorterHierarchyNode = shorterHierarchy[i];
  6211. var longerHierarchyNode = longerHierarchy[longerStart + i];
  6212. // We found the first common ancestor
  6213. if (longerHierarchyNode !== shorterHierarchyNode) {
  6214. var siblings = shorterHierarchyNode.parentNode.childNodes;
  6215. if (siblings.indexOf(shorterHierarchyNode) < siblings.indexOf(longerHierarchyNode)) {
  6216. // Shorter is before longer
  6217. if (shorterHierarchy === node1Hierarchy) {
  6218. // Other is before this
  6219. return Node.DOCUMENT_POSITION_PRECEDING;
  6220. } else {
  6221. // This is before other
  6222. return Node.DOCUMENT_POSITION_FOLLOWING;
  6223. }
  6224. } else {
  6225. // Longer is before shorter
  6226. if (longerHierarchy === node1Hierarchy) {
  6227. // Other is before this
  6228. return Node.DOCUMENT_POSITION_PRECEDING;
  6229. } else {
  6230. // Other is after this
  6231. return Node.DOCUMENT_POSITION_FOLLOWING;
  6232. }
  6233. }
  6234. }
  6235. }
  6236. return Node.DOCUMENT_POSITION_FOLLOWING;
  6237. }
  6238. /**
  6239. * @deprecated
  6240. * @alias contains
  6241. */;
  6242. _proto.contain = function contain(other) {
  6243. return this.contains(other);
  6244. };
  6245. _proto.contains = function contains(other) {
  6246. // the node itself, one of its direct children
  6247. var tmp = other;
  6248. // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
  6249. while (tmp && this !== tmp) {
  6250. tmp = tmp.parentNode;
  6251. }
  6252. return !!tmp;
  6253. };
  6254. _proto.getAncestor = function getAncestor(n) {
  6255. // eslint-disable-next-line @typescript-eslint/no-this-alias
  6256. var temp = this;
  6257. while (n > 0 && temp) {
  6258. temp = temp.parentNode;
  6259. n--;
  6260. }
  6261. return temp;
  6262. };
  6263. _proto.forEach = function forEach(callback, assigned) {
  6264. if (assigned === void 0) {
  6265. assigned = false;
  6266. }
  6267. if (!callback(this)) {
  6268. (assigned ? this.childNodes.slice() : this.childNodes).forEach(function (child) {
  6269. child.forEach(callback);
  6270. });
  6271. }
  6272. };
  6273. _createClass(Node, [{
  6274. key: "textContent",
  6275. get:
  6276. /**
  6277. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent
  6278. */
  6279. function get() {
  6280. var out = '';
  6281. if (this.nodeName === exports.Shape.TEXT) {
  6282. // @ts-ignore
  6283. out += this.style.text;
  6284. }
  6285. for (var _iterator = _createForOfIteratorHelperLoose(this.childNodes), _step; !(_step = _iterator()).done;) {
  6286. var child = _step.value;
  6287. if (child.nodeName === exports.Shape.TEXT) {
  6288. out += child.nodeValue;
  6289. } else {
  6290. out += child.textContent;
  6291. }
  6292. }
  6293. return out;
  6294. },
  6295. set: function set(content) {
  6296. var _this2 = this;
  6297. // remove all children
  6298. this.childNodes.slice().forEach(function (child) {
  6299. _this2.removeChild(child);
  6300. });
  6301. if (this.nodeName === exports.Shape.TEXT) {
  6302. // @ts-ignore
  6303. this.style.text = "" + content;
  6304. }
  6305. }
  6306. }, {
  6307. key: "parent",
  6308. get:
  6309. /**
  6310. * @deprecated
  6311. * @alias parentNode
  6312. */
  6313. function get() {
  6314. return this.parentNode;
  6315. }
  6316. }, {
  6317. key: "parentElement",
  6318. get: function get() {
  6319. return null;
  6320. }
  6321. }, {
  6322. key: "nextSibling",
  6323. get: function get() {
  6324. return null;
  6325. }
  6326. }, {
  6327. key: "previousSibling",
  6328. get: function get() {
  6329. return null;
  6330. }
  6331. }, {
  6332. key: "firstChild",
  6333. get: function get() {
  6334. return this.childNodes.length > 0 ? this.childNodes[0] : null;
  6335. }
  6336. }, {
  6337. key: "lastChild",
  6338. get: function get() {
  6339. return this.childNodes.length > 0 ? this.childNodes[this.childNodes.length - 1] : null;
  6340. }
  6341. }]);
  6342. return Node;
  6343. }(EventTarget);
  6344. /**
  6345. * Both nodes are in different documents or different trees in the same document.
  6346. */
  6347. Node.DOCUMENT_POSITION_DISCONNECTED = 1;
  6348. /**
  6349. * otherNode precedes the node in either a pre-order depth-first traversal
  6350. * of a tree containing both (e.g., as an ancestor or previous sibling or a descendant of a previous sibling or previous sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
  6351. */
  6352. Node.DOCUMENT_POSITION_PRECEDING = 2;
  6353. /**
  6354. * otherNode follows the node in either a pre-order depth-first traversal of a tree containing both (e.g., as a descendant or following sibling or a descendant of a following sibling or following sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
  6355. */
  6356. Node.DOCUMENT_POSITION_FOLLOWING = 4;
  6357. /**
  6358. * otherNode is an ancestor of the node.
  6359. */
  6360. Node.DOCUMENT_POSITION_CONTAINS = 8;
  6361. /**
  6362. * otherNode is a descendant of the node.
  6363. */
  6364. Node.DOCUMENT_POSITION_CONTAINED_BY = 16;
  6365. /**
  6366. * The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable.
  6367. */
  6368. Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
  6369. /**
  6370. * the entry of DOM tree
  6371. * Document -> Node -> EventTarget
  6372. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
  6373. */
  6374. var Document = /*#__PURE__*/function (_Node) {
  6375. _inheritsLoose(Document, _Node);
  6376. function Document() {
  6377. var _this;
  6378. _this = _Node.call(this) || this;
  6379. /**
  6380. * only document has defaultView, points to canvas,
  6381. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView
  6382. */
  6383. _this.defaultView = null;
  6384. /**
  6385. * the root element of document, eg. <html>
  6386. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement
  6387. */
  6388. _this.documentElement = void 0;
  6389. /**
  6390. * document.timeline in WAAPI
  6391. */
  6392. _this.timeline = void 0;
  6393. _this.ownerDocument = null;
  6394. _this.nodeName = 'document';
  6395. // create timeline
  6396. try {
  6397. _this.timeline = new runtime.AnimationTimeline(_assertThisInitialized(_this));
  6398. } catch (e) {}
  6399. /**
  6400. * for inherited properties, the initial value is used on the root element only,
  6401. * as long as no specified value is supplied.
  6402. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value
  6403. */
  6404. var initialStyle = {};
  6405. BUILT_IN_PROPERTIES.forEach(function (_ref) {
  6406. var n = _ref.n,
  6407. inh = _ref.inh,
  6408. d = _ref.d;
  6409. if (inh && d) {
  6410. initialStyle[n] = isFunction(d) ? d(exports.Shape.GROUP) : d;
  6411. }
  6412. });
  6413. // like <html> in DOM tree
  6414. _this.documentElement = new Group({
  6415. id: 'g-root',
  6416. style: initialStyle
  6417. });
  6418. _this.documentElement.ownerDocument = _assertThisInitialized(_this);
  6419. _this.documentElement.parentNode = _assertThisInitialized(_this);
  6420. _this.childNodes = [_this.documentElement];
  6421. return _this;
  6422. }
  6423. var _proto = Document.prototype;
  6424. /**
  6425. * @example const circle = document.createElement('circle', { style: { r: 10 } });
  6426. */
  6427. _proto.createElement = function createElement(tagName, options) {
  6428. // @observablehq/plot will create <svg>
  6429. if (tagName === 'svg') {
  6430. return this.documentElement;
  6431. }
  6432. // d3 will use <tspan>
  6433. var clazz = this.defaultView.customElements.get(tagName);
  6434. if (!clazz) {
  6435. console.warn('Unsupported tagName: ', tagName);
  6436. clazz = tagName === 'tspan' ? Text : Group;
  6437. }
  6438. var shape = new clazz(options);
  6439. shape.ownerDocument = this;
  6440. return shape;
  6441. };
  6442. _proto.createElementNS = function createElementNS(namespaceURI, tagName, options) {
  6443. return this.createElement(tagName, options);
  6444. };
  6445. _proto.cloneNode = function cloneNode(deep) {
  6446. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6447. };
  6448. _proto.destroy = function destroy() {
  6449. try {
  6450. this.documentElement.destroyChildren();
  6451. this.timeline.destroy();
  6452. } catch (e) {}
  6453. }
  6454. /**
  6455. * Picking 2D graphics with RBush based on BBox, fast but inaccurate.
  6456. */;
  6457. _proto.elementsFromBBox = function elementsFromBBox(minX, minY, maxX, maxY) {
  6458. var rBush = this.defaultView.context.rBushRoot;
  6459. var rBushNodes = rBush.search({
  6460. minX: minX,
  6461. minY: minY,
  6462. maxX: maxX,
  6463. maxY: maxY
  6464. });
  6465. var hitTestList = [];
  6466. rBushNodes.forEach(function (_ref2) {
  6467. var displayObject = _ref2.displayObject;
  6468. var pointerEvents = displayObject.parsedStyle.pointerEvents;
  6469. // account for `visibility`
  6470. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
  6471. var isVisibilityAffected = ['auto', 'visiblepainted', 'visiblefill', 'visiblestroke', 'visible'].includes(pointerEvents);
  6472. if ((!isVisibilityAffected || isVisibilityAffected && displayObject.isVisible()) && !displayObject.isCulled() && displayObject.isInteractive()) {
  6473. hitTestList.push(displayObject);
  6474. }
  6475. });
  6476. // find group with max z-index
  6477. hitTestList.sort(function (a, b) {
  6478. return b.sortable.renderOrder - a.sortable.renderOrder;
  6479. });
  6480. return hitTestList;
  6481. };
  6482. _proto.elementFromPointSync = function elementFromPointSync(x, y) {
  6483. var _this$defaultView$can = this.defaultView.canvas2Viewport({
  6484. x: x,
  6485. y: y
  6486. }),
  6487. viewportX = _this$defaultView$can.x,
  6488. viewportY = _this$defaultView$can.y;
  6489. var _this$defaultView$get = this.defaultView.getConfig(),
  6490. width = _this$defaultView$get.width,
  6491. height = _this$defaultView$get.height;
  6492. // outside canvas' viewport
  6493. if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
  6494. return null;
  6495. }
  6496. var _this$defaultView$vie = this.defaultView.viewport2Client({
  6497. x: viewportX,
  6498. y: viewportY
  6499. }),
  6500. clientX = _this$defaultView$vie.x,
  6501. clientY = _this$defaultView$vie.y;
  6502. var _this$defaultView$get2 = this.defaultView.getRenderingService().hooks.pickSync.call({
  6503. topmost: true,
  6504. position: {
  6505. x: x,
  6506. y: y,
  6507. viewportX: viewportX,
  6508. viewportY: viewportY,
  6509. clientX: clientX,
  6510. clientY: clientY
  6511. },
  6512. picked: []
  6513. }),
  6514. picked = _this$defaultView$get2.picked;
  6515. return picked && picked[0] || this.documentElement;
  6516. }
  6517. /**
  6518. * Do picking with API instead of triggering interactive events.
  6519. *
  6520. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementFromPoint
  6521. */;
  6522. _proto.elementFromPoint =
  6523. /*#__PURE__*/
  6524. function () {
  6525. var _elementFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(x, y) {
  6526. var _this$defaultView$can2, viewportX, viewportY, _this$defaultView$get3, width, height, _this$defaultView$vie2, clientX, clientY, _yield$this$defaultVi, picked;
  6527. return _regeneratorRuntime().wrap(function _callee$(_context) {
  6528. while (1) switch (_context.prev = _context.next) {
  6529. case 0:
  6530. _this$defaultView$can2 = this.defaultView.canvas2Viewport({
  6531. x: x,
  6532. y: y
  6533. }), viewportX = _this$defaultView$can2.x, viewportY = _this$defaultView$can2.y;
  6534. _this$defaultView$get3 = this.defaultView.getConfig(), width = _this$defaultView$get3.width, height = _this$defaultView$get3.height; // outside canvas' viewport
  6535. if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
  6536. _context.next = 4;
  6537. break;
  6538. }
  6539. return _context.abrupt("return", null);
  6540. case 4:
  6541. _this$defaultView$vie2 = this.defaultView.viewport2Client({
  6542. x: viewportX,
  6543. y: viewportY
  6544. }), clientX = _this$defaultView$vie2.x, clientY = _this$defaultView$vie2.y;
  6545. _context.next = 7;
  6546. return this.defaultView.getRenderingService().hooks.pick.promise({
  6547. topmost: true,
  6548. position: {
  6549. x: x,
  6550. y: y,
  6551. viewportX: viewportX,
  6552. viewportY: viewportY,
  6553. clientX: clientX,
  6554. clientY: clientY
  6555. },
  6556. picked: []
  6557. });
  6558. case 7:
  6559. _yield$this$defaultVi = _context.sent;
  6560. picked = _yield$this$defaultVi.picked;
  6561. return _context.abrupt("return", picked && picked[0] || this.documentElement);
  6562. case 10:
  6563. case "end":
  6564. return _context.stop();
  6565. }
  6566. }, _callee, this);
  6567. }));
  6568. function elementFromPoint(_x, _x2) {
  6569. return _elementFromPoint.apply(this, arguments);
  6570. }
  6571. return elementFromPoint;
  6572. }();
  6573. _proto.elementsFromPointSync = function elementsFromPointSync(x, y) {
  6574. var _this$defaultView$can3 = this.defaultView.canvas2Viewport({
  6575. x: x,
  6576. y: y
  6577. }),
  6578. viewportX = _this$defaultView$can3.x,
  6579. viewportY = _this$defaultView$can3.y;
  6580. var _this$defaultView$get4 = this.defaultView.getConfig(),
  6581. width = _this$defaultView$get4.width,
  6582. height = _this$defaultView$get4.height;
  6583. // outside canvas' viewport
  6584. if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
  6585. return [];
  6586. }
  6587. var _this$defaultView$vie3 = this.defaultView.viewport2Client({
  6588. x: viewportX,
  6589. y: viewportY
  6590. }),
  6591. clientX = _this$defaultView$vie3.x,
  6592. clientY = _this$defaultView$vie3.y;
  6593. var _this$defaultView$get5 = this.defaultView.getRenderingService().hooks.pickSync.call({
  6594. topmost: false,
  6595. position: {
  6596. x: x,
  6597. y: y,
  6598. viewportX: viewportX,
  6599. viewportY: viewportY,
  6600. clientX: clientX,
  6601. clientY: clientY
  6602. },
  6603. picked: []
  6604. }),
  6605. picked = _this$defaultView$get5.picked;
  6606. if (picked[picked.length - 1] !== this.documentElement) {
  6607. picked.push(this.documentElement);
  6608. }
  6609. return picked;
  6610. }
  6611. /**
  6612. * Do picking with API instead of triggering interactive events.
  6613. *
  6614. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementsFromPoint
  6615. */;
  6616. _proto.elementsFromPoint =
  6617. /*#__PURE__*/
  6618. function () {
  6619. var _elementsFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(x, y) {
  6620. var _this$defaultView$can4, viewportX, viewportY, _this$defaultView$get6, width, height, _this$defaultView$vie4, clientX, clientY, _yield$this$defaultVi2, picked;
  6621. return _regeneratorRuntime().wrap(function _callee2$(_context2) {
  6622. while (1) switch (_context2.prev = _context2.next) {
  6623. case 0:
  6624. _this$defaultView$can4 = this.defaultView.canvas2Viewport({
  6625. x: x,
  6626. y: y
  6627. }), viewportX = _this$defaultView$can4.x, viewportY = _this$defaultView$can4.y;
  6628. _this$defaultView$get6 = this.defaultView.getConfig(), width = _this$defaultView$get6.width, height = _this$defaultView$get6.height; // outside canvas' viewport
  6629. if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
  6630. _context2.next = 4;
  6631. break;
  6632. }
  6633. return _context2.abrupt("return", []);
  6634. case 4:
  6635. _this$defaultView$vie4 = this.defaultView.viewport2Client({
  6636. x: viewportX,
  6637. y: viewportY
  6638. }), clientX = _this$defaultView$vie4.x, clientY = _this$defaultView$vie4.y;
  6639. _context2.next = 7;
  6640. return this.defaultView.getRenderingService().hooks.pick.promise({
  6641. topmost: false,
  6642. position: {
  6643. x: x,
  6644. y: y,
  6645. viewportX: viewportX,
  6646. viewportY: viewportY,
  6647. clientX: clientX,
  6648. clientY: clientY
  6649. },
  6650. picked: []
  6651. });
  6652. case 7:
  6653. _yield$this$defaultVi2 = _context2.sent;
  6654. picked = _yield$this$defaultVi2.picked;
  6655. if (picked[picked.length - 1] !== this.documentElement) {
  6656. picked.push(this.documentElement);
  6657. }
  6658. return _context2.abrupt("return", picked);
  6659. case 11:
  6660. case "end":
  6661. return _context2.stop();
  6662. }
  6663. }, _callee2, this);
  6664. }));
  6665. function elementsFromPoint(_x3, _x4) {
  6666. return _elementsFromPoint.apply(this, arguments);
  6667. }
  6668. return elementsFromPoint;
  6669. }()
  6670. /**
  6671. * eg. Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
  6672. */
  6673. ;
  6674. _proto.appendChild = function appendChild(newChild, index) {
  6675. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6676. };
  6677. _proto.insertBefore = function insertBefore(newChild, refChild) {
  6678. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6679. };
  6680. _proto.removeChild = function removeChild(oldChild, destroy) {
  6681. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6682. };
  6683. _proto.replaceChild = function replaceChild(newChild, oldChild, destroy) {
  6684. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6685. };
  6686. _proto.append = function append() {
  6687. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6688. };
  6689. _proto.prepend = function prepend() {
  6690. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6691. }
  6692. /**
  6693. * Execute query on documentElement.
  6694. */;
  6695. _proto.getElementById = function getElementById(id) {
  6696. return this.documentElement.getElementById(id);
  6697. };
  6698. _proto.getElementsByName = function getElementsByName(name) {
  6699. return this.documentElement.getElementsByName(name);
  6700. };
  6701. _proto.getElementsByTagName = function getElementsByTagName(tagName) {
  6702. return this.documentElement.getElementsByTagName(tagName);
  6703. };
  6704. _proto.getElementsByClassName = function getElementsByClassName(className) {
  6705. return this.documentElement.getElementsByClassName(className);
  6706. };
  6707. _proto.querySelector = function querySelector(selectors) {
  6708. return this.documentElement.querySelector(selectors);
  6709. };
  6710. _proto.querySelectorAll = function querySelectorAll(selectors) {
  6711. return this.documentElement.querySelectorAll(selectors);
  6712. };
  6713. _proto.find = function find(filter) {
  6714. return this.documentElement.find(filter);
  6715. };
  6716. _proto.findAll = function findAll(filter) {
  6717. return this.documentElement.findAll(filter);
  6718. };
  6719. _createClass(Document, [{
  6720. key: "children",
  6721. get: function get() {
  6722. return this.childNodes;
  6723. }
  6724. }, {
  6725. key: "childElementCount",
  6726. get: function get() {
  6727. return this.childNodes.length;
  6728. }
  6729. }, {
  6730. key: "firstElementChild",
  6731. get: function get() {
  6732. return this.firstChild;
  6733. }
  6734. }, {
  6735. key: "lastElementChild",
  6736. get: function get() {
  6737. return this.lastChild;
  6738. }
  6739. }]);
  6740. return Document;
  6741. }(Node);
  6742. /**
  6743. * built-in events for element
  6744. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
  6745. *
  6746. * TODO: use MutationObserver instead
  6747. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
  6748. */
  6749. (function (ElementEvent) {
  6750. ElementEvent["REPARENT"] = "reparent";
  6751. ElementEvent["DESTROY"] = "destroy";
  6752. /**
  6753. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified
  6754. */
  6755. ElementEvent["ATTR_MODIFIED"] = "DOMAttrModified";
  6756. /**
  6757. * it has been inserted
  6758. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted
  6759. */
  6760. ElementEvent["INSERTED"] = "DOMNodeInserted";
  6761. /**
  6762. * it is being removed
  6763. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved
  6764. */
  6765. ElementEvent["REMOVED"] = "removed";
  6766. /**
  6767. * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnodeinsertedintodocument
  6768. */
  6769. ElementEvent["MOUNTED"] = "DOMNodeInsertedIntoDocument";
  6770. /**
  6771. * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnoderemovedfromdocument
  6772. */
  6773. ElementEvent["UNMOUNTED"] = "DOMNodeRemovedFromDocument";
  6774. ElementEvent["BOUNDS_CHANGED"] = "bounds-changed";
  6775. ElementEvent["CULLED"] = "culled";
  6776. })(exports.ElementEvent || (exports.ElementEvent = {}));
  6777. var MutationEvent = /*#__PURE__*/function (_FederatedEvent) {
  6778. _inheritsLoose(MutationEvent, _FederatedEvent);
  6779. function MutationEvent(typeArg, relatedNode, prevValue, newValue, attrName, attrChange, prevParsedValue, newParsedValue) {
  6780. var _this;
  6781. _this = _FederatedEvent.call(this, null) || this;
  6782. _this.relatedNode = void 0;
  6783. _this.prevValue = void 0;
  6784. _this.newValue = void 0;
  6785. _this.attrName = void 0;
  6786. _this.attrChange = void 0;
  6787. _this.prevParsedValue = void 0;
  6788. _this.newParsedValue = void 0;
  6789. _this.relatedNode = relatedNode;
  6790. _this.prevValue = prevValue;
  6791. _this.newValue = newValue;
  6792. _this.attrName = attrName;
  6793. _this.attrChange = attrChange;
  6794. _this.prevParsedValue = prevParsedValue;
  6795. _this.newParsedValue = newParsedValue;
  6796. _this.type = typeArg;
  6797. return _this;
  6798. }
  6799. return MutationEvent;
  6800. }(FederatedEvent);
  6801. MutationEvent.ADDITION = 2;
  6802. MutationEvent.MODIFICATION = 1;
  6803. MutationEvent.REMOVAL = 3;
  6804. var entityCounter = 0;
  6805. function resetEntityCounter() {
  6806. entityCounter = 0;
  6807. }
  6808. var insertedEvent = new MutationEvent(exports.ElementEvent.INSERTED, null, '', '', '', 0, '', '');
  6809. var removedEvent = new MutationEvent(exports.ElementEvent.REMOVED, null, '', '', '', 0, '', '');
  6810. var destroyEvent = new CustomEvent(exports.ElementEvent.DESTROY);
  6811. /**
  6812. * Has following capabilities:
  6813. * * Node insert/remove, eg. appendChild, removeChild, remove...
  6814. * * Query eg. querySelector getElementById...
  6815. * * Animation
  6816. */
  6817. var Element = /*#__PURE__*/function (_Node) {
  6818. _inheritsLoose(Element, _Node);
  6819. function Element() {
  6820. var _this;
  6821. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  6822. args[_key] = arguments[_key];
  6823. }
  6824. _this = _Node.call.apply(_Node, [this].concat(args)) || this;
  6825. /**
  6826. * Unique id.
  6827. */
  6828. _this.entity = entityCounter++;
  6829. _this.renderable = {
  6830. bounds: undefined,
  6831. boundsDirty: true,
  6832. renderBounds: undefined,
  6833. renderBoundsDirty: true,
  6834. dirtyRenderBounds: undefined,
  6835. dirty: false,
  6836. proxyNodeName: undefined
  6837. };
  6838. _this.cullable = {
  6839. strategy: exports.Strategy.Standard,
  6840. visibilityPlaneMask: -1,
  6841. visible: true,
  6842. enable: true
  6843. };
  6844. _this.transformable = {
  6845. dirtyFlag: false,
  6846. localDirtyFlag: false,
  6847. frozen: false,
  6848. localPosition: [0, 0, 0],
  6849. localRotation: [0, 0, 0, 1],
  6850. localScale: [1, 1, 1],
  6851. localTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
  6852. localSkew: [0, 0],
  6853. position: [0, 0, 0],
  6854. rotation: [0, 0, 0, 1],
  6855. scaling: [1, 1, 1],
  6856. worldTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
  6857. origin: [0, 0, 0]
  6858. };
  6859. _this.sortable = {
  6860. dirty: false,
  6861. sorted: undefined,
  6862. renderOrder: 0,
  6863. dirtyChildren: [],
  6864. dirtyReason: undefined
  6865. };
  6866. _this.geometry = {
  6867. contentBounds: undefined,
  6868. renderBounds: undefined
  6869. };
  6870. _this.rBushNode = {
  6871. aabb: undefined
  6872. };
  6873. /**
  6874. * used with `getElementById()`
  6875. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/id
  6876. */
  6877. _this.id = void 0;
  6878. /**
  6879. * used in `getElementsByName`
  6880. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
  6881. */
  6882. _this.name = void 0;
  6883. /**
  6884. * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/namespaceURI
  6885. */
  6886. _this.namespaceURI = 'g';
  6887. _this.scrollLeft = 0;
  6888. _this.scrollTop = 0;
  6889. /**
  6890. * We don't support border now
  6891. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
  6892. */
  6893. _this.clientTop = 0;
  6894. _this.clientLeft = 0;
  6895. /**
  6896. * is destroyed or not
  6897. */
  6898. _this.destroyed = false;
  6899. /**
  6900. * compatible with `style`
  6901. * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
  6902. */
  6903. _this.style = {};
  6904. _this.computedStyle = runtime.enableCSSParsing ? {
  6905. anchor: unsetKeywordValue,
  6906. opacity: unsetKeywordValue,
  6907. fillOpacity: unsetKeywordValue,
  6908. strokeOpacity: unsetKeywordValue,
  6909. fill: unsetKeywordValue,
  6910. stroke: unsetKeywordValue,
  6911. transform: unsetKeywordValue,
  6912. transformOrigin: unsetKeywordValue,
  6913. visibility: unsetKeywordValue,
  6914. pointerEvents: unsetKeywordValue,
  6915. lineWidth: unsetKeywordValue,
  6916. lineCap: unsetKeywordValue,
  6917. lineJoin: unsetKeywordValue,
  6918. increasedLineWidthForHitTesting: unsetKeywordValue,
  6919. fontSize: unsetKeywordValue,
  6920. fontFamily: unsetKeywordValue,
  6921. fontStyle: unsetKeywordValue,
  6922. fontWeight: unsetKeywordValue,
  6923. fontVariant: unsetKeywordValue,
  6924. textAlign: unsetKeywordValue,
  6925. textBaseline: unsetKeywordValue,
  6926. textTransform: unsetKeywordValue,
  6927. zIndex: unsetKeywordValue,
  6928. filter: unsetKeywordValue,
  6929. shadowType: unsetKeywordValue
  6930. } : null;
  6931. /**
  6932. * Renderers will use these used values.
  6933. */
  6934. _this.parsedStyle = {
  6935. // opacity: '',
  6936. // fillOpacity: '',
  6937. // strokeOpacity: '',
  6938. // transformOrigin: '',
  6939. // visibility: '',
  6940. // pointerEvents: '',
  6941. // lineWidth: '',
  6942. // lineCap: '',
  6943. // lineJoin: '',
  6944. // increasedLineWidthForHitTesting: '',
  6945. // fontSize: '',
  6946. // fontFamily: '',
  6947. // fontStyle: '',
  6948. // fontWeight: '',
  6949. // fontVariant: '',
  6950. // textAlign: '',
  6951. // textBaseline: '',
  6952. // textTransform: '',
  6953. };
  6954. /**
  6955. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
  6956. */
  6957. _this.attributes = {};
  6958. return _this;
  6959. }
  6960. Element.isElement = function isElement(target) {
  6961. return !!target.getAttribute;
  6962. };
  6963. var _proto = Element.prototype;
  6964. _proto.cloneNode = function cloneNode(deep) {
  6965. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6966. };
  6967. _proto.appendChild = function appendChild(child, index) {
  6968. var _this$ownerDocument;
  6969. if (child.destroyed) {
  6970. throw new Error(ERROR_MSG_APPEND_DESTROYED_ELEMENT);
  6971. }
  6972. runtime.sceneGraphService.attach(child, this, index);
  6973. if ((_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView) {
  6974. this.ownerDocument.defaultView.mountChildren(child);
  6975. }
  6976. insertedEvent.relatedNode = this;
  6977. child.dispatchEvent(insertedEvent);
  6978. return child;
  6979. };
  6980. _proto.insertBefore = function insertBefore(newChild, refChild) {
  6981. if (!refChild) {
  6982. this.appendChild(newChild);
  6983. } else {
  6984. var index = this.childNodes.indexOf(refChild);
  6985. this.appendChild(newChild, index - 1);
  6986. }
  6987. return newChild;
  6988. };
  6989. _proto.replaceChild = function replaceChild(newChild, oldChild) {
  6990. var index = this.childNodes.indexOf(oldChild);
  6991. this.removeChild(oldChild);
  6992. this.appendChild(newChild, index);
  6993. return oldChild;
  6994. };
  6995. _proto.removeChild = function removeChild(child) {
  6996. var _child$ownerDocument;
  6997. // should emit on itself before detach
  6998. removedEvent.relatedNode = this;
  6999. child.dispatchEvent(removedEvent);
  7000. if ((_child$ownerDocument = child.ownerDocument) === null || _child$ownerDocument === void 0 ? void 0 : _child$ownerDocument.defaultView) {
  7001. child.ownerDocument.defaultView.unmountChildren(child);
  7002. }
  7003. // remove from scene graph
  7004. runtime.sceneGraphService.detach(child);
  7005. return child;
  7006. }
  7007. /**
  7008. * Remove all children which can be appended to its original parent later again.
  7009. */;
  7010. _proto.removeChildren = function removeChildren() {
  7011. for (var i = this.childNodes.length - 1; i >= 0; i--) {
  7012. var child = this.childNodes[i];
  7013. this.removeChild(child);
  7014. }
  7015. }
  7016. /**
  7017. * Recursively destroy all children which can not be appended to its original parent later again.
  7018. */;
  7019. _proto.destroyChildren = function destroyChildren() {
  7020. for (var i = this.childNodes.length - 1; i >= 0; i--) {
  7021. var child = this.childNodes[i];
  7022. if (child.childNodes.length) {
  7023. child.destroyChildren();
  7024. }
  7025. child.destroy();
  7026. }
  7027. }
  7028. /**
  7029. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
  7030. */;
  7031. _proto.matches = function matches(selector) {
  7032. return runtime.sceneGraphService.matches(selector, this);
  7033. };
  7034. _proto.getElementById = function getElementById(id) {
  7035. return runtime.sceneGraphService.querySelector("#" + id, this);
  7036. };
  7037. _proto.getElementsByName = function getElementsByName(name) {
  7038. return runtime.sceneGraphService.querySelectorAll("[name=\"" + name + "\"]", this);
  7039. };
  7040. _proto.getElementsByClassName = function getElementsByClassName(className) {
  7041. return runtime.sceneGraphService.querySelectorAll("." + className, this);
  7042. };
  7043. _proto.getElementsByTagName = function getElementsByTagName(tagName) {
  7044. return runtime.sceneGraphService.querySelectorAll(tagName, this);
  7045. };
  7046. _proto.querySelector = function querySelector(selectors) {
  7047. return runtime.sceneGraphService.querySelector(selectors, this);
  7048. };
  7049. _proto.querySelectorAll = function querySelectorAll(selectors) {
  7050. return runtime.sceneGraphService.querySelectorAll(selectors, this);
  7051. }
  7052. /**
  7053. * should traverses the element and its parents (heading toward the document root)
  7054. * until it finds a node that matches the specified CSS selector.
  7055. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
  7056. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill
  7057. */;
  7058. _proto.closest = function closest(selectors) {
  7059. var el = this;
  7060. do {
  7061. if (runtime.sceneGraphService.matches(selectors, el)) return el;
  7062. el = el.parentElement;
  7063. } while (el !== null);
  7064. return null;
  7065. }
  7066. /**
  7067. * search in scene group, but should not include itself
  7068. */;
  7069. _proto.find = function find(filter) {
  7070. var _this2 = this;
  7071. var target = null;
  7072. this.forEach(function (object) {
  7073. if (object !== _this2 && filter(object)) {
  7074. target = object;
  7075. return true;
  7076. }
  7077. return false;
  7078. });
  7079. return target;
  7080. };
  7081. _proto.findAll = function findAll(filter) {
  7082. var _this3 = this;
  7083. var objects = [];
  7084. this.forEach(function (object) {
  7085. if (object !== _this3 && filter(object)) {
  7086. objects.push(object);
  7087. }
  7088. });
  7089. return objects;
  7090. }
  7091. /**
  7092. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/after
  7093. */;
  7094. _proto.after = function after() {
  7095. var _this4 = this;
  7096. if (this.parentNode) {
  7097. var index = this.parentNode.childNodes.indexOf(this);
  7098. for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  7099. nodes[_key2] = arguments[_key2];
  7100. }
  7101. nodes.forEach(function (node, i) {
  7102. var _this4$parentNode;
  7103. return (_this4$parentNode = _this4.parentNode) === null || _this4$parentNode === void 0 ? void 0 : _this4$parentNode.appendChild(node, index + i + 1);
  7104. });
  7105. }
  7106. }
  7107. /**
  7108. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/before
  7109. */;
  7110. _proto.before = function before() {
  7111. if (this.parentNode) {
  7112. var index = this.parentNode.childNodes.indexOf(this);
  7113. for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  7114. nodes[_key3] = arguments[_key3];
  7115. }
  7116. var first = nodes[0],
  7117. rest = nodes.slice(1);
  7118. this.parentNode.appendChild(first, index);
  7119. first.after.apply(first, rest);
  7120. }
  7121. }
  7122. /**
  7123. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceWith
  7124. */;
  7125. _proto.replaceWith = function replaceWith() {
  7126. this.after.apply(this, arguments);
  7127. this.remove();
  7128. }
  7129. /**
  7130. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/append
  7131. */;
  7132. _proto.append = function append() {
  7133. var _this5 = this;
  7134. for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  7135. nodes[_key4] = arguments[_key4];
  7136. }
  7137. nodes.forEach(function (node) {
  7138. return _this5.appendChild(node);
  7139. });
  7140. }
  7141. /**
  7142. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/prepend
  7143. */;
  7144. _proto.prepend = function prepend() {
  7145. var _this6 = this;
  7146. for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  7147. nodes[_key5] = arguments[_key5];
  7148. }
  7149. nodes.forEach(function (node, i) {
  7150. return _this6.appendChild(node, i);
  7151. });
  7152. }
  7153. /**
  7154. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceChildren
  7155. */;
  7156. _proto.replaceChildren = function replaceChildren() {
  7157. while (this.childNodes.length && this.firstChild) {
  7158. this.removeChild(this.firstChild);
  7159. }
  7160. this.append.apply(this, arguments);
  7161. }
  7162. /**
  7163. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/remove
  7164. */;
  7165. _proto.remove = function remove() {
  7166. if (this.parentNode) {
  7167. return this.parentNode.removeChild(this);
  7168. }
  7169. return this;
  7170. };
  7171. _proto.destroy = function destroy() {
  7172. // destroy itself before remove
  7173. this.dispatchEvent(destroyEvent);
  7174. // remove from scenegraph first
  7175. this.remove();
  7176. // remove event listeners
  7177. this.emitter.removeAllListeners();
  7178. this.destroyed = true;
  7179. };
  7180. _proto.getGeometryBounds = function getGeometryBounds() {
  7181. return runtime.sceneGraphService.getGeometryBounds(this);
  7182. };
  7183. _proto.getRenderBounds = function getRenderBounds() {
  7184. return runtime.sceneGraphService.getBounds(this, true);
  7185. }
  7186. /**
  7187. * get bounds in world space, account for children
  7188. */;
  7189. _proto.getBounds = function getBounds() {
  7190. return runtime.sceneGraphService.getBounds(this);
  7191. }
  7192. /**
  7193. * get bounds in local space, account for children
  7194. */;
  7195. _proto.getLocalBounds = function getLocalBounds() {
  7196. return runtime.sceneGraphService.getLocalBounds(this);
  7197. }
  7198. /**
  7199. * account for context's bounds in client space,
  7200. * but not accounting for children
  7201. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
  7202. */;
  7203. _proto.getBoundingClientRect = function getBoundingClientRect() {
  7204. return runtime.sceneGraphService.getBoundingClientRect(this);
  7205. }
  7206. /**
  7207. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getClientRects
  7208. */;
  7209. _proto.getClientRects = function getClientRects() {
  7210. return [this.getBoundingClientRect()];
  7211. };
  7212. /**
  7213. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap
  7214. * eg. circle.computedStyleMap().get('fill');
  7215. */
  7216. _proto.computedStyleMap = function computedStyleMap() {
  7217. return new Map(Object.entries(this.computedStyle));
  7218. };
  7219. /**
  7220. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
  7221. */
  7222. _proto.getAttributeNames = function getAttributeNames() {
  7223. return Object.keys(this.attributes);
  7224. }
  7225. /**
  7226. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  7227. */;
  7228. _proto.getAttribute = function getAttribute(name) {
  7229. // @see https://github.com/antvis/G/issues/1267
  7230. if (isSymbol(name)) {
  7231. return runtime.enableCSSParsing ? null : undefined;
  7232. }
  7233. var value = this.attributes[name];
  7234. if (value === undefined) {
  7235. var attributeName = formatAttributeName(name);
  7236. value = this.attributes[attributeName];
  7237. // if the given attribute does not exist, the value returned will either be null or ""
  7238. return runtime.enableCSSParsing ? util.isNil(value) ? null : value : value;
  7239. } else {
  7240. return value;
  7241. }
  7242. }
  7243. /**
  7244. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
  7245. */;
  7246. _proto.hasAttribute = function hasAttribute(qualifiedName) {
  7247. return this.getAttributeNames().includes(qualifiedName);
  7248. }
  7249. /**
  7250. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
  7251. */;
  7252. _proto.hasAttributes = function hasAttributes() {
  7253. return !!this.getAttributeNames().length;
  7254. }
  7255. /**
  7256. * should use removeAttribute() instead of setting the attribute value to null either directly or using setAttribute(). Many attributes will not behave as expected if you set them to null.
  7257. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
  7258. */;
  7259. _proto.removeAttribute = function removeAttribute(attributeName) {
  7260. this.setAttribute(attributeName, null);
  7261. delete this.attributes[attributeName];
  7262. }
  7263. /**
  7264. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
  7265. */;
  7266. _proto.setAttribute = function setAttribute(attributeName, value, force) {
  7267. this.attributes[attributeName] = value;
  7268. };
  7269. _proto.getAttributeNS = function getAttributeNS(namespace, localName) {
  7270. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7271. };
  7272. _proto.getAttributeNode = function getAttributeNode(qualifiedName) {
  7273. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7274. };
  7275. _proto.getAttributeNodeNS = function getAttributeNodeNS(namespace, localName) {
  7276. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7277. };
  7278. _proto.hasAttributeNS = function hasAttributeNS(namespace, localName) {
  7279. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7280. };
  7281. _proto.removeAttributeNS = function removeAttributeNS(namespace, localName) {
  7282. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7283. };
  7284. _proto.removeAttributeNode = function removeAttributeNode(attr) {
  7285. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7286. };
  7287. _proto.setAttributeNS = function setAttributeNS(namespace, qualifiedName, value) {
  7288. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7289. };
  7290. _proto.setAttributeNode = function setAttributeNode(attr) {
  7291. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7292. };
  7293. _proto.setAttributeNodeNS = function setAttributeNodeNS(attr) {
  7294. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7295. };
  7296. _proto.toggleAttribute = function toggleAttribute(qualifiedName, force) {
  7297. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7298. };
  7299. _createClass(Element, [{
  7300. key: "className",
  7301. get:
  7302. /**
  7303. * used in `getElementsByClassName`
  7304. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  7305. */
  7306. function get() {
  7307. // @ts-ignore
  7308. return this.getAttribute('class') || '';
  7309. },
  7310. set: function set(className) {
  7311. this.setAttribute('class', className);
  7312. }
  7313. }, {
  7314. key: "classList",
  7315. get:
  7316. /**
  7317. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
  7318. */
  7319. function get() {
  7320. return this.className.split(' ').filter(function (c) {
  7321. return c !== '';
  7322. });
  7323. }
  7324. }, {
  7325. key: "tagName",
  7326. get: function get() {
  7327. return this.nodeName;
  7328. }
  7329. }, {
  7330. key: "children",
  7331. get: function get() {
  7332. return this.childNodes;
  7333. }
  7334. }, {
  7335. key: "childElementCount",
  7336. get: function get() {
  7337. return this.childNodes.length;
  7338. }
  7339. }, {
  7340. key: "firstElementChild",
  7341. get: function get() {
  7342. return this.firstChild;
  7343. }
  7344. }, {
  7345. key: "lastElementChild",
  7346. get: function get() {
  7347. return this.lastChild;
  7348. }
  7349. }, {
  7350. key: "parentElement",
  7351. get: function get() {
  7352. return this.parentNode;
  7353. }
  7354. }, {
  7355. key: "nextSibling",
  7356. get: function get() {
  7357. if (this.parentNode) {
  7358. var index = this.parentNode.childNodes.indexOf(this);
  7359. return this.parentNode.childNodes[index + 1] || null;
  7360. }
  7361. return null;
  7362. }
  7363. }, {
  7364. key: "previousSibling",
  7365. get: function get() {
  7366. if (this.parentNode) {
  7367. var index = this.parentNode.childNodes.indexOf(this);
  7368. return this.parentNode.childNodes[index - 1] || null;
  7369. }
  7370. return null;
  7371. }
  7372. }]);
  7373. return Element;
  7374. }(Node);
  7375. var FederatedMouseEvent = /*#__PURE__*/function (_FederatedEvent) {
  7376. _inheritsLoose(FederatedMouseEvent, _FederatedEvent);
  7377. function FederatedMouseEvent() {
  7378. var _this;
  7379. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  7380. args[_key] = arguments[_key];
  7381. }
  7382. _this = _FederatedEvent.call.apply(_FederatedEvent, [this].concat(args)) || this;
  7383. /** Whether the "alt" key was pressed when this mouse event occurred. */
  7384. _this.altKey = void 0;
  7385. /** The specific button that was pressed in this mouse event. */
  7386. _this.button = void 0;
  7387. /** The button depressed when this event occurred. */
  7388. _this.buttons = void 0;
  7389. /** Whether the "control" key was pressed when this mouse event occurred. */
  7390. _this.ctrlKey = void 0;
  7391. /** Whether the "meta" key was pressed when this mouse event occurred. */
  7392. _this.metaKey = void 0;
  7393. /** This is currently not implemented in the Federated Events API. */
  7394. _this.relatedTarget = void 0;
  7395. /** Whether the "shift" key was pressed when this mouse event occurred. */
  7396. _this.shiftKey = void 0;
  7397. /**
  7398. * The coordinates of the mouse event relative to the canvas.
  7399. */
  7400. _this.client = new Point();
  7401. /**
  7402. * The movement in this pointer relative to the last `mousemove` event.
  7403. */
  7404. _this.movement = new Point();
  7405. /**
  7406. * The offset of the pointer coordinates w.r.t. target DisplayObject in world space. This is
  7407. * not supported at the moment.
  7408. */
  7409. _this.offset = new Point();
  7410. /**
  7411. * The pointer coordinates in world space.
  7412. */
  7413. _this.global = new Point();
  7414. /**
  7415. * The pointer coordinates in sceen space.
  7416. */
  7417. _this.screen = new Point();
  7418. return _this;
  7419. }
  7420. var _proto = FederatedMouseEvent.prototype;
  7421. _proto.getModifierState = function getModifierState(key) {
  7422. return 'getModifierState' in this.nativeEvent && this.nativeEvent.getModifierState(key);
  7423. };
  7424. _proto.initMouseEvent = function initMouseEvent() {
  7425. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7426. };
  7427. _createClass(FederatedMouseEvent, [{
  7428. key: "clientX",
  7429. get: function get() {
  7430. return this.client.x;
  7431. }
  7432. }, {
  7433. key: "clientY",
  7434. get: function get() {
  7435. return this.client.y;
  7436. }
  7437. }, {
  7438. key: "movementX",
  7439. get: function get() {
  7440. return this.movement.x;
  7441. }
  7442. }, {
  7443. key: "movementY",
  7444. get: function get() {
  7445. return this.movement.y;
  7446. }
  7447. }, {
  7448. key: "offsetX",
  7449. get: function get() {
  7450. return this.offset.x;
  7451. }
  7452. }, {
  7453. key: "offsetY",
  7454. get: function get() {
  7455. return this.offset.y;
  7456. }
  7457. }, {
  7458. key: "globalX",
  7459. get: function get() {
  7460. return this.global.x;
  7461. }
  7462. }, {
  7463. key: "globalY",
  7464. get: function get() {
  7465. return this.global.y;
  7466. }
  7467. }, {
  7468. key: "screenX",
  7469. get: function get() {
  7470. return this.screen.x;
  7471. }
  7472. }, {
  7473. key: "screenY",
  7474. get: function get() {
  7475. return this.screen.y;
  7476. }
  7477. }]);
  7478. return FederatedMouseEvent;
  7479. }(FederatedEvent);
  7480. var FederatedPointerEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
  7481. _inheritsLoose(FederatedPointerEvent, _FederatedMouseEvent);
  7482. function FederatedPointerEvent() {
  7483. var _this;
  7484. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  7485. args[_key] = arguments[_key];
  7486. }
  7487. _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
  7488. /**
  7489. * The unique identifier of the pointer.
  7490. *
  7491. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
  7492. */
  7493. _this.pointerId = void 0;
  7494. /**
  7495. * The width of the pointer's contact along the x-axis, measured in CSS pixels.
  7496. * radiusX of TouchEvents will be represented by this value.
  7497. *
  7498. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
  7499. */
  7500. _this.width = 0;
  7501. /**
  7502. * The height of the pointer's contact along the y-axis, measured in CSS pixels.
  7503. * radiusY of TouchEvents will be represented by this value.
  7504. *
  7505. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
  7506. */
  7507. _this.height = 0;
  7508. /**
  7509. * Indicates whether or not the pointer device that created the event is the primary pointer.
  7510. *
  7511. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
  7512. */
  7513. _this.isPrimary = false;
  7514. /**
  7515. * The type of pointer that triggered the event.
  7516. *
  7517. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
  7518. */
  7519. _this.pointerType = void 0;
  7520. /**
  7521. * Pressure applied by the pointing device during the event.
  7522. *s
  7523. * A Touch's force property will be represented by this value.
  7524. *
  7525. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
  7526. */
  7527. _this.pressure = void 0;
  7528. /**
  7529. * Barrel pressure on a stylus pointer.
  7530. *
  7531. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  7532. */
  7533. _this.tangentialPressure = void 0;
  7534. /**
  7535. * The angle, in degrees, between the pointer device and the screen.
  7536. *
  7537. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
  7538. */
  7539. _this.tiltX = void 0;
  7540. /**
  7541. * The angle, in degrees, between the pointer device and the screen.
  7542. *
  7543. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
  7544. */
  7545. _this.tiltY = void 0;
  7546. /**
  7547. * Twist of a stylus pointer.
  7548. *
  7549. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  7550. */
  7551. _this.twist = void 0;
  7552. return _this;
  7553. }
  7554. var _proto = FederatedPointerEvent.prototype;
  7555. /**
  7556. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents
  7557. */
  7558. _proto.getCoalescedEvents = function getCoalescedEvents() {
  7559. if (this.type === 'pointermove' || this.type === 'mousemove' || this.type === 'touchmove') {
  7560. return [this];
  7561. }
  7562. return [];
  7563. }
  7564. /**
  7565. * @see https://chromestatus.com/feature/5765569655603200
  7566. */;
  7567. _proto.getPredictedEvents = function getPredictedEvents() {
  7568. throw new Error('getPredictedEvents is not supported!');
  7569. }
  7570. /**
  7571. * @see https://github.com/antvis/G/issues/1115
  7572. * We currently reuses event objects in the event system,
  7573. * avoiding the creation of a large number of event objects.
  7574. * Reused objects are only used to carry different data,
  7575. * such as coordinate information, native event objects,
  7576. * and therefore the lifecycle is limited to the event handler,
  7577. * which can lead to unintended consequences if an attempt is made to cache the entire event object.
  7578. *
  7579. * Therefore, while keeping the above performance considerations in mind, it is possible to provide a clone method that creates a new object when the user really wants to cache it, e.g.
  7580. */;
  7581. _proto.clone = function clone() {
  7582. return this.manager.clonePointerEvent(this);
  7583. };
  7584. return FederatedPointerEvent;
  7585. }(FederatedMouseEvent);
  7586. var FederatedWheelEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
  7587. _inheritsLoose(FederatedWheelEvent, _FederatedMouseEvent);
  7588. function FederatedWheelEvent() {
  7589. var _this;
  7590. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  7591. args[_key] = arguments[_key];
  7592. }
  7593. _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
  7594. /**
  7595. * The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
  7596. * `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
  7597. */
  7598. _this.deltaMode = void 0;
  7599. /** Horizontal scroll amount */
  7600. _this.deltaX = void 0;
  7601. /** Vertical scroll amount */
  7602. _this.deltaY = void 0;
  7603. /** z-axis scroll amount. */
  7604. _this.deltaZ = void 0;
  7605. /** Units specified in lines. */
  7606. _this.DOM_DELTA_LINE = 0;
  7607. /** Units specified in pages. */
  7608. _this.DOM_DELTA_PAGE = 1;
  7609. /** Units specified in pixels. */
  7610. _this.DOM_DELTA_PIXEL = 2;
  7611. return _this;
  7612. }
  7613. var _proto = FederatedWheelEvent.prototype;
  7614. _proto.clone = function clone() {
  7615. return this.manager.cloneWheelEvent(this);
  7616. };
  7617. return FederatedWheelEvent;
  7618. }(FederatedMouseEvent);
  7619. function isDisplayObject(value) {
  7620. return !!(value === null || value === void 0 ? void 0 : value.nodeName);
  7621. }
  7622. var mutationEvent = new MutationEvent(exports.ElementEvent.ATTR_MODIFIED, null, null, null, null, MutationEvent.MODIFICATION, null, null);
  7623. var DEFAULT_STYLE_PROPS = {
  7624. anchor: '',
  7625. opacity: '',
  7626. fillOpacity: '',
  7627. strokeOpacity: '',
  7628. fill: '',
  7629. stroke: '',
  7630. transform: '',
  7631. transformOrigin: '',
  7632. visibility: '',
  7633. pointerEvents: '',
  7634. lineWidth: '',
  7635. lineCap: '',
  7636. lineJoin: '',
  7637. increasedLineWidthForHitTesting: '',
  7638. fontSize: '',
  7639. fontFamily: '',
  7640. fontStyle: '',
  7641. fontWeight: '',
  7642. fontVariant: '',
  7643. textAlign: '',
  7644. textBaseline: '',
  7645. textTransform: '',
  7646. zIndex: '',
  7647. filter: '',
  7648. shadowType: ''
  7649. };
  7650. var DEFAULT_PARSED_STYLE_PROPS = {
  7651. anchor: [0, 0],
  7652. fill: noneColor,
  7653. stroke: noneColor,
  7654. transform: [],
  7655. zIndex: 0,
  7656. filter: [],
  7657. shadowType: 'outer',
  7658. miterLimit: 10
  7659. };
  7660. var DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED = _extends({}, DEFAULT_PARSED_STYLE_PROPS, {
  7661. opacity: 1,
  7662. fillOpacity: 1,
  7663. strokeOpacity: 1,
  7664. visibility: 'visible',
  7665. pointerEvents: 'auto',
  7666. lineWidth: 1,
  7667. lineCap: 'butt',
  7668. lineJoin: 'miter',
  7669. increasedLineWidthForHitTesting: 0,
  7670. fillRule: 'nonzero'
  7671. // TODO: transformOrigin
  7672. });
  7673. var INHERITABLE_BASE_STYLE_PROPS = ['opacity', 'fillOpacity', 'strokeOpacity', 'transformOrigin', 'visibility', 'pointerEvents', 'lineWidth', 'lineCap', 'lineJoin', 'increasedLineWidthForHitTesting'];
  7674. var INHERITABLE_STYLE_PROPS = [].concat(INHERITABLE_BASE_STYLE_PROPS, ['fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'fontVariant', 'textAlign', 'textBaseline', 'textTransform']);
  7675. var DATASET_PREFIX = 'data-';
  7676. /**
  7677. * prototype chains: DisplayObject -> Element -> Node -> EventTarget
  7678. *
  7679. * mixins: Animatable, Transformable, Visible
  7680. * @see https://github.com/tannerntannern/ts-mixer/blob/master/README.md#mixing-generic-classes
  7681. *
  7682. * Provide abilities in scene graph, such as:
  7683. * * transform `translate/rotate/scale`
  7684. * * add/remove child
  7685. * * visibility and z-index
  7686. *
  7687. * Those abilities are implemented with those components: `Transform/Sortable/Visible`.
  7688. *
  7689. * Emit following events:
  7690. * * init
  7691. * * destroy
  7692. * * attributeChanged
  7693. */
  7694. var DisplayObject = /*#__PURE__*/function (_Element) {
  7695. _inheritsLoose(DisplayObject, _Element);
  7696. function DisplayObject(config) {
  7697. var _this$config$capture;
  7698. var _this;
  7699. _this = _Element.call(this) || this;
  7700. // assign name, id to config
  7701. // eg. group.get('name')
  7702. /**
  7703. * contains style props in constructor's params, eg. fill, stroke...
  7704. */
  7705. _this.config = void 0;
  7706. _this.isCustomElement = false;
  7707. _this.isMutationObserved = false;
  7708. /**
  7709. * push to active animations after calling `animate()`
  7710. */
  7711. _this.activeAnimations = [];
  7712. /**
  7713. * Use data-* attribute.
  7714. * @see https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
  7715. * @example
  7716. * group.dataset.prop1 = 1;
  7717. * group.getAttribute('data-prop1'); // 1
  7718. */
  7719. _this.dataset = void 0;
  7720. /**
  7721. * Use `this.style.clipPath` instead.
  7722. * @deprecated
  7723. */
  7724. _this.getClip = function () {
  7725. return this.style.clipPath || null;
  7726. };
  7727. _this.config = config;
  7728. // compatible with G 3.0
  7729. _this.config.interactive = (_this$config$capture = _this.config.capture) !== null && _this$config$capture !== void 0 ? _this$config$capture : _this.config.interactive;
  7730. // init scene graph node
  7731. _this.id = _this.config.id || '';
  7732. _this.name = _this.config.name || '';
  7733. if (_this.config.className || _this.config.class) {
  7734. _this.className = _this.config.className || _this.config.class;
  7735. }
  7736. _this.nodeName = _this.config.type || exports.Shape.GROUP;
  7737. // compatible with G 3.0
  7738. _this.config.style = _this.config.style || _this.config.attrs || {};
  7739. Object.assign(_this.config.style, _this.config.attrs);
  7740. // this.config.style = {
  7741. // // ...DEFAULT_STYLE_PROPS,
  7742. // ...this.config.style,
  7743. // ...this.config.attrs,
  7744. // };
  7745. if (_this.config.visible != null) {
  7746. _this.config.style.visibility = _this.config.visible === false ? 'hidden' : 'visible';
  7747. }
  7748. if (_this.config.interactive != null) {
  7749. _this.config.style.pointerEvents = _this.config.interactive === false ? 'none' : 'auto';
  7750. }
  7751. // merge parsed value
  7752. Object.assign(_this.parsedStyle, runtime.enableCSSParsing ? DEFAULT_PARSED_STYLE_PROPS : DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED, _this.config.initialParsedStyle);
  7753. if (runtime.enableCSSParsing) {
  7754. Object.assign(_this.attributes, DEFAULT_STYLE_PROPS);
  7755. }
  7756. // start to process attributes
  7757. _this.initAttributes(_this.config.style);
  7758. var Proxy = runtime.globalThis.Proxy ? runtime.globalThis.Proxy : function () {};
  7759. if (runtime.enableDataset) {
  7760. _this.dataset = new Proxy({}, {
  7761. get: function get(target, name) {
  7762. var formattedName = "" + DATASET_PREFIX + kebabize(name);
  7763. if (target[formattedName] !== undefined) {
  7764. return target[formattedName];
  7765. }
  7766. return _this.getAttribute(formattedName);
  7767. },
  7768. set: function set(_, prop, value) {
  7769. _this.setAttribute("" + DATASET_PREFIX + kebabize(prop), value);
  7770. return true;
  7771. }
  7772. });
  7773. }
  7774. if (runtime.enableStyleSyntax) {
  7775. _this.style = new Proxy(
  7776. // @ts-ignore
  7777. {
  7778. // ...this.attributes,
  7779. setProperty: function setProperty(propertyName, value) {
  7780. _this.setAttribute(propertyName, value);
  7781. },
  7782. getPropertyValue: function getPropertyValue(propertyName) {
  7783. return _this.getAttribute(propertyName);
  7784. },
  7785. removeProperty: function removeProperty(propertyName) {
  7786. _this.removeAttribute(propertyName);
  7787. },
  7788. item: function item() {
  7789. return '';
  7790. }
  7791. }, {
  7792. get: function get(target, name) {
  7793. if (target[name] !== undefined) {
  7794. // if (name in target) {
  7795. return target[name];
  7796. }
  7797. return _this.getAttribute(name);
  7798. },
  7799. set: function set(_, prop, value) {
  7800. _this.setAttribute(prop, value);
  7801. return true;
  7802. }
  7803. });
  7804. }
  7805. return _this;
  7806. }
  7807. var _proto = DisplayObject.prototype;
  7808. _proto.destroy = function destroy() {
  7809. _Element.prototype.destroy.call(this);
  7810. // stop all active animations
  7811. this.getAnimations().forEach(function (animation) {
  7812. animation.cancel();
  7813. });
  7814. // FIXME
  7815. // this.renderable = null;
  7816. // this.cullable = null;
  7817. // this.transformable = null;
  7818. // this.rBushNode = null;
  7819. // this.geometry = null;
  7820. // this.sortable = null;
  7821. };
  7822. _proto.cloneNode = function cloneNode(deep, customCloneFunc) {
  7823. var clonedStyle = _extends({}, this.attributes);
  7824. for (var attributeName in clonedStyle) {
  7825. var attribute = clonedStyle[attributeName];
  7826. // @see https://github.com/antvis/G/issues/1095
  7827. if (isDisplayObject(attribute) &&
  7828. // share the same clipPath if possible
  7829. attributeName !== 'clipPath' && attributeName !== 'offsetPath' && attributeName !== 'textPath') {
  7830. clonedStyle[attributeName] = attribute.cloneNode(deep);
  7831. }
  7832. // TODO: clone other type
  7833. if (customCloneFunc) {
  7834. clonedStyle[attributeName] = customCloneFunc(attributeName, attribute);
  7835. }
  7836. }
  7837. var cloned = new this.constructor({
  7838. // copy id & name
  7839. // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode#notes
  7840. id: this.id,
  7841. name: this.name,
  7842. className: this.name,
  7843. interactive: this.interactive,
  7844. style: clonedStyle
  7845. });
  7846. // apply transform
  7847. cloned.setLocalTransform(this.getLocalTransform());
  7848. if (deep) {
  7849. this.children.forEach(function (child) {
  7850. // skip marker
  7851. if (!child.style.isMarker) {
  7852. var clonedChild = child.cloneNode(deep);
  7853. cloned.appendChild(clonedChild);
  7854. }
  7855. });
  7856. }
  7857. return cloned;
  7858. };
  7859. _proto.initAttributes = function initAttributes(attributes) {
  7860. if (attributes === void 0) {
  7861. attributes = {};
  7862. }
  7863. var renderable = this.renderable;
  7864. var options = {
  7865. forceUpdateGeometry: true
  7866. // usedAttributes:
  7867. // // only Group / Text should account for text relative props
  7868. // this.tagName === Shape.GROUP || this.tagName === Shape.TEXT
  7869. // ? INHERITABLE_STYLE_PROPS
  7870. // : INHERITABLE_BASE_STYLE_PROPS,
  7871. };
  7872. if (runtime.enableCSSParsing) {
  7873. // @ts-ignore
  7874. options.usedAttributes = INHERITABLE_STYLE_PROPS;
  7875. }
  7876. // account for FCP, process properties as less as possible
  7877. var formattedAttributes = {};
  7878. for (var name in attributes) {
  7879. var attributeName = formatAttributeName(name);
  7880. formattedAttributes[attributeName] = attributes[name];
  7881. }
  7882. runtime.styleValueRegistry.processProperties(this, formattedAttributes, options);
  7883. // redraw at next frame
  7884. renderable.dirty = true;
  7885. };
  7886. _proto.setAttribute = function setAttribute(name, value, force) {
  7887. if (force === void 0) {
  7888. force = false;
  7889. }
  7890. var attributeName = formatAttributeName(name);
  7891. // ignore undefined value
  7892. if (util.isUndefined(value)) {
  7893. return;
  7894. }
  7895. if (force || value !== this.attributes[attributeName]) {
  7896. this.internalSetAttribute(attributeName, value);
  7897. _Element.prototype.setAttribute.call(this, attributeName, value);
  7898. }
  7899. }
  7900. /**
  7901. * called when attributes get changed or initialized
  7902. */;
  7903. _proto.internalSetAttribute = function internalSetAttribute(name, value, parseOptions) {
  7904. var _runtime$styleValueRe;
  7905. if (parseOptions === void 0) {
  7906. parseOptions = {};
  7907. }
  7908. var renderable = this.renderable;
  7909. var oldValue = this.attributes[name];
  7910. var oldParsedValue = this.parsedStyle[name];
  7911. runtime.styleValueRegistry.processProperties(this, (_runtime$styleValueRe = {}, _runtime$styleValueRe[name] = value, _runtime$styleValueRe), parseOptions);
  7912. // redraw at next frame
  7913. renderable.dirty = true;
  7914. var newParsedValue = this.parsedStyle[name];
  7915. if (this.isConnected) {
  7916. mutationEvent.relatedNode = this;
  7917. mutationEvent.prevValue = oldValue;
  7918. mutationEvent.newValue = value;
  7919. mutationEvent.attrName = name;
  7920. mutationEvent.prevParsedValue = oldParsedValue;
  7921. mutationEvent.newParsedValue = newParsedValue;
  7922. if (this.isMutationObserved) {
  7923. this.dispatchEvent(mutationEvent);
  7924. } else {
  7925. mutationEvent.target = this;
  7926. this.ownerDocument.defaultView.dispatchEvent(mutationEvent, true);
  7927. }
  7928. }
  7929. if ((this.isCustomElement && this.isConnected || !this.isCustomElement) && this.attributeChangedCallback) {
  7930. this.attributeChangedCallback(name, oldValue, value, oldParsedValue, newParsedValue);
  7931. }
  7932. }
  7933. // #region transformable
  7934. /**
  7935. * returns different values than getBoundingClientRect(), as the latter returns value relative to the viewport
  7936. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
  7937. *
  7938. * FIXME: It is worth noting that getBBox responds to original untransformed values of a drawn object.
  7939. * @see https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox
  7940. */;
  7941. _proto.getBBox = function getBBox() {
  7942. var aabb = this.getBounds();
  7943. var _aabb$getMin = aabb.getMin(),
  7944. left = _aabb$getMin[0],
  7945. top = _aabb$getMin[1];
  7946. var _aabb$getMax = aabb.getMax(),
  7947. right = _aabb$getMax[0],
  7948. bottom = _aabb$getMax[1];
  7949. return new Rectangle(left, top, right - left, bottom - top);
  7950. };
  7951. _proto.setOrigin = function setOrigin(position, y, z) {
  7952. if (y === void 0) {
  7953. y = 0;
  7954. }
  7955. if (z === void 0) {
  7956. z = 0;
  7957. }
  7958. runtime.sceneGraphService.setOrigin(this, createVec3(position, y, z));
  7959. return this;
  7960. };
  7961. _proto.getOrigin = function getOrigin() {
  7962. return runtime.sceneGraphService.getOrigin(this);
  7963. }
  7964. /**
  7965. * set position in world space
  7966. */;
  7967. _proto.setPosition = function setPosition(position, y, z) {
  7968. if (y === void 0) {
  7969. y = 0;
  7970. }
  7971. if (z === void 0) {
  7972. z = 0;
  7973. }
  7974. runtime.sceneGraphService.setPosition(this, createVec3(position, y, z));
  7975. return this;
  7976. }
  7977. /**
  7978. * set position in local space
  7979. */;
  7980. _proto.setLocalPosition = function setLocalPosition(position, y, z) {
  7981. if (y === void 0) {
  7982. y = 0;
  7983. }
  7984. if (z === void 0) {
  7985. z = 0;
  7986. }
  7987. runtime.sceneGraphService.setLocalPosition(this, createVec3(position, y, z));
  7988. return this;
  7989. }
  7990. /**
  7991. * translate in world space
  7992. */;
  7993. _proto.translate = function translate(position, y, z) {
  7994. if (y === void 0) {
  7995. y = 0;
  7996. }
  7997. if (z === void 0) {
  7998. z = 0;
  7999. }
  8000. runtime.sceneGraphService.translate(this, createVec3(position, y, z));
  8001. return this;
  8002. }
  8003. /**
  8004. * translate in local space
  8005. */;
  8006. _proto.translateLocal = function translateLocal(position, y, z) {
  8007. if (y === void 0) {
  8008. y = 0;
  8009. }
  8010. if (z === void 0) {
  8011. z = 0;
  8012. }
  8013. runtime.sceneGraphService.translateLocal(this, createVec3(position, y, z));
  8014. return this;
  8015. };
  8016. _proto.getPosition = function getPosition() {
  8017. return runtime.sceneGraphService.getPosition(this);
  8018. };
  8019. _proto.getLocalPosition = function getLocalPosition() {
  8020. return runtime.sceneGraphService.getLocalPosition(this);
  8021. }
  8022. /**
  8023. * compatible with G 3.0
  8024. *
  8025. * scaling in local space
  8026. * scale(10) = scale(10, 10, 10)
  8027. *
  8028. * we can't set scale in world space
  8029. */;
  8030. _proto.scale = function scale(scaling, y, z) {
  8031. return this.scaleLocal(scaling, y, z);
  8032. };
  8033. _proto.scaleLocal = function scaleLocal(scaling, y, z) {
  8034. if (typeof scaling === 'number') {
  8035. y = y || scaling;
  8036. z = z || scaling;
  8037. scaling = createVec3(scaling, y, z);
  8038. }
  8039. runtime.sceneGraphService.scaleLocal(this, scaling);
  8040. return this;
  8041. }
  8042. /**
  8043. * set scaling in local space
  8044. */;
  8045. _proto.setLocalScale = function setLocalScale(scaling, y, z) {
  8046. if (typeof scaling === 'number') {
  8047. y = y || scaling;
  8048. z = z || scaling;
  8049. scaling = createVec3(scaling, y, z);
  8050. }
  8051. runtime.sceneGraphService.setLocalScale(this, scaling);
  8052. return this;
  8053. }
  8054. /**
  8055. * get scaling in local space
  8056. */;
  8057. _proto.getLocalScale = function getLocalScale() {
  8058. return runtime.sceneGraphService.getLocalScale(this);
  8059. }
  8060. /**
  8061. * get scaling in world space
  8062. */;
  8063. _proto.getScale = function getScale() {
  8064. return runtime.sceneGraphService.getScale(this);
  8065. }
  8066. /**
  8067. * only return degrees of Z axis in world space
  8068. */;
  8069. _proto.getEulerAngles = function getEulerAngles() {
  8070. var _getEuler = getEuler(glMatrix.vec3.create(), runtime.sceneGraphService.getWorldTransform(this)),
  8071. ez = _getEuler[2];
  8072. return rad2deg(ez);
  8073. }
  8074. /**
  8075. * only return degrees of Z axis in local space
  8076. */;
  8077. _proto.getLocalEulerAngles = function getLocalEulerAngles() {
  8078. var _getEuler2 = getEuler(glMatrix.vec3.create(), runtime.sceneGraphService.getLocalRotation(this)),
  8079. ez = _getEuler2[2];
  8080. return rad2deg(ez);
  8081. }
  8082. /**
  8083. * set euler angles(degrees) in world space
  8084. */;
  8085. _proto.setEulerAngles = function setEulerAngles(z) {
  8086. runtime.sceneGraphService.setEulerAngles(this, 0, 0, z);
  8087. return this;
  8088. }
  8089. /**
  8090. * set euler angles(degrees) in local space
  8091. */;
  8092. _proto.setLocalEulerAngles = function setLocalEulerAngles(z) {
  8093. runtime.sceneGraphService.setLocalEulerAngles(this, 0, 0, z);
  8094. return this;
  8095. };
  8096. _proto.rotateLocal = function rotateLocal(x, y, z) {
  8097. if (util.isNil(y) && util.isNil(z)) {
  8098. runtime.sceneGraphService.rotateLocal(this, 0, 0, x);
  8099. } else {
  8100. runtime.sceneGraphService.rotateLocal(this, x, y, z);
  8101. }
  8102. return this;
  8103. };
  8104. _proto.rotate = function rotate(x, y, z) {
  8105. if (util.isNil(y) && util.isNil(z)) {
  8106. runtime.sceneGraphService.rotate(this, 0, 0, x);
  8107. } else {
  8108. runtime.sceneGraphService.rotate(this, x, y, z);
  8109. }
  8110. return this;
  8111. };
  8112. _proto.setRotation = function setRotation(rotation, y, z, w) {
  8113. runtime.sceneGraphService.setRotation(this, rotation, y, z, w);
  8114. return this;
  8115. };
  8116. _proto.setLocalRotation = function setLocalRotation(rotation, y, z, w) {
  8117. runtime.sceneGraphService.setLocalRotation(this, rotation, y, z, w);
  8118. return this;
  8119. };
  8120. _proto.setLocalSkew = function setLocalSkew(skew, y) {
  8121. runtime.sceneGraphService.setLocalSkew(this, skew, y);
  8122. return this;
  8123. };
  8124. _proto.getRotation = function getRotation() {
  8125. return runtime.sceneGraphService.getRotation(this);
  8126. };
  8127. _proto.getLocalRotation = function getLocalRotation() {
  8128. return runtime.sceneGraphService.getLocalRotation(this);
  8129. };
  8130. _proto.getLocalSkew = function getLocalSkew() {
  8131. return runtime.sceneGraphService.getLocalSkew(this);
  8132. };
  8133. _proto.getLocalTransform = function getLocalTransform() {
  8134. return runtime.sceneGraphService.getLocalTransform(this);
  8135. };
  8136. _proto.getWorldTransform = function getWorldTransform() {
  8137. return runtime.sceneGraphService.getWorldTransform(this);
  8138. };
  8139. _proto.setLocalTransform = function setLocalTransform(transform) {
  8140. runtime.sceneGraphService.setLocalTransform(this, transform);
  8141. return this;
  8142. };
  8143. _proto.resetLocalTransform = function resetLocalTransform() {
  8144. runtime.sceneGraphService.resetLocalTransform(this);
  8145. }
  8146. // #endregion transformable
  8147. // #region animatable
  8148. /**
  8149. * returns an array of all Animation objects affecting this element
  8150. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
  8151. */;
  8152. _proto.getAnimations = function getAnimations() {
  8153. return this.activeAnimations;
  8154. }
  8155. /**
  8156. * create an animation with WAAPI
  8157. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/animate
  8158. */;
  8159. _proto.animate = function animate(keyframes, options) {
  8160. var _this$ownerDocument;
  8161. var timeline = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.timeline;
  8162. if (timeline) {
  8163. return timeline.play(this, keyframes, options);
  8164. }
  8165. return null;
  8166. }
  8167. // #endregion animatable
  8168. // #region visible
  8169. /**
  8170. * shortcut for Used value of `visibility`
  8171. */;
  8172. _proto.isVisible = function isVisible() {
  8173. var _this$parsedStyle;
  8174. return ((_this$parsedStyle = this.parsedStyle) === null || _this$parsedStyle === void 0 ? void 0 : _this$parsedStyle.visibility) === 'visible';
  8175. };
  8176. _proto.isInteractive = function isInteractive() {
  8177. var _this$parsedStyle2;
  8178. return ((_this$parsedStyle2 = this.parsedStyle) === null || _this$parsedStyle2 === void 0 ? void 0 : _this$parsedStyle2.pointerEvents) !== 'none';
  8179. };
  8180. _proto.isCulled = function isCulled() {
  8181. return !!(this.cullable && this.cullable.enable && !this.cullable.visible);
  8182. }
  8183. /**
  8184. * bring to front in current group
  8185. */;
  8186. _proto.toFront = function toFront() {
  8187. if (this.parentNode) {
  8188. this.style.zIndex = Math.max.apply(Math, this.parentNode.children.map(function (child) {
  8189. return Number(child.style.zIndex);
  8190. })) + 1;
  8191. }
  8192. return this;
  8193. }
  8194. /**
  8195. * send to back in current group
  8196. */;
  8197. _proto.toBack = function toBack() {
  8198. if (this.parentNode) {
  8199. this.style.zIndex = Math.min.apply(Math, this.parentNode.children.map(function (child) {
  8200. return Number(child.style.zIndex);
  8201. })) - 1;
  8202. }
  8203. return this;
  8204. }
  8205. // #endregion visible
  8206. // #region deprecated
  8207. /**
  8208. * compatible with G 3.0
  8209. * @alias object.config
  8210. * @deprecated
  8211. */;
  8212. _proto.getConfig = function getConfig() {
  8213. return this.config;
  8214. };
  8215. _proto.attr = function attr() {
  8216. var _this2 = this;
  8217. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  8218. args[_key] = arguments[_key];
  8219. }
  8220. var name = args[0],
  8221. value = args[1];
  8222. if (!name) {
  8223. return this.attributes;
  8224. }
  8225. if (util.isObject(name)) {
  8226. Object.keys(name).forEach(function (key) {
  8227. _this2.setAttribute(key, name[key]);
  8228. });
  8229. return this;
  8230. }
  8231. if (args.length === 2) {
  8232. this.setAttribute(name, value);
  8233. return this;
  8234. }
  8235. return this.attributes[name];
  8236. }
  8237. /**
  8238. * return 3x3 matrix in world space
  8239. * @deprecated
  8240. */;
  8241. _proto.getMatrix = function getMatrix(transformMat4) {
  8242. var transform = transformMat4 || this.getWorldTransform();
  8243. var _mat4$getTranslation = glMatrix.mat4.getTranslation(glMatrix.vec3.create(), transform),
  8244. tx = _mat4$getTranslation[0],
  8245. ty = _mat4$getTranslation[1];
  8246. var _mat4$getScaling = glMatrix.mat4.getScaling(glMatrix.vec3.create(), transform),
  8247. sx = _mat4$getScaling[0],
  8248. sy = _mat4$getScaling[1];
  8249. var rotation = glMatrix.mat4.getRotation(glMatrix.quat.create(), transform);
  8250. var _getEuler3 = getEuler(glMatrix.vec3.create(), rotation),
  8251. eux = _getEuler3[0],
  8252. euz = _getEuler3[2];
  8253. // gimbal lock at 90 degrees
  8254. return fromRotationTranslationScale(eux || euz, tx, ty, sx, sy);
  8255. }
  8256. /**
  8257. * return 3x3 matrix in local space
  8258. * @deprecated
  8259. */;
  8260. _proto.getLocalMatrix = function getLocalMatrix() {
  8261. return this.getMatrix(this.getLocalTransform());
  8262. }
  8263. /**
  8264. * set 3x3 matrix in world space
  8265. * @deprecated
  8266. */;
  8267. _proto.setMatrix = function setMatrix(mat) {
  8268. var _decompose = decompose(mat),
  8269. tx = _decompose[0],
  8270. ty = _decompose[1],
  8271. scalingX = _decompose[2],
  8272. scalingY = _decompose[3],
  8273. angle = _decompose[4];
  8274. this.setEulerAngles(angle).setPosition(tx, ty).setLocalScale(scalingX, scalingY);
  8275. }
  8276. /**
  8277. * set 3x3 matrix in local space
  8278. * @deprecated
  8279. */;
  8280. _proto.setLocalMatrix = function setLocalMatrix(mat) {
  8281. var _decompose2 = decompose(mat),
  8282. tx = _decompose2[0],
  8283. ty = _decompose2[1],
  8284. scalingX = _decompose2[2],
  8285. scalingY = _decompose2[3],
  8286. angle = _decompose2[4];
  8287. this.setLocalEulerAngles(angle).setLocalPosition(tx, ty).setLocalScale(scalingX, scalingY);
  8288. }
  8289. /**
  8290. * Use `visibility: visible` instead.
  8291. * @deprecated
  8292. */;
  8293. _proto.show = function show() {
  8294. if (runtime.enableCSSParsing) {
  8295. this.style.visibility = 'visible';
  8296. } else {
  8297. this.forEach(function (object) {
  8298. object.style.visibility = 'visible';
  8299. });
  8300. }
  8301. }
  8302. /**
  8303. * Use `visibility: hidden` instead.
  8304. * @deprecated
  8305. */;
  8306. _proto.hide = function hide() {
  8307. if (runtime.enableCSSParsing) {
  8308. this.style.visibility = 'hidden';
  8309. } else {
  8310. this.forEach(function (object) {
  8311. object.style.visibility = 'hidden';
  8312. });
  8313. }
  8314. }
  8315. /**
  8316. * Use `childElementCount` instead.
  8317. * @deprecated
  8318. */;
  8319. _proto.getCount = function getCount() {
  8320. return this.childElementCount;
  8321. }
  8322. /**
  8323. * Use `parentElement` instead.
  8324. * @deprecated
  8325. */;
  8326. _proto.getParent = function getParent() {
  8327. return this.parentElement;
  8328. }
  8329. /**
  8330. * Use `children` instead.
  8331. * @deprecated
  8332. */;
  8333. _proto.getChildren = function getChildren() {
  8334. return this.children;
  8335. }
  8336. /**
  8337. * Use `firstElementChild` instead.
  8338. * @deprecated
  8339. */;
  8340. _proto.getFirst = function getFirst() {
  8341. return this.firstElementChild;
  8342. }
  8343. /**
  8344. * Use `lastElementChild` instead.
  8345. * @deprecated
  8346. */;
  8347. _proto.getLast = function getLast() {
  8348. return this.lastElementChild;
  8349. }
  8350. /**
  8351. * Use `this.children[index]` instead.
  8352. * @deprecated
  8353. */;
  8354. _proto.getChildByIndex = function getChildByIndex(index) {
  8355. return this.children[index] || null;
  8356. }
  8357. /**
  8358. * Use `appendChild` instead.
  8359. * @deprecated
  8360. */;
  8361. _proto.add = function add(child, index) {
  8362. return this.appendChild(child, index);
  8363. }
  8364. /**
  8365. * Use `this.style.clipPath` instead.
  8366. * @deprecated
  8367. */;
  8368. _proto.setClip = function setClip(clipPath) {
  8369. this.style.clipPath = clipPath;
  8370. };
  8371. /**
  8372. * @deprecated
  8373. */
  8374. _proto.set = function set(name, value) {
  8375. // @ts-ignore
  8376. this.config[name] = value;
  8377. }
  8378. /**
  8379. * @deprecated
  8380. */;
  8381. _proto.get = function get(name) {
  8382. return this.config[name];
  8383. }
  8384. /**
  8385. * Use `setPosition` instead.
  8386. * @deprecated
  8387. */;
  8388. _proto.moveTo = function moveTo(position, y, z) {
  8389. if (y === void 0) {
  8390. y = 0;
  8391. }
  8392. if (z === void 0) {
  8393. z = 0;
  8394. }
  8395. this.setPosition(position, y, z);
  8396. return this;
  8397. }
  8398. /**
  8399. * Use `setPosition` instead.
  8400. * @deprecated
  8401. */;
  8402. _proto.move = function move(position, y, z) {
  8403. if (y === void 0) {
  8404. y = 0;
  8405. }
  8406. if (z === void 0) {
  8407. z = 0;
  8408. }
  8409. this.setPosition(position, y, z);
  8410. return this;
  8411. }
  8412. /**
  8413. * Use `this.style.zIndex` instead.
  8414. * @deprecated
  8415. */;
  8416. _proto.setZIndex = function setZIndex(zIndex) {
  8417. this.style.zIndex = zIndex;
  8418. return this;
  8419. };
  8420. _createClass(DisplayObject, [{
  8421. key: "interactive",
  8422. get: function get() {
  8423. return this.isInteractive();
  8424. },
  8425. set: function set(b) {
  8426. this.style.pointerEvents = b ? 'auto' : 'none';
  8427. }
  8428. }]);
  8429. return DisplayObject;
  8430. }(Element);
  8431. var _excluded = ["style"];
  8432. var Circle = /*#__PURE__*/function (_DisplayObject) {
  8433. _inheritsLoose(Circle, _DisplayObject);
  8434. function Circle(_temp) {
  8435. var _ref = _temp === void 0 ? {} : _temp,
  8436. style = _ref.style,
  8437. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  8438. return _DisplayObject.call(this, _extends({
  8439. type: exports.Shape.CIRCLE,
  8440. style: runtime.enableCSSParsing ? _extends({
  8441. cx: '',
  8442. cy: '',
  8443. r: ''
  8444. }, style) : _extends({}, style),
  8445. initialParsedStyle: {
  8446. anchor: [0.5, 0.5],
  8447. transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
  8448. }
  8449. }, rest)) || this;
  8450. }
  8451. return Circle;
  8452. }(DisplayObject);
  8453. var _excluded$1 = ["style"];
  8454. /**
  8455. * shadow root
  8456. * @see https://yuque.antfin-inc.com/antv/czqvg5/pgqipg
  8457. */
  8458. var CustomElement = /*#__PURE__*/function (_DisplayObject) {
  8459. _inheritsLoose(CustomElement, _DisplayObject);
  8460. // private shadowNodes: DisplayObject[] = [];
  8461. function CustomElement(_temp) {
  8462. var _this;
  8463. var _ref = _temp === void 0 ? {} : _temp,
  8464. style = _ref.style,
  8465. rest = _objectWithoutPropertiesLoose(_ref, _excluded$1);
  8466. _this = _DisplayObject.call(this, _extends({
  8467. style: runtime.enableCSSParsing ? _extends({
  8468. x: '',
  8469. y: ''
  8470. }, style) : _extends({}, style)
  8471. }, rest)) || this;
  8472. // static get observedAttributes(): string[] {
  8473. // return [];
  8474. // }
  8475. _this.isCustomElement = true;
  8476. return _this;
  8477. }
  8478. return CustomElement;
  8479. }(DisplayObject);
  8480. var _excluded$2 = ["style"];
  8481. var Ellipse = /*#__PURE__*/function (_DisplayObject) {
  8482. _inheritsLoose(Ellipse, _DisplayObject);
  8483. function Ellipse(_temp) {
  8484. var _ref = _temp === void 0 ? {} : _temp,
  8485. style = _ref.style,
  8486. rest = _objectWithoutPropertiesLoose(_ref, _excluded$2);
  8487. return _DisplayObject.call(this, _extends({
  8488. type: exports.Shape.ELLIPSE,
  8489. style: runtime.enableCSSParsing ? _extends({
  8490. cx: '',
  8491. cy: '',
  8492. rx: '',
  8493. ry: ''
  8494. }, style) : _extends({}, style),
  8495. initialParsedStyle: {
  8496. anchor: [0.5, 0.5],
  8497. transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
  8498. }
  8499. }, rest)) || this;
  8500. }
  8501. return Ellipse;
  8502. }(DisplayObject);
  8503. var _excluded$3 = ["style"];
  8504. /**
  8505. * its attributes are inherited by its children.
  8506. * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g
  8507. *
  8508. * @example
  8509. * <g fill="white" stroke="green" stroke-width="5">
  8510. <circle cx="40" cy="40" r="25" />
  8511. <circle cx="60" cy="60" r="25" />
  8512. </g>
  8513. */
  8514. var Group = /*#__PURE__*/function (_DisplayObject) {
  8515. _inheritsLoose(Group, _DisplayObject);
  8516. function Group(_temp) {
  8517. var _ref = _temp === void 0 ? {} : _temp,
  8518. style = _ref.style,
  8519. rest = _objectWithoutPropertiesLoose(_ref, _excluded$3);
  8520. return _DisplayObject.call(this, _extends({
  8521. type: exports.Shape.GROUP,
  8522. style: runtime.enableCSSParsing ? _extends({
  8523. x: '',
  8524. y: '',
  8525. width: '',
  8526. height: ''
  8527. }, style) : _extends({}, style)
  8528. }, rest)) || this;
  8529. }
  8530. return Group;
  8531. }(DisplayObject);
  8532. var _excluded$4 = ["style"];
  8533. /**
  8534. * HTML container
  8535. * @see https://github.com/pmndrs/drei#html
  8536. */
  8537. var HTML = /*#__PURE__*/function (_DisplayObject) {
  8538. _inheritsLoose(HTML, _DisplayObject);
  8539. function HTML(_temp) {
  8540. var _this;
  8541. var _ref = _temp === void 0 ? {} : _temp,
  8542. style = _ref.style,
  8543. rest = _objectWithoutPropertiesLoose(_ref, _excluded$4);
  8544. _this = _DisplayObject.call(this, _extends({
  8545. type: exports.Shape.HTML,
  8546. style: runtime.enableCSSParsing ? _extends({
  8547. x: '',
  8548. y: '',
  8549. width: 'auto',
  8550. height: 'auto',
  8551. innerHTML: ''
  8552. }, style) : _extends({}, style)
  8553. }, rest)) || this;
  8554. _this.cullable.enable = false;
  8555. return _this;
  8556. }
  8557. /**
  8558. * return wrapper HTMLElement
  8559. * * <div> in g-webgl/canvas
  8560. * * <foreignObject> in g-svg
  8561. */
  8562. var _proto = HTML.prototype;
  8563. _proto.getDomElement = function getDomElement() {
  8564. return this.parsedStyle.$el;
  8565. }
  8566. /**
  8567. * override with $el.getBoundingClientRect
  8568. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
  8569. */;
  8570. _proto.getBoundingClientRect = function getBoundingClientRect() {
  8571. return this.parsedStyle.$el.getBoundingClientRect();
  8572. };
  8573. _proto.getClientRects = function getClientRects() {
  8574. return [this.getBoundingClientRect()];
  8575. };
  8576. _proto.getBounds = function getBounds() {
  8577. var _this$ownerDocument, _this$ownerDocument$d;
  8578. var clientRect = this.getBoundingClientRect();
  8579. // calc context's offset
  8580. // @ts-ignore
  8581. var canvasRect = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : (_this$ownerDocument$d = _this$ownerDocument.defaultView) === null || _this$ownerDocument$d === void 0 ? void 0 : _this$ownerDocument$d.getContextService().getBoundingClientRect();
  8582. if (canvasRect) {
  8583. var minX = clientRect.left - canvasRect.left;
  8584. var minY = clientRect.top - canvasRect.top;
  8585. var aabb = new AABB();
  8586. // aabb.setMinMax(
  8587. // vec3.fromValues(minX, minY, 0),
  8588. // vec3.fromValues(minX + clientRect.width, minY + clientRect.height, 0),
  8589. // );
  8590. aabb.setMinMax([minX, minY, 0], [minX + clientRect.width, minY + clientRect.height, 0]);
  8591. return aabb;
  8592. }
  8593. return null;
  8594. };
  8595. _proto.getLocalBounds = function getLocalBounds() {
  8596. if (this.parentNode) {
  8597. var parentInvert = glMatrix.mat4.invert(glMatrix.mat4.create(), this.parentNode.getWorldTransform());
  8598. var bounds = this.getBounds();
  8599. if (!AABB.isEmpty(bounds)) {
  8600. var localBounds = new AABB();
  8601. localBounds.setFromTransformedAABB(bounds, parentInvert);
  8602. return localBounds;
  8603. }
  8604. }
  8605. return this.getBounds();
  8606. };
  8607. return HTML;
  8608. }(DisplayObject);
  8609. var _excluded$5 = ["style"];
  8610. var Image = /*#__PURE__*/function (_DisplayObject) {
  8611. _inheritsLoose(Image, _DisplayObject);
  8612. function Image(_temp) {
  8613. var _ref = _temp === void 0 ? {} : _temp,
  8614. style = _ref.style,
  8615. rest = _objectWithoutPropertiesLoose(_ref, _excluded$5);
  8616. return _DisplayObject.call(this, _extends({
  8617. type: exports.Shape.IMAGE,
  8618. style: runtime.enableCSSParsing ? _extends({
  8619. x: '',
  8620. y: '',
  8621. img: '',
  8622. width: '',
  8623. height: ''
  8624. }, style) : _extends({}, style)
  8625. }, rest)) || this;
  8626. }
  8627. return Image;
  8628. }(DisplayObject);
  8629. var _excluded$6 = ["style"];
  8630. /**
  8631. * Create a line connecting two points.
  8632. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line
  8633. *
  8634. * Also support for using marker.
  8635. */
  8636. var Line = /*#__PURE__*/function (_DisplayObject) {
  8637. _inheritsLoose(Line, _DisplayObject);
  8638. function Line(_temp) {
  8639. var _this;
  8640. var _ref = _temp === void 0 ? {} : _temp,
  8641. style = _ref.style,
  8642. rest = _objectWithoutPropertiesLoose(_ref, _excluded$6);
  8643. _this = _DisplayObject.call(this, _extends({
  8644. type: exports.Shape.LINE,
  8645. style: _extends({
  8646. x1: 0,
  8647. y1: 0,
  8648. x2: 0,
  8649. y2: 0,
  8650. z1: 0,
  8651. z2: 0,
  8652. isBillboard: false
  8653. }, style)
  8654. }, rest)) || this;
  8655. _this.markerStartAngle = 0;
  8656. _this.markerEndAngle = 0;
  8657. var _this$parsedStyle = _this.parsedStyle,
  8658. markerStart = _this$parsedStyle.markerStart,
  8659. markerEnd = _this$parsedStyle.markerEnd;
  8660. if (markerStart && isDisplayObject(markerStart)) {
  8661. _this.markerStartAngle = markerStart.getLocalEulerAngles();
  8662. _this.appendChild(markerStart);
  8663. }
  8664. if (markerEnd && isDisplayObject(markerEnd)) {
  8665. _this.markerEndAngle = markerEnd.getLocalEulerAngles();
  8666. _this.appendChild(markerEnd);
  8667. }
  8668. _this.transformMarker(true);
  8669. _this.transformMarker(false);
  8670. return _this;
  8671. }
  8672. var _proto = Line.prototype;
  8673. _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
  8674. if (attrName === 'x1' || attrName === 'y1' || attrName === 'x2' || attrName === 'y2' || attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
  8675. this.transformMarker(true);
  8676. this.transformMarker(false);
  8677. } else if (attrName === 'markerStart') {
  8678. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8679. this.markerStartAngle = 0;
  8680. prevParsedValue.remove();
  8681. }
  8682. // CSSKeyword 'unset'
  8683. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8684. this.markerStartAngle = newParsedValue.getLocalEulerAngles();
  8685. this.appendChild(newParsedValue);
  8686. this.transformMarker(true);
  8687. }
  8688. } else if (attrName === 'markerEnd') {
  8689. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8690. this.markerEndAngle = 0;
  8691. prevParsedValue.remove();
  8692. }
  8693. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8694. this.markerEndAngle = newParsedValue.getLocalEulerAngles();
  8695. this.appendChild(newParsedValue);
  8696. this.transformMarker(false);
  8697. }
  8698. }
  8699. };
  8700. _proto.transformMarker = function transformMarker(isStart) {
  8701. var _this$parsedStyle2 = this.parsedStyle,
  8702. markerStart = _this$parsedStyle2.markerStart,
  8703. markerEnd = _this$parsedStyle2.markerEnd,
  8704. markerStartOffset = _this$parsedStyle2.markerStartOffset,
  8705. markerEndOffset = _this$parsedStyle2.markerEndOffset,
  8706. x1 = _this$parsedStyle2.x1,
  8707. x2 = _this$parsedStyle2.x2,
  8708. y1 = _this$parsedStyle2.y1,
  8709. y2 = _this$parsedStyle2.y2,
  8710. defX = _this$parsedStyle2.defX,
  8711. defY = _this$parsedStyle2.defY;
  8712. var marker = isStart ? markerStart : markerEnd;
  8713. if (!marker || !isDisplayObject(marker)) {
  8714. return;
  8715. }
  8716. var rad = 0;
  8717. var x;
  8718. var y;
  8719. var ox;
  8720. var oy;
  8721. var offset;
  8722. var originalAngle;
  8723. if (isStart) {
  8724. ox = x1 - defX;
  8725. oy = y1 - defY;
  8726. x = x2 - x1;
  8727. y = y2 - y1;
  8728. offset = markerStartOffset || 0;
  8729. originalAngle = this.markerStartAngle;
  8730. } else {
  8731. ox = x2 - defX;
  8732. oy = y2 - defY;
  8733. x = x1 - x2;
  8734. y = y1 - y2;
  8735. offset = markerEndOffset || 0;
  8736. originalAngle = this.markerEndAngle;
  8737. }
  8738. rad = Math.atan2(y, x);
  8739. // account for markerOffset
  8740. marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
  8741. marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
  8742. };
  8743. _proto.getPoint = function getPoint(ratio, inWorldSpace) {
  8744. if (inWorldSpace === void 0) {
  8745. inWorldSpace = false;
  8746. }
  8747. // TODO: account for z1/z2 in 3D line
  8748. var _this$parsedStyle3 = this.parsedStyle,
  8749. x1 = _this$parsedStyle3.x1,
  8750. y1 = _this$parsedStyle3.y1,
  8751. x2 = _this$parsedStyle3.x2,
  8752. y2 = _this$parsedStyle3.y2,
  8753. defX = _this$parsedStyle3.defX,
  8754. defY = _this$parsedStyle3.defY;
  8755. var _LineUtil$pointAt = gMath.Line.pointAt(x1, y1, x2, y2, ratio),
  8756. x = _LineUtil$pointAt.x,
  8757. y = _LineUtil$pointAt.y;
  8758. var transformed = glMatrix.vec3.transformMat4(glMatrix.vec3.create(), glMatrix.vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
  8759. // apply local transformation
  8760. return new Point(transformed[0], transformed[1]);
  8761. };
  8762. _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
  8763. if (inWorldSpace === void 0) {
  8764. inWorldSpace = false;
  8765. }
  8766. return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
  8767. };
  8768. _proto.getTotalLength = function getTotalLength() {
  8769. // TODO: account for z1/z2 in 3D line
  8770. var _this$parsedStyle4 = this.parsedStyle,
  8771. x1 = _this$parsedStyle4.x1,
  8772. y1 = _this$parsedStyle4.y1,
  8773. x2 = _this$parsedStyle4.x2,
  8774. y2 = _this$parsedStyle4.y2;
  8775. return gMath.Line.length(x1, y1, x2, y2);
  8776. };
  8777. return Line;
  8778. }(DisplayObject);
  8779. var _excluded$7 = ["style"];
  8780. var EMPTY_PARSED_PATH = {
  8781. absolutePath: [],
  8782. hasArc: false,
  8783. segments: [],
  8784. polygons: [],
  8785. polylines: [],
  8786. curve: null,
  8787. totalLength: 0,
  8788. rect: new Rectangle(0, 0, 0, 0)
  8789. };
  8790. var Path = /*#__PURE__*/function (_DisplayObject) {
  8791. _inheritsLoose(Path, _DisplayObject);
  8792. function Path(_temp) {
  8793. var _this;
  8794. var _ref = _temp === void 0 ? {} : _temp,
  8795. style = _ref.style,
  8796. rest = _objectWithoutPropertiesLoose(_ref, _excluded$7);
  8797. _this = _DisplayObject.call(this, _extends({
  8798. type: exports.Shape.PATH,
  8799. style: runtime.enableCSSParsing ? _extends({
  8800. path: '',
  8801. miterLimit: ''
  8802. }, style) : _extends({}, style),
  8803. initialParsedStyle: runtime.enableCSSParsing ? null : {
  8804. miterLimit: 4,
  8805. path: _extends({}, EMPTY_PARSED_PATH)
  8806. }
  8807. }, rest)) || this;
  8808. _this.markerStartAngle = 0;
  8809. _this.markerEndAngle = 0;
  8810. /**
  8811. * markers placed at the mid
  8812. */
  8813. _this.markerMidList = [];
  8814. var _this$parsedStyle = _this.parsedStyle,
  8815. markerStart = _this$parsedStyle.markerStart,
  8816. markerEnd = _this$parsedStyle.markerEnd,
  8817. markerMid = _this$parsedStyle.markerMid;
  8818. if (markerStart && isDisplayObject(markerStart)) {
  8819. _this.markerStartAngle = markerStart.getLocalEulerAngles();
  8820. _this.appendChild(markerStart);
  8821. }
  8822. if (markerMid && isDisplayObject(markerMid)) {
  8823. _this.placeMarkerMid(markerMid);
  8824. }
  8825. if (markerEnd && isDisplayObject(markerEnd)) {
  8826. _this.markerEndAngle = markerEnd.getLocalEulerAngles();
  8827. _this.appendChild(markerEnd);
  8828. }
  8829. _this.transformMarker(true);
  8830. _this.transformMarker(false);
  8831. return _this;
  8832. }
  8833. var _proto = Path.prototype;
  8834. _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
  8835. if (attrName === 'path') {
  8836. // recalc markers
  8837. this.transformMarker(true);
  8838. this.transformMarker(false);
  8839. this.placeMarkerMid(this.parsedStyle.markerMid);
  8840. } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
  8841. this.transformMarker(true);
  8842. this.transformMarker(false);
  8843. } else if (attrName === 'markerStart') {
  8844. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8845. this.markerStartAngle = 0;
  8846. prevParsedValue.remove();
  8847. }
  8848. // CSSKeyword 'unset'
  8849. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8850. this.markerStartAngle = newParsedValue.getLocalEulerAngles();
  8851. this.appendChild(newParsedValue);
  8852. this.transformMarker(true);
  8853. }
  8854. } else if (attrName === 'markerEnd') {
  8855. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8856. this.markerEndAngle = 0;
  8857. prevParsedValue.remove();
  8858. }
  8859. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8860. this.markerEndAngle = newParsedValue.getLocalEulerAngles();
  8861. this.appendChild(newParsedValue);
  8862. this.transformMarker(false);
  8863. }
  8864. } else if (attrName === 'markerMid') {
  8865. this.placeMarkerMid(newParsedValue);
  8866. }
  8867. };
  8868. _proto.transformMarker = function transformMarker(isStart) {
  8869. var _this$parsedStyle2 = this.parsedStyle,
  8870. markerStart = _this$parsedStyle2.markerStart,
  8871. markerEnd = _this$parsedStyle2.markerEnd,
  8872. markerStartOffset = _this$parsedStyle2.markerStartOffset,
  8873. markerEndOffset = _this$parsedStyle2.markerEndOffset,
  8874. defX = _this$parsedStyle2.defX,
  8875. defY = _this$parsedStyle2.defY;
  8876. var marker = isStart ? markerStart : markerEnd;
  8877. if (!marker || !isDisplayObject(marker)) {
  8878. return;
  8879. }
  8880. var rad = 0;
  8881. var x;
  8882. var y;
  8883. var ox;
  8884. var oy;
  8885. var offset;
  8886. var originalAngle;
  8887. if (isStart) {
  8888. var _this$getStartTangent = this.getStartTangent(),
  8889. p1 = _this$getStartTangent[0],
  8890. p2 = _this$getStartTangent[1];
  8891. ox = p2[0] - defX;
  8892. oy = p2[1] - defY;
  8893. x = p1[0] - p2[0];
  8894. y = p1[1] - p2[1];
  8895. offset = markerStartOffset || 0;
  8896. originalAngle = this.markerStartAngle;
  8897. } else {
  8898. var _this$getEndTangent = this.getEndTangent(),
  8899. _p = _this$getEndTangent[0],
  8900. _p2 = _this$getEndTangent[1];
  8901. ox = _p2[0] - defX;
  8902. oy = _p2[1] - defY;
  8903. x = _p[0] - _p2[0];
  8904. y = _p[1] - _p2[1];
  8905. offset = markerEndOffset || 0;
  8906. originalAngle = this.markerEndAngle;
  8907. }
  8908. rad = Math.atan2(y, x);
  8909. // account for markerOffset
  8910. marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
  8911. marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
  8912. };
  8913. _proto.placeMarkerMid = function placeMarkerMid(marker) {
  8914. var _this$parsedStyle3 = this.parsedStyle,
  8915. segments = _this$parsedStyle3.path.segments,
  8916. defX = _this$parsedStyle3.defX,
  8917. defY = _this$parsedStyle3.defY;
  8918. // clear all existed markers
  8919. this.markerMidList.forEach(function (marker) {
  8920. marker.remove();
  8921. });
  8922. if (marker && isDisplayObject(marker)) {
  8923. for (var i = 1; i < segments.length - 1; i++) {
  8924. var _segments$i$currentPo = segments[i].currentPoint,
  8925. ox = _segments$i$currentPo[0],
  8926. oy = _segments$i$currentPo[1];
  8927. var cloned = i === 1 ? marker : marker.cloneNode(true);
  8928. this.markerMidList.push(cloned);
  8929. this.appendChild(cloned);
  8930. cloned.setLocalPosition(ox - defX, oy - defY);
  8931. // TODO: orient of marker
  8932. }
  8933. }
  8934. }
  8935. /**
  8936. * Returns the total length of the path.
  8937. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
  8938. */;
  8939. _proto.getTotalLength = function getTotalLength() {
  8940. return getOrCalculatePathTotalLength(this);
  8941. }
  8942. /**
  8943. * Returns the point at a given distance along the path.
  8944. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getPointAtLength
  8945. */;
  8946. _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
  8947. if (inWorldSpace === void 0) {
  8948. inWorldSpace = false;
  8949. }
  8950. var _this$parsedStyle4 = this.parsedStyle,
  8951. defX = _this$parsedStyle4.defX,
  8952. defY = _this$parsedStyle4.defY,
  8953. absolutePath = _this$parsedStyle4.path.absolutePath;
  8954. var _getPointAtLength2 = util.getPointAtLength(absolutePath, distance),
  8955. x = _getPointAtLength2.x,
  8956. y = _getPointAtLength2.y;
  8957. var transformed = glMatrix.vec3.transformMat4(glMatrix.vec3.create(), glMatrix.vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
  8958. // apply local transformation
  8959. return new Point(transformed[0], transformed[1]);
  8960. }
  8961. /**
  8962. * Returns the point at a given ratio of the total length in path.
  8963. */;
  8964. _proto.getPoint = function getPoint(ratio, inWorldSpace) {
  8965. if (inWorldSpace === void 0) {
  8966. inWorldSpace = false;
  8967. }
  8968. return this.getPointAtLength(ratio * getOrCalculatePathTotalLength(this), inWorldSpace);
  8969. }
  8970. /**
  8971. * Get start tangent vector
  8972. */;
  8973. _proto.getStartTangent = function getStartTangent() {
  8974. var segments = this.parsedStyle.path.segments;
  8975. var result = [];
  8976. if (segments.length > 1) {
  8977. var startPoint = segments[0].currentPoint;
  8978. var endPoint = segments[1].currentPoint;
  8979. var tangent = segments[1].startTangent;
  8980. result = [];
  8981. if (tangent) {
  8982. result.push([startPoint[0] - tangent[0], startPoint[1] - tangent[1]]);
  8983. result.push([startPoint[0], startPoint[1]]);
  8984. } else {
  8985. result.push([endPoint[0], endPoint[1]]);
  8986. result.push([startPoint[0], startPoint[1]]);
  8987. }
  8988. }
  8989. return result;
  8990. }
  8991. /**
  8992. * Get end tangent vector
  8993. */;
  8994. _proto.getEndTangent = function getEndTangent() {
  8995. var segments = this.parsedStyle.path.segments;
  8996. var length = segments.length;
  8997. var result = [];
  8998. if (length > 1) {
  8999. var startPoint = segments[length - 2].currentPoint;
  9000. var endPoint = segments[length - 1].currentPoint;
  9001. var tangent = segments[length - 1].endTangent;
  9002. result = [];
  9003. if (tangent) {
  9004. result.push([endPoint[0] - tangent[0], endPoint[1] - tangent[1]]);
  9005. result.push([endPoint[0], endPoint[1]]);
  9006. } else {
  9007. result.push([startPoint[0], startPoint[1]]);
  9008. result.push([endPoint[0], endPoint[1]]);
  9009. }
  9010. }
  9011. return result;
  9012. };
  9013. return Path;
  9014. }(DisplayObject);
  9015. var _excluded$8 = ["style"];
  9016. var Polygon = /*#__PURE__*/function (_DisplayObject) {
  9017. _inheritsLoose(Polygon, _DisplayObject);
  9018. function Polygon(_temp) {
  9019. var _this;
  9020. var _ref = _temp === void 0 ? {} : _temp,
  9021. style = _ref.style,
  9022. rest = _objectWithoutPropertiesLoose(_ref, _excluded$8);
  9023. _this = _DisplayObject.call(this, _extends({
  9024. type: exports.Shape.POLYGON,
  9025. style: runtime.enableCSSParsing ? _extends({
  9026. points: '',
  9027. miterLimit: '',
  9028. isClosed: true
  9029. }, style) : _extends({}, style),
  9030. initialParsedStyle: runtime.enableCSSParsing ? null : {
  9031. points: {
  9032. points: [],
  9033. totalLength: 0,
  9034. segments: []
  9035. },
  9036. miterLimit: 4,
  9037. isClosed: true
  9038. }
  9039. }, rest)) || this;
  9040. _this.markerStartAngle = 0;
  9041. _this.markerEndAngle = 0;
  9042. /**
  9043. * markers placed at the mid
  9044. */
  9045. _this.markerMidList = [];
  9046. var _this$parsedStyle = _this.parsedStyle,
  9047. markerStart = _this$parsedStyle.markerStart,
  9048. markerEnd = _this$parsedStyle.markerEnd,
  9049. markerMid = _this$parsedStyle.markerMid;
  9050. if (markerStart && isDisplayObject(markerStart)) {
  9051. _this.markerStartAngle = markerStart.getLocalEulerAngles();
  9052. _this.appendChild(markerStart);
  9053. }
  9054. if (markerMid && isDisplayObject(markerMid)) {
  9055. _this.placeMarkerMid(markerMid);
  9056. }
  9057. if (markerEnd && isDisplayObject(markerEnd)) {
  9058. _this.markerEndAngle = markerEnd.getLocalEulerAngles();
  9059. _this.appendChild(markerEnd);
  9060. }
  9061. _this.transformMarker(true);
  9062. _this.transformMarker(false);
  9063. return _this;
  9064. }
  9065. var _proto = Polygon.prototype;
  9066. _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
  9067. if (attrName === 'points') {
  9068. // recalc markers
  9069. this.transformMarker(true);
  9070. this.transformMarker(false);
  9071. this.placeMarkerMid(this.parsedStyle.markerMid);
  9072. } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
  9073. this.transformMarker(true);
  9074. this.transformMarker(false);
  9075. } else if (attrName === 'markerStart') {
  9076. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  9077. this.markerStartAngle = 0;
  9078. prevParsedValue.remove();
  9079. }
  9080. // CSSKeyword 'unset'
  9081. if (newParsedValue && isDisplayObject(newParsedValue)) {
  9082. this.markerStartAngle = newParsedValue.getLocalEulerAngles();
  9083. this.appendChild(newParsedValue);
  9084. this.transformMarker(true);
  9085. }
  9086. } else if (attrName === 'markerEnd') {
  9087. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  9088. this.markerEndAngle = 0;
  9089. prevParsedValue.remove();
  9090. }
  9091. if (newParsedValue && isDisplayObject(newParsedValue)) {
  9092. this.markerEndAngle = newParsedValue.getLocalEulerAngles();
  9093. this.appendChild(newParsedValue);
  9094. this.transformMarker(false);
  9095. }
  9096. } else if (attrName === 'markerMid') {
  9097. this.placeMarkerMid(newParsedValue);
  9098. }
  9099. };
  9100. _proto.transformMarker = function transformMarker(isStart) {
  9101. var _this$parsedStyle2 = this.parsedStyle,
  9102. markerStart = _this$parsedStyle2.markerStart,
  9103. markerEnd = _this$parsedStyle2.markerEnd,
  9104. markerStartOffset = _this$parsedStyle2.markerStartOffset,
  9105. markerEndOffset = _this$parsedStyle2.markerEndOffset,
  9106. points = _this$parsedStyle2.points.points,
  9107. defX = _this$parsedStyle2.defX,
  9108. defY = _this$parsedStyle2.defY;
  9109. var marker = isStart ? markerStart : markerEnd;
  9110. if (!marker || !isDisplayObject(marker)) {
  9111. return;
  9112. }
  9113. var rad = 0;
  9114. var x;
  9115. var y;
  9116. var ox;
  9117. var oy;
  9118. var offset;
  9119. var originalAngle;
  9120. ox = points[0][0] - defX;
  9121. oy = points[0][1] - defY;
  9122. if (isStart) {
  9123. x = points[1][0] - points[0][0];
  9124. y = points[1][1] - points[0][1];
  9125. offset = markerStartOffset || 0;
  9126. originalAngle = this.markerStartAngle;
  9127. } else {
  9128. var length = points.length;
  9129. if (!this.parsedStyle.isClosed) {
  9130. ox = points[length - 1][0] - defX;
  9131. oy = points[length - 1][1] - defY;
  9132. x = points[length - 2][0] - points[length - 1][0];
  9133. y = points[length - 2][1] - points[length - 1][1];
  9134. } else {
  9135. x = points[length - 1][0] - points[0][0];
  9136. y = points[length - 1][1] - points[0][1];
  9137. }
  9138. offset = markerEndOffset || 0;
  9139. originalAngle = this.markerEndAngle;
  9140. }
  9141. rad = Math.atan2(y, x);
  9142. // account for markerOffset
  9143. marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
  9144. marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
  9145. };
  9146. _proto.placeMarkerMid = function placeMarkerMid(marker) {
  9147. var _this$parsedStyle3 = this.parsedStyle,
  9148. points = _this$parsedStyle3.points.points,
  9149. defX = _this$parsedStyle3.defX,
  9150. defY = _this$parsedStyle3.defY;
  9151. // clear all existed markers
  9152. this.markerMidList.forEach(function (marker) {
  9153. marker.remove();
  9154. });
  9155. this.markerMidList = [];
  9156. if (marker && isDisplayObject(marker)) {
  9157. for (var i = 1; i < (this.parsedStyle.isClosed ? points.length : points.length - 1); i++) {
  9158. var ox = points[i][0] - defX;
  9159. var oy = points[i][1] - defY;
  9160. var cloned = i === 1 ? marker : marker.cloneNode(true);
  9161. this.markerMidList.push(cloned);
  9162. this.appendChild(cloned);
  9163. cloned.setLocalPosition(ox, oy);
  9164. // TODO: orient of marker
  9165. }
  9166. }
  9167. };
  9168. return Polygon;
  9169. }(DisplayObject);
  9170. var _excluded$9 = ["style"];
  9171. /**
  9172. * Polyline inherits the marker-related capabilities of Polygon.
  9173. */
  9174. var Polyline = /*#__PURE__*/function (_Polygon) {
  9175. _inheritsLoose(Polyline, _Polygon);
  9176. function Polyline(_temp) {
  9177. var _ref = _temp === void 0 ? {} : _temp,
  9178. style = _ref.style,
  9179. rest = _objectWithoutPropertiesLoose(_ref, _excluded$9);
  9180. return _Polygon.call(this, _extends({
  9181. type: exports.Shape.POLYLINE,
  9182. style: runtime.enableCSSParsing ? _extends({
  9183. points: '',
  9184. miterLimit: '',
  9185. isClosed: false
  9186. }, style) : _extends({}, style),
  9187. initialParsedStyle: runtime.enableCSSParsing ? null : {
  9188. points: {
  9189. points: [],
  9190. totalLength: 0,
  9191. segments: []
  9192. },
  9193. miterLimit: 4,
  9194. isClosed: false
  9195. }
  9196. }, rest)) || this;
  9197. }
  9198. var _proto = Polyline.prototype;
  9199. _proto.getTotalLength = function getTotalLength() {
  9200. return this.parsedStyle.points.totalLength;
  9201. };
  9202. _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
  9203. if (inWorldSpace === void 0) {
  9204. inWorldSpace = false;
  9205. }
  9206. return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
  9207. };
  9208. _proto.getPoint = function getPoint(ratio, inWorldSpace) {
  9209. if (inWorldSpace === void 0) {
  9210. inWorldSpace = false;
  9211. }
  9212. var _this$parsedStyle = this.parsedStyle,
  9213. defX = _this$parsedStyle.defX,
  9214. defY = _this$parsedStyle.defY,
  9215. _this$parsedStyle$poi = _this$parsedStyle.points,
  9216. points = _this$parsedStyle$poi.points,
  9217. segments = _this$parsedStyle$poi.segments;
  9218. var subt = 0;
  9219. var index = 0;
  9220. segments.forEach(function (v, i) {
  9221. if (ratio >= v[0] && ratio <= v[1]) {
  9222. subt = (ratio - v[0]) / (v[1] - v[0]);
  9223. index = i;
  9224. }
  9225. });
  9226. var _LineUtil$pointAt = gMath.Line.pointAt(points[index][0], points[index][1], points[index + 1][0], points[index + 1][1], subt),
  9227. x = _LineUtil$pointAt.x,
  9228. y = _LineUtil$pointAt.y;
  9229. var transformed = glMatrix.vec3.transformMat4(glMatrix.vec3.create(), glMatrix.vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
  9230. // apply local transformation
  9231. return new Point(transformed[0], transformed[1]);
  9232. };
  9233. _proto.getStartTangent = function getStartTangent() {
  9234. var points = this.parsedStyle.points.points;
  9235. var result = [];
  9236. result.push([points[1][0], points[1][1]]);
  9237. result.push([points[0][0], points[0][1]]);
  9238. return result;
  9239. };
  9240. _proto.getEndTangent = function getEndTangent() {
  9241. var points = this.parsedStyle.points.points;
  9242. var l = points.length - 1;
  9243. var result = [];
  9244. result.push([points[l - 1][0], points[l - 1][1]]);
  9245. result.push([points[l][0], points[l][1]]);
  9246. return result;
  9247. };
  9248. return Polyline;
  9249. }(Polygon);
  9250. var _excluded$a = ["style"];
  9251. var Rect = /*#__PURE__*/function (_DisplayObject) {
  9252. _inheritsLoose(Rect, _DisplayObject);
  9253. function Rect(_temp) {
  9254. var _ref = _temp === void 0 ? {} : _temp,
  9255. style = _ref.style,
  9256. rest = _objectWithoutPropertiesLoose(_ref, _excluded$a);
  9257. return _DisplayObject.call(this, _extends({
  9258. type: exports.Shape.RECT,
  9259. style: runtime.enableCSSParsing ? _extends({
  9260. x: '',
  9261. y: '',
  9262. width: '',
  9263. height: '',
  9264. radius: ''
  9265. }, style) : _extends({}, style)
  9266. }, rest)) || this;
  9267. }
  9268. return Rect;
  9269. }(DisplayObject);
  9270. var _excluded$b = ["style"];
  9271. /**
  9272. * <text> @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextElement
  9273. */
  9274. var Text = /*#__PURE__*/function (_DisplayObject) {
  9275. _inheritsLoose(Text, _DisplayObject);
  9276. /**
  9277. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement#constants
  9278. */
  9279. // LENGTHADJUST_SPACING: number = 1;
  9280. // LENGTHADJUST_SPACINGANDGLYPHS: number = 2;
  9281. // LENGTHADJUST_UNKNOWN: number = 0;
  9282. function Text(_temp) {
  9283. var _ref = _temp === void 0 ? {} : _temp,
  9284. style = _ref.style,
  9285. rest = _objectWithoutPropertiesLoose(_ref, _excluded$b);
  9286. return _DisplayObject.call(this, _extends({
  9287. type: exports.Shape.TEXT,
  9288. style: runtime.enableCSSParsing ? _extends({
  9289. x: '',
  9290. y: '',
  9291. text: '',
  9292. fontSize: '',
  9293. fontFamily: '',
  9294. fontStyle: '',
  9295. fontWeight: '',
  9296. fontVariant: '',
  9297. textAlign: '',
  9298. textBaseline: '',
  9299. textTransform: '',
  9300. fill: 'black',
  9301. letterSpacing: '',
  9302. lineHeight: '',
  9303. miterLimit: '',
  9304. // whiteSpace: 'pre',
  9305. wordWrap: false,
  9306. wordWrapWidth: 0,
  9307. leading: 0,
  9308. dx: '',
  9309. dy: '',
  9310. isBillboard: false,
  9311. sizeAttenuation: true
  9312. }, style) : _extends({
  9313. fill: 'black'
  9314. }, style),
  9315. initialParsedStyle: runtime.enableCSSParsing ? {} : {
  9316. x: 0,
  9317. y: 0,
  9318. fontSize: 16,
  9319. fontFamily: 'sans-serif',
  9320. fontStyle: 'normal',
  9321. fontWeight: 'normal',
  9322. fontVariant: 'normal',
  9323. lineHeight: 0,
  9324. letterSpacing: 0,
  9325. textBaseline: 'alphabetic',
  9326. textAlign: 'start',
  9327. wordWrap: false,
  9328. wordWrapWidth: 0,
  9329. leading: 0,
  9330. dx: 0,
  9331. dy: 0,
  9332. isBillboard: false,
  9333. sizeAttenuation: true
  9334. }
  9335. }, rest)) || this;
  9336. }
  9337. // lengthAdjust: SVGAnimatedEnumeration;
  9338. // textLength: SVGAnimatedLength;
  9339. // getCharNumAtPosition(point?: DOMPointInit): number {
  9340. // throw new Error('Method not implemented.');
  9341. // }
  9342. /**
  9343. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement
  9344. */
  9345. var _proto = Text.prototype;
  9346. _proto.getComputedTextLength = function getComputedTextLength() {
  9347. var _this$parsedStyle$met;
  9348. return ((_this$parsedStyle$met = this.parsedStyle.metrics) === null || _this$parsedStyle$met === void 0 ? void 0 : _this$parsedStyle$met.maxLineWidth) || 0;
  9349. }
  9350. // getEndPositionOfChar(charnum: number): DOMPoint {
  9351. // throw new Error('Method not implemented.');
  9352. // }
  9353. // getExtentOfChar(charnum: number): DOMRect {
  9354. // throw new Error('Method not implemented.');
  9355. // }
  9356. // getNumberOfChars(): number {
  9357. // throw new Error('Method not implemented.');
  9358. // }
  9359. // getRotationOfChar(charnum: number): number {
  9360. // throw new Error('Method not implemented.');
  9361. // }
  9362. // getStartPositionOfChar(charnum: number): DOMPoint {
  9363. // throw new Error('Method not implemented.');
  9364. // }
  9365. // getSubStringLength(charnum: number, nchars: number): number {
  9366. // throw new Error('Method not implemented.');
  9367. // }
  9368. // selectSubString(charnum: number, nchars: number): void {
  9369. // throw new Error('Method not implemented.');
  9370. // }
  9371. ;
  9372. _proto.getLineBoundingRects = function getLineBoundingRects() {
  9373. var _this$parsedStyle$met2;
  9374. return ((_this$parsedStyle$met2 = this.parsedStyle.metrics) === null || _this$parsedStyle$met2 === void 0 ? void 0 : _this$parsedStyle$met2.lineMetrics) || [];
  9375. };
  9376. _proto.isOverflowing = function isOverflowing() {
  9377. return !!this.parsedStyle.isOverflowing;
  9378. };
  9379. return Text;
  9380. }(DisplayObject);
  9381. /**
  9382. * Blink used them in code generation(css_properties.json5)
  9383. */
  9384. var BUILT_IN_PROPERTIES = [{
  9385. /**
  9386. * used in CSS Layout API
  9387. * eg. `display: 'flex'`
  9388. */
  9389. n: 'display',
  9390. k: ['none']
  9391. }, {
  9392. /**
  9393. * range [0.0, 1.0]
  9394. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity
  9395. */
  9396. n: 'opacity',
  9397. int: true,
  9398. inh: true,
  9399. d: '1',
  9400. syntax: exports.PropertySyntax.OPACITY_VALUE
  9401. }, {
  9402. /**
  9403. * inheritable, range [0.0, 1.0]
  9404. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity
  9405. * @see https://svgwg.org/svg2-draft/painting.html#FillOpacity
  9406. */
  9407. n: 'fillOpacity',
  9408. int: true,
  9409. inh: true,
  9410. d: '1',
  9411. syntax: exports.PropertySyntax.OPACITY_VALUE
  9412. }, {
  9413. /**
  9414. * inheritable, range [0.0, 1.0]
  9415. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity
  9416. * @see https://svgwg.org/svg2-draft/painting.html#StrokeOpacity
  9417. */
  9418. n: 'strokeOpacity',
  9419. int: true,
  9420. inh: true,
  9421. d: '1',
  9422. syntax: exports.PropertySyntax.OPACITY_VALUE
  9423. }, {
  9424. /**
  9425. * background-color is not inheritable
  9426. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
  9427. */
  9428. n: 'fill',
  9429. int: true,
  9430. k: ['none'],
  9431. d: 'none',
  9432. syntax: exports.PropertySyntax.PAINT
  9433. }, {
  9434. n: 'fillRule',
  9435. k: ['nonzero', 'evenodd'],
  9436. d: 'nonzero'
  9437. },
  9438. /**
  9439. * default to none
  9440. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke#usage_notes
  9441. */
  9442. {
  9443. n: 'stroke',
  9444. int: true,
  9445. k: ['none'],
  9446. d: 'none',
  9447. syntax: exports.PropertySyntax.PAINT,
  9448. /**
  9449. * Stroke 'none' won't affect geometry but others will.
  9450. */
  9451. l: true
  9452. }, {
  9453. n: 'shadowType',
  9454. k: ['inner', 'outer', 'both'],
  9455. d: 'outer',
  9456. l: true
  9457. }, {
  9458. n: 'shadowColor',
  9459. int: true,
  9460. syntax: exports.PropertySyntax.COLOR
  9461. }, {
  9462. n: 'shadowOffsetX',
  9463. int: true,
  9464. l: true,
  9465. d: '0',
  9466. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9467. }, {
  9468. n: 'shadowOffsetY',
  9469. int: true,
  9470. l: true,
  9471. d: '0',
  9472. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9473. }, {
  9474. n: 'shadowBlur',
  9475. int: true,
  9476. l: true,
  9477. d: '0',
  9478. syntax: exports.PropertySyntax.SHADOW_BLUR
  9479. }, {
  9480. /**
  9481. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width
  9482. */
  9483. n: 'lineWidth',
  9484. int: true,
  9485. inh: true,
  9486. d: '1',
  9487. l: true,
  9488. a: ['strokeWidth'],
  9489. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9490. }, {
  9491. n: 'increasedLineWidthForHitTesting',
  9492. inh: true,
  9493. d: '0',
  9494. l: true,
  9495. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9496. }, {
  9497. n: 'lineJoin',
  9498. inh: true,
  9499. l: true,
  9500. a: ['strokeLinejoin'],
  9501. k: ['miter', 'bevel', 'round'],
  9502. d: 'miter'
  9503. }, {
  9504. n: 'lineCap',
  9505. inh: true,
  9506. l: true,
  9507. a: ['strokeLinecap'],
  9508. k: ['butt', 'round', 'square'],
  9509. d: 'butt'
  9510. }, {
  9511. n: 'lineDash',
  9512. int: true,
  9513. inh: true,
  9514. k: ['none'],
  9515. a: ['strokeDasharray'],
  9516. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE_12
  9517. }, {
  9518. n: 'lineDashOffset',
  9519. int: true,
  9520. inh: true,
  9521. d: '0',
  9522. a: ['strokeDashoffset'],
  9523. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9524. }, {
  9525. n: 'offsetPath',
  9526. syntax: exports.PropertySyntax.DEFINED_PATH
  9527. }, {
  9528. n: 'offsetDistance',
  9529. int: true,
  9530. syntax: exports.PropertySyntax.OFFSET_DISTANCE
  9531. }, {
  9532. n: 'dx',
  9533. int: true,
  9534. l: true,
  9535. d: '0',
  9536. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9537. }, {
  9538. n: 'dy',
  9539. int: true,
  9540. l: true,
  9541. d: '0',
  9542. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9543. }, {
  9544. n: 'zIndex',
  9545. ind: true,
  9546. int: true,
  9547. d: '0',
  9548. k: ['auto'],
  9549. syntax: exports.PropertySyntax.Z_INDEX
  9550. }, {
  9551. n: 'visibility',
  9552. k: ['visible', 'hidden'],
  9553. ind: true,
  9554. inh: true,
  9555. /**
  9556. * support interpolation
  9557. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#interpolation
  9558. */
  9559. int: true,
  9560. d: 'visible'
  9561. }, {
  9562. n: 'pointerEvents',
  9563. inh: true,
  9564. k: ['none', 'auto', 'stroke', 'fill', 'painted', 'visible', 'visiblestroke', 'visiblefill', 'visiblepainted',
  9565. // 'bounding-box',
  9566. 'all'],
  9567. d: 'auto'
  9568. }, {
  9569. n: 'filter',
  9570. ind: true,
  9571. l: true,
  9572. k: ['none'],
  9573. d: 'none',
  9574. syntax: exports.PropertySyntax.FILTER
  9575. }, {
  9576. n: 'clipPath',
  9577. syntax: exports.PropertySyntax.DEFINED_PATH
  9578. }, {
  9579. n: 'textPath',
  9580. syntax: exports.PropertySyntax.DEFINED_PATH
  9581. }, {
  9582. n: 'textPathSide',
  9583. k: ['left', 'right'],
  9584. d: 'left'
  9585. }, {
  9586. n: 'textPathStartOffset',
  9587. l: true,
  9588. d: '0',
  9589. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9590. }, {
  9591. n: 'transform',
  9592. p: 100,
  9593. int: true,
  9594. k: ['none'],
  9595. d: 'none',
  9596. syntax: exports.PropertySyntax.TRANSFORM
  9597. }, {
  9598. n: 'transformOrigin',
  9599. p: 100,
  9600. // int: true,
  9601. d: function d(nodeName) {
  9602. if (nodeName === exports.Shape.CIRCLE || nodeName === exports.Shape.ELLIPSE) {
  9603. return 'center';
  9604. }
  9605. if (nodeName === exports.Shape.TEXT) {
  9606. return 'text-anchor';
  9607. }
  9608. return 'left top';
  9609. },
  9610. l: true,
  9611. syntax: exports.PropertySyntax.TRANSFORM_ORIGIN
  9612. }, {
  9613. n: 'anchor',
  9614. p: 99,
  9615. d: function d(nodeName) {
  9616. if (nodeName === exports.Shape.CIRCLE || nodeName === exports.Shape.ELLIPSE) {
  9617. return '0.5 0.5';
  9618. }
  9619. return '0 0';
  9620. },
  9621. l: true,
  9622. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE_12
  9623. },
  9624. // <circle> & <ellipse>
  9625. {
  9626. n: 'cx',
  9627. int: true,
  9628. d: '0',
  9629. syntax: exports.PropertySyntax.COORDINATE
  9630. }, {
  9631. n: 'cy',
  9632. int: true,
  9633. d: '0',
  9634. syntax: exports.PropertySyntax.COORDINATE
  9635. }, {
  9636. n: 'cz',
  9637. int: true,
  9638. d: '0',
  9639. syntax: exports.PropertySyntax.COORDINATE
  9640. }, {
  9641. n: 'r',
  9642. int: true,
  9643. l: true,
  9644. d: '0',
  9645. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9646. }, {
  9647. n: 'rx',
  9648. int: true,
  9649. l: true,
  9650. d: '0',
  9651. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9652. }, {
  9653. n: 'ry',
  9654. int: true,
  9655. l: true,
  9656. d: '0',
  9657. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9658. },
  9659. // Rect Image Group
  9660. {
  9661. // x in local space
  9662. n: 'x',
  9663. int: true,
  9664. d: '0',
  9665. syntax: exports.PropertySyntax.COORDINATE
  9666. }, {
  9667. // y in local space
  9668. n: 'y',
  9669. int: true,
  9670. d: '0',
  9671. syntax: exports.PropertySyntax.COORDINATE
  9672. }, {
  9673. // z in local space
  9674. n: 'z',
  9675. int: true,
  9676. d: '0',
  9677. syntax: exports.PropertySyntax.COORDINATE
  9678. }, {
  9679. n: 'width',
  9680. int: true,
  9681. l: true,
  9682. /**
  9683. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
  9684. */
  9685. k: ['auto', 'fit-content', 'min-content', 'max-content'],
  9686. d: '0',
  9687. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9688. }, {
  9689. n: 'height',
  9690. int: true,
  9691. l: true,
  9692. /**
  9693. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/height
  9694. */
  9695. k: ['auto', 'fit-content', 'min-content', 'max-content'],
  9696. d: '0',
  9697. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9698. }, {
  9699. n: 'radius',
  9700. int: true,
  9701. l: true,
  9702. d: '0',
  9703. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE_14
  9704. },
  9705. // Line
  9706. {
  9707. n: 'x1',
  9708. int: true,
  9709. l: true,
  9710. syntax: exports.PropertySyntax.COORDINATE
  9711. }, {
  9712. n: 'y1',
  9713. int: true,
  9714. l: true,
  9715. syntax: exports.PropertySyntax.COORDINATE
  9716. }, {
  9717. n: 'z1',
  9718. int: true,
  9719. l: true,
  9720. syntax: exports.PropertySyntax.COORDINATE
  9721. }, {
  9722. n: 'x2',
  9723. int: true,
  9724. l: true,
  9725. syntax: exports.PropertySyntax.COORDINATE
  9726. }, {
  9727. n: 'y2',
  9728. int: true,
  9729. l: true,
  9730. syntax: exports.PropertySyntax.COORDINATE
  9731. }, {
  9732. n: 'z2',
  9733. int: true,
  9734. l: true,
  9735. syntax: exports.PropertySyntax.COORDINATE
  9736. },
  9737. // Path
  9738. {
  9739. n: 'path',
  9740. int: true,
  9741. l: true,
  9742. d: '',
  9743. a: ['d'],
  9744. syntax: exports.PropertySyntax.PATH,
  9745. p: 50
  9746. },
  9747. // Polyline & Polygon
  9748. {
  9749. n: 'points',
  9750. /**
  9751. * support interpolation
  9752. */
  9753. int: true,
  9754. l: true,
  9755. syntax: exports.PropertySyntax.LIST_OF_POINTS,
  9756. p: 50
  9757. },
  9758. // Text
  9759. {
  9760. n: 'text',
  9761. l: true,
  9762. d: '',
  9763. syntax: exports.PropertySyntax.TEXT,
  9764. p: 50
  9765. }, {
  9766. n: 'textTransform',
  9767. l: true,
  9768. inh: true,
  9769. k: ['capitalize', 'uppercase', 'lowercase', 'none'],
  9770. d: 'none',
  9771. syntax: exports.PropertySyntax.TEXT_TRANSFORM,
  9772. p: 51 // it must get parsed after text
  9773. }, {
  9774. n: 'font',
  9775. l: true
  9776. }, {
  9777. n: 'fontSize',
  9778. int: true,
  9779. inh: true,
  9780. /**
  9781. * @see https://www.w3schools.com/css/css_font_size.asp
  9782. */
  9783. d: '16px',
  9784. l: true,
  9785. syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
  9786. }, {
  9787. n: 'fontFamily',
  9788. l: true,
  9789. inh: true,
  9790. d: 'sans-serif'
  9791. }, {
  9792. n: 'fontStyle',
  9793. l: true,
  9794. inh: true,
  9795. k: ['normal', 'italic', 'oblique'],
  9796. d: 'normal'
  9797. }, {
  9798. n: 'fontWeight',
  9799. l: true,
  9800. inh: true,
  9801. k: ['normal', 'bold', 'bolder', 'lighter'],
  9802. d: 'normal'
  9803. }, {
  9804. n: 'fontVariant',
  9805. l: true,
  9806. inh: true,
  9807. k: ['normal', 'small-caps'],
  9808. d: 'normal'
  9809. }, {
  9810. n: 'lineHeight',
  9811. l: true,
  9812. syntax: exports.PropertySyntax.LENGTH,
  9813. int: true,
  9814. d: '0'
  9815. }, {
  9816. n: 'letterSpacing',
  9817. l: true,
  9818. syntax: exports.PropertySyntax.LENGTH,
  9819. int: true,
  9820. d: '0'
  9821. }, {
  9822. n: 'miterLimit',
  9823. l: true,
  9824. syntax: exports.PropertySyntax.NUMBER,
  9825. d: function d(nodeName) {
  9826. if (nodeName === exports.Shape.PATH || nodeName === exports.Shape.POLYGON || nodeName === exports.Shape.POLYLINE) {
  9827. return '4';
  9828. }
  9829. return '10';
  9830. }
  9831. }, {
  9832. n: 'wordWrap',
  9833. l: true
  9834. }, {
  9835. n: 'wordWrapWidth',
  9836. l: true
  9837. }, {
  9838. n: 'maxLines',
  9839. l: true
  9840. }, {
  9841. n: 'textOverflow',
  9842. l: true,
  9843. d: 'clip'
  9844. }, {
  9845. n: 'leading',
  9846. l: true
  9847. }, {
  9848. n: 'textBaseline',
  9849. l: true,
  9850. inh: true,
  9851. k: ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'],
  9852. d: 'alphabetic'
  9853. }, {
  9854. n: 'textAlign',
  9855. l: true,
  9856. inh: true,
  9857. k: ['start', 'center', 'middle', 'end', 'left', 'right'],
  9858. d: 'start'
  9859. },
  9860. // {
  9861. // n: 'whiteSpace',
  9862. // l: true,
  9863. // },
  9864. {
  9865. n: 'markerStart',
  9866. syntax: exports.PropertySyntax.MARKER
  9867. }, {
  9868. n: 'markerEnd',
  9869. syntax: exports.PropertySyntax.MARKER
  9870. }, {
  9871. n: 'markerMid',
  9872. syntax: exports.PropertySyntax.MARKER
  9873. }, {
  9874. n: 'markerStartOffset',
  9875. syntax: exports.PropertySyntax.LENGTH,
  9876. l: true,
  9877. int: true,
  9878. d: '0'
  9879. }, {
  9880. n: 'markerEndOffset',
  9881. syntax: exports.PropertySyntax.LENGTH,
  9882. l: true,
  9883. int: true,
  9884. d: '0'
  9885. }];
  9886. var GEOMETRY_ATTRIBUTE_NAMES = BUILT_IN_PROPERTIES.filter(function (n) {
  9887. return !!n.l;
  9888. }).map(function (n) {
  9889. return n.n;
  9890. });
  9891. var propertyMetadataCache = {};
  9892. var unresolvedProperties = new WeakMap();
  9893. // const uniqueAttributeSet = new Set<string>();
  9894. // const tmpVec3a = vec3.create();
  9895. // const tmpVec3b = vec3.create();
  9896. // const tmpVec3c = vec3.create();
  9897. var isPropertyResolved = function isPropertyResolved(object, name) {
  9898. var properties = unresolvedProperties.get(object);
  9899. if (!properties || properties.length === 0) {
  9900. return true;
  9901. }
  9902. return properties.includes(name);
  9903. };
  9904. var DefaultStyleValueRegistry = /*#__PURE__*/function () {
  9905. /**
  9906. * need recalc later
  9907. */
  9908. // dirty = false;
  9909. function DefaultStyleValueRegistry() {
  9910. var _this = this;
  9911. BUILT_IN_PROPERTIES.forEach(function (property) {
  9912. _this.registerMetadata(property);
  9913. });
  9914. }
  9915. var _proto = DefaultStyleValueRegistry.prototype;
  9916. _proto.registerMetadata = function registerMetadata(metadata) {
  9917. [metadata.n].concat(metadata.a || []).forEach(function (name) {
  9918. propertyMetadataCache[name] = metadata;
  9919. });
  9920. };
  9921. _proto.unregisterMetadata = function unregisterMetadata(name) {
  9922. delete propertyMetadataCache[name];
  9923. };
  9924. _proto.getPropertySyntax = function getPropertySyntax(syntax) {
  9925. return runtime.CSSPropertySyntaxFactory[syntax];
  9926. }
  9927. /**
  9928. * * parse value, eg.
  9929. * fill: 'red' => CSSRGB
  9930. * translateX: '10px' => CSSUnitValue { unit: 'px', value: 10 }
  9931. * fontSize: '2em' => { unit: 'px', value: 32 }
  9932. *
  9933. * * calculate used value
  9934. * * post process
  9935. */;
  9936. _proto.processProperties = function processProperties(object, attributes, options) {
  9937. var _this2 = this;
  9938. if (options === void 0) {
  9939. options = {
  9940. skipUpdateAttribute: false,
  9941. skipParse: false,
  9942. forceUpdateGeometry: false,
  9943. usedAttributes: []
  9944. };
  9945. }
  9946. if (!runtime.enableCSSParsing) {
  9947. Object.assign(object.attributes, attributes);
  9948. var _attributeNames = Object.keys(attributes);
  9949. // clipPath
  9950. var oldClipPath = object.parsedStyle.clipPath;
  9951. var oldOffsetPath = object.parsedStyle.offsetPath;
  9952. object.parsedStyle = Object.assign(object.parsedStyle, attributes);
  9953. var _needUpdateGeometry = !!options.forceUpdateGeometry;
  9954. if (!_needUpdateGeometry) {
  9955. for (var i = 0; i < GEOMETRY_ATTRIBUTE_NAMES.length; i++) {
  9956. if (GEOMETRY_ATTRIBUTE_NAMES[i] in attributes) {
  9957. _needUpdateGeometry = true;
  9958. break;
  9959. }
  9960. }
  9961. }
  9962. if (attributes.fill) {
  9963. object.parsedStyle.fill = parseColor(attributes.fill);
  9964. }
  9965. if (attributes.stroke) {
  9966. object.parsedStyle.stroke = parseColor(attributes.stroke);
  9967. }
  9968. if (attributes.shadowColor) {
  9969. object.parsedStyle.shadowColor = parseColor(attributes.shadowColor);
  9970. }
  9971. if (attributes.filter) {
  9972. object.parsedStyle.filter = parseFilter(attributes.filter);
  9973. }
  9974. // Rect
  9975. // @ts-ignore
  9976. if (!util.isNil(attributes.radius)) {
  9977. // @ts-ignore
  9978. object.parsedStyle.radius = parseDimensionArrayFormat(
  9979. // @ts-ignore
  9980. attributes.radius, 4);
  9981. }
  9982. // Polyline
  9983. if (!util.isNil(attributes.lineDash)) {
  9984. object.parsedStyle.lineDash = parseDimensionArrayFormat(attributes.lineDash, 2);
  9985. }
  9986. // @ts-ignore
  9987. if (attributes.points) {
  9988. // @ts-ignore
  9989. object.parsedStyle.points = parsePoints(attributes.points, object);
  9990. }
  9991. // Path
  9992. // @ts-ignore
  9993. if (attributes.path === '') {
  9994. object.parsedStyle.path = _extends({}, EMPTY_PARSED_PATH);
  9995. }
  9996. // @ts-ignore
  9997. if (attributes.path) {
  9998. object.parsedStyle.path = parsePath(
  9999. // @ts-ignore
  10000. attributes.path, object);
  10001. }
  10002. // Text
  10003. if (attributes.textTransform) {
  10004. runtime.CSSPropertySyntaxFactory['<text-transform>'].calculator(null, null, {
  10005. value: attributes.textTransform
  10006. }, object, null);
  10007. }
  10008. if (attributes.clipPath) {
  10009. runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('clipPath', oldClipPath, attributes.clipPath, object, this);
  10010. }
  10011. if (attributes.offsetPath) {
  10012. runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('offsetPath', oldOffsetPath, attributes.offsetPath, object, this);
  10013. }
  10014. if (attributes.anchor) {
  10015. object.parsedStyle.anchor = parseDimensionArrayFormat(
  10016. // @ts-ignorex
  10017. attributes.anchor, 2);
  10018. }
  10019. if (attributes.transform) {
  10020. object.parsedStyle.transform = parseTransform(attributes.transform);
  10021. }
  10022. if (attributes.transformOrigin) {
  10023. object.parsedStyle.transformOrigin = parseTransformOrigin(attributes.transformOrigin);
  10024. }
  10025. // Marker
  10026. // @ts-ignore
  10027. if (attributes.markerStart) {
  10028. // @ts-ignore
  10029. object.parsedStyle.markerStart = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
  10030. // @ts-ignore
  10031. attributes.markerStart,
  10032. // @ts-ignore
  10033. attributes.markerStart, null, null);
  10034. }
  10035. // @ts-ignore
  10036. if (attributes.markerEnd) {
  10037. // @ts-ignore
  10038. object.parsedStyle.markerEnd = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
  10039. // @ts-ignore
  10040. attributes.markerEnd,
  10041. // @ts-ignore
  10042. attributes.markerEnd, null, null);
  10043. }
  10044. // @ts-ignore
  10045. if (attributes.markerMid) {
  10046. // @ts-ignore
  10047. object.parsedStyle.markerMid = runtime.CSSPropertySyntaxFactory['<marker>'].calculator('',
  10048. // @ts-ignore
  10049. attributes.markerMid,
  10050. // @ts-ignore
  10051. attributes.markerMid, null, null);
  10052. }
  10053. if (
  10054. // Circle & Ellipse
  10055. (object.nodeName === exports.Shape.CIRCLE || object.nodeName === exports.Shape.ELLIPSE) && (
  10056. // @ts-ignore
  10057. !util.isNil(attributes.cx) ||
  10058. // @ts-ignore
  10059. !util.isNil(attributes.cy)) || (object.nodeName === exports.Shape.RECT || object.nodeName === exports.Shape.IMAGE || object.nodeName === exports.Shape.GROUP || object.nodeName === exports.Shape.HTML || object.nodeName === exports.Shape.TEXT || object.nodeName === exports.Shape.MESH) && (
  10060. // @ts-ignore
  10061. !util.isNil(attributes.x) ||
  10062. // @ts-ignore
  10063. !util.isNil(attributes.y) ||
  10064. // @ts-ignore
  10065. !util.isNil(attributes.z)) ||
  10066. // Line
  10067. object.nodeName === exports.Shape.LINE && (
  10068. // @ts-ignore
  10069. !util.isNil(attributes.x1) ||
  10070. // @ts-ignore
  10071. !util.isNil(attributes.y1) ||
  10072. // @ts-ignore
  10073. !util.isNil(attributes.z1) ||
  10074. // @ts-ignore
  10075. !util.isNil(attributes.x2) ||
  10076. // @ts-ignore
  10077. !util.isNil(attributes.y2) ||
  10078. // @ts-ignore
  10079. !util.isNil(attributes.z2))) {
  10080. runtime.CSSPropertySyntaxFactory['<coordinate>'].postProcessor(object, _attributeNames);
  10081. }
  10082. if (!util.isNil(attributes.zIndex)) {
  10083. runtime.CSSPropertySyntaxFactory['<z-index>'].postProcessor(object, _attributeNames);
  10084. }
  10085. // @ts-ignore
  10086. if (attributes.path) {
  10087. runtime.CSSPropertySyntaxFactory['<path>'].postProcessor(object, _attributeNames);
  10088. }
  10089. // @ts-ignore
  10090. if (attributes.points) {
  10091. runtime.CSSPropertySyntaxFactory['<list-of-points>'].postProcessor(object, _attributeNames);
  10092. }
  10093. if (!util.isNil(attributes.offsetDistance)) {
  10094. runtime.CSSPropertySyntaxFactory['<offset-distance>'].postProcessor(object, _attributeNames);
  10095. }
  10096. if (attributes.transform) {
  10097. runtime.CSSPropertySyntaxFactory['<transform>'].postProcessor(object, _attributeNames);
  10098. }
  10099. if (_needUpdateGeometry) {
  10100. this.updateGeometry(object);
  10101. }
  10102. return;
  10103. }
  10104. var _options = options,
  10105. skipUpdateAttribute = _options.skipUpdateAttribute,
  10106. skipParse = _options.skipParse,
  10107. forceUpdateGeometry = _options.forceUpdateGeometry,
  10108. usedAttributes = _options.usedAttributes;
  10109. var needUpdateGeometry = forceUpdateGeometry;
  10110. var attributeNames = Object.keys(attributes);
  10111. attributeNames.forEach(function (attributeName) {
  10112. var _propertyMetadataCach;
  10113. if (!skipUpdateAttribute) {
  10114. object.attributes[attributeName] = attributes[attributeName];
  10115. }
  10116. if (!needUpdateGeometry && ((_propertyMetadataCach = propertyMetadataCache[attributeName]) === null || _propertyMetadataCach === void 0 ? void 0 : _propertyMetadataCach.l)) {
  10117. needUpdateGeometry = true;
  10118. }
  10119. });
  10120. if (!skipParse) {
  10121. attributeNames.forEach(function (name) {
  10122. object.computedStyle[name] = _this2.parseProperty(name, object.attributes[name], object);
  10123. });
  10124. }
  10125. // let hasUnresolvedProperties = false;
  10126. // parse according to priority
  10127. // path 50
  10128. // points 50
  10129. // text 50
  10130. // textTransform 51
  10131. // anchor 99
  10132. // transform 100
  10133. // transformOrigin 100
  10134. if (usedAttributes === null || usedAttributes === void 0 ? void 0 : usedAttributes.length) {
  10135. // uniqueAttributeSet.clear();
  10136. attributeNames = Array.from(new Set(attributeNames.concat(usedAttributes)));
  10137. }
  10138. // [
  10139. // 'path',
  10140. // 'points',
  10141. // 'text',
  10142. // 'textTransform',
  10143. // 'anchor',
  10144. // 'transform',
  10145. // 'transformOrigin',
  10146. // ].forEach((name) => {
  10147. // const index = attributeNames.indexOf(name);
  10148. // if (index > -1) {
  10149. // attributeNames.splice(index, 1);
  10150. // attributeNames.push(name);
  10151. // }
  10152. // });
  10153. attributeNames.forEach(function (name) {
  10154. // some style props maybe deleted after parsing such as `anchor` in Text
  10155. if (name in object.computedStyle) {
  10156. object.parsedStyle[name] = _this2.computeProperty(name, object.computedStyle[name], object);
  10157. }
  10158. });
  10159. // if (hasUnresolvedProperties) {
  10160. // this.dirty = true;
  10161. // return;
  10162. // }
  10163. // update geometry
  10164. if (needUpdateGeometry) {
  10165. // object.geometry.dirty = true;
  10166. // runtime.sceneGraphService.dirtifyToRoot(object);
  10167. this.updateGeometry(object);
  10168. }
  10169. attributeNames.forEach(function (name) {
  10170. if (name in object.parsedStyle) {
  10171. _this2.postProcessProperty(name, object, attributeNames);
  10172. }
  10173. });
  10174. if (runtime.enableCSSParsing && object.children.length) {
  10175. attributeNames.forEach(function (name) {
  10176. if (name in object.parsedStyle && _this2.isPropertyInheritable(name)) {
  10177. // update children's inheritable
  10178. object.children.forEach(function (child) {
  10179. child.internalSetAttribute(name, null, {
  10180. skipUpdateAttribute: true,
  10181. skipParse: true
  10182. });
  10183. });
  10184. }
  10185. });
  10186. }
  10187. }
  10188. /**
  10189. * string -> parsed value
  10190. */;
  10191. _proto.parseProperty = function parseProperty(name, value, object) {
  10192. var metadata = propertyMetadataCache[name];
  10193. var computed = value;
  10194. if (value === '' || util.isNil(value)) {
  10195. value = 'unset';
  10196. }
  10197. if (value === 'unset' || value === 'initial' || value === 'inherit') {
  10198. // computed = new CSSKeywordValue(value);
  10199. computed = getOrCreateKeyword(value);
  10200. } else {
  10201. if (metadata) {
  10202. var keywords = metadata.k,
  10203. syntax = metadata.syntax;
  10204. var handler = syntax && this.getPropertySyntax(syntax);
  10205. // use keywords
  10206. if (keywords && keywords.indexOf(value) > -1) {
  10207. // computed = new CSSKeywordValue(value);
  10208. computed = getOrCreateKeyword(value);
  10209. } else if (handler && handler.parser) {
  10210. // try to parse it to CSSStyleValue, eg. '10px' -> CSS.px(10)
  10211. computed = handler.parser(value, object);
  10212. }
  10213. }
  10214. }
  10215. return computed;
  10216. }
  10217. /**
  10218. * computed value -> used value
  10219. */;
  10220. _proto.computeProperty = function computeProperty(name, computed, object) {
  10221. var metadata = propertyMetadataCache[name];
  10222. var isDocumentElement = object.id === 'g-root';
  10223. // let used: CSSStyleValue = computed instanceof CSSStyleValue ? computed.clone() : computed;
  10224. var used = computed;
  10225. if (metadata) {
  10226. var syntax = metadata.syntax,
  10227. inherited = metadata.inh,
  10228. defaultValue = metadata.d;
  10229. if (computed instanceof CSSKeywordValue) {
  10230. var value = computed.value;
  10231. /**
  10232. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/unset
  10233. */
  10234. if (value === 'unset') {
  10235. if (inherited && !isDocumentElement) {
  10236. value = 'inherit';
  10237. } else {
  10238. value = 'initial';
  10239. }
  10240. }
  10241. if (value === 'initial') {
  10242. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial
  10243. if (!util.isNil(defaultValue)) {
  10244. computed = this.parseProperty(name, isFunction(defaultValue) ? defaultValue(object.nodeName) : defaultValue, object);
  10245. }
  10246. } else if (value === 'inherit') {
  10247. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/inherit
  10248. // behave like `inherit`
  10249. var resolved = this.tryToResolveProperty(object, name, {
  10250. inherited: true
  10251. });
  10252. if (!util.isNil(resolved)) {
  10253. // object.parsedStyle[name] = resolved;
  10254. // return false;
  10255. return resolved;
  10256. } else {
  10257. this.addUnresolveProperty(object, name);
  10258. return;
  10259. }
  10260. }
  10261. }
  10262. var handler = syntax && this.getPropertySyntax(syntax);
  10263. if (handler && handler.calculator) {
  10264. // convert computed value to used value
  10265. var oldParsedValue = object.parsedStyle[name];
  10266. used = handler.calculator(name, oldParsedValue, computed, object, this);
  10267. } else if (computed instanceof CSSKeywordValue) {
  10268. used = computed.value;
  10269. } else {
  10270. used = computed;
  10271. }
  10272. }
  10273. // object.parsedStyle[name] = used;
  10274. // return false;
  10275. return used;
  10276. };
  10277. _proto.postProcessProperty = function postProcessProperty(name, object, attributes) {
  10278. var metadata = propertyMetadataCache[name];
  10279. if (metadata && metadata.syntax) {
  10280. var handler = metadata.syntax && this.getPropertySyntax(metadata.syntax);
  10281. var propertyHandler = handler;
  10282. if (propertyHandler && propertyHandler.postProcessor) {
  10283. propertyHandler.postProcessor(object, attributes);
  10284. }
  10285. }
  10286. }
  10287. /**
  10288. * resolve later
  10289. */;
  10290. _proto.addUnresolveProperty = function addUnresolveProperty(object, name) {
  10291. var properties = unresolvedProperties.get(object);
  10292. if (!properties) {
  10293. unresolvedProperties.set(object, []);
  10294. properties = unresolvedProperties.get(object);
  10295. }
  10296. if (properties.indexOf(name) === -1) {
  10297. properties.push(name);
  10298. }
  10299. };
  10300. _proto.tryToResolveProperty = function tryToResolveProperty(object, name, options) {
  10301. if (options === void 0) {
  10302. options = {};
  10303. }
  10304. var _options2 = options,
  10305. inherited = _options2.inherited;
  10306. if (inherited) {
  10307. if (object.parentElement && isPropertyResolved(object.parentElement, name)) {
  10308. // const computedValue = object.parentElement.computedStyle[name];
  10309. var usedValue = object.parentElement.parsedStyle[name];
  10310. if (
  10311. // usedValue instanceof CSSKeywordValue &&
  10312. usedValue === 'unset' || usedValue === 'initial' || usedValue === 'inherit') {
  10313. return;
  10314. }
  10315. // else if (
  10316. // usedValue instanceof CSSUnitValue &&
  10317. // CSSUnitValue.isRelativeUnit(usedValue.unit)
  10318. // ) {
  10319. // return false;
  10320. // }
  10321. return usedValue;
  10322. }
  10323. }
  10324. return;
  10325. };
  10326. _proto.recalc = function recalc(object) {
  10327. var properties = unresolvedProperties.get(object);
  10328. if (properties && properties.length) {
  10329. var attributes = {};
  10330. properties.forEach(function (property) {
  10331. attributes[property] = object.attributes[property];
  10332. });
  10333. this.processProperties(object, attributes);
  10334. unresolvedProperties.delete(object);
  10335. }
  10336. }
  10337. /**
  10338. * update geometry when relative props changed,
  10339. * eg. r of Circle, width/height of Rect
  10340. */;
  10341. _proto.updateGeometry = function updateGeometry(object) {
  10342. var nodeName = object.nodeName;
  10343. var geometryUpdater = runtime.geometryUpdaterFactory[nodeName];
  10344. if (geometryUpdater) {
  10345. var geometry = object.geometry;
  10346. if (!geometry.contentBounds) {
  10347. geometry.contentBounds = new AABB();
  10348. }
  10349. if (!geometry.renderBounds) {
  10350. geometry.renderBounds = new AABB();
  10351. }
  10352. var parsedStyle = object.parsedStyle;
  10353. var _geometryUpdater$upda = geometryUpdater.update(parsedStyle, object),
  10354. width = _geometryUpdater$upda.width,
  10355. height = _geometryUpdater$upda.height,
  10356. _geometryUpdater$upda2 = _geometryUpdater$upda.depth,
  10357. depth = _geometryUpdater$upda2 === void 0 ? 0 : _geometryUpdater$upda2,
  10358. _geometryUpdater$upda3 = _geometryUpdater$upda.offsetX,
  10359. offsetX = _geometryUpdater$upda3 === void 0 ? 0 : _geometryUpdater$upda3,
  10360. _geometryUpdater$upda4 = _geometryUpdater$upda.offsetY,
  10361. offsetY = _geometryUpdater$upda4 === void 0 ? 0 : _geometryUpdater$upda4,
  10362. _geometryUpdater$upda5 = _geometryUpdater$upda.offsetZ,
  10363. offsetZ = _geometryUpdater$upda5 === void 0 ? 0 : _geometryUpdater$upda5;
  10364. // init with content box
  10365. var halfExtents = [Math.abs(width) / 2, Math.abs(height) / 2, depth / 2];
  10366. // const halfExtents = vec3.set(
  10367. // tmpVec3a,
  10368. // Math.abs(width) / 2,
  10369. // Math.abs(height) / 2,
  10370. // depth / 2,
  10371. // );
  10372. // anchor is center by default, don't account for lineWidth here
  10373. var stroke = parsedStyle.stroke,
  10374. lineWidth = parsedStyle.lineWidth,
  10375. increasedLineWidthForHitTesting = parsedStyle.increasedLineWidthForHitTesting,
  10376. shadowType = parsedStyle.shadowType,
  10377. shadowColor = parsedStyle.shadowColor,
  10378. _parsedStyle$filter = parsedStyle.filter,
  10379. filter = _parsedStyle$filter === void 0 ? [] : _parsedStyle$filter,
  10380. transformOrigin = parsedStyle.transformOrigin;
  10381. var anchor = parsedStyle.anchor;
  10382. // <Text> use textAlign & textBaseline instead of anchor
  10383. if (nodeName === exports.Shape.TEXT) {
  10384. delete parsedStyle.anchor;
  10385. } else if (nodeName === exports.Shape.MESH) {
  10386. parsedStyle.anchor[2] = 0.5;
  10387. }
  10388. var center = [(1 - (anchor && anchor[0] || 0) * 2) * width / 2 + offsetX, (1 - (anchor && anchor[1] || 0) * 2) * height / 2 + offsetY, (1 - (anchor && anchor[2] || 0) * 2) * halfExtents[2] + offsetZ];
  10389. // const center = vec3.set(
  10390. // tmpVec3b,
  10391. // ((1 - ((anchor && anchor[0]) || 0) * 2) * width) / 2 + offsetX,
  10392. // ((1 - ((anchor && anchor[1]) || 0) * 2) * height) / 2 + offsetY,
  10393. // (1 - ((anchor && anchor[2]) || 0) * 2) * halfExtents[2] + offsetZ,
  10394. // );
  10395. // update geometry's AABB
  10396. geometry.contentBounds.update(center, halfExtents);
  10397. // @see https://github.molgen.mpg.de/git-mirror/cairo/blob/master/src/cairo-stroke-style.c#L97..L128
  10398. var expansion = nodeName === exports.Shape.POLYLINE || nodeName === exports.Shape.POLYGON || nodeName === exports.Shape.PATH ? Math.SQRT2 : 0.5;
  10399. // if (lineCap?.value === 'square') {
  10400. // expansion = Math.SQRT1_2;
  10401. // }
  10402. // if (lineJoin?.value === 'miter' && expansion < Math.SQRT2 * miterLimit) {
  10403. // expansion = Math.SQRT1_2 * miterLimit;
  10404. // }
  10405. // append border only if stroke existed
  10406. var hasStroke = stroke && !stroke.isNone;
  10407. if (hasStroke) {
  10408. var halfLineWidth = ((lineWidth || 0) + (increasedLineWidthForHitTesting || 0)) * expansion;
  10409. // halfExtents[0] += halfLineWidth[0];
  10410. // halfExtents[1] += halfLineWidth[1];
  10411. halfExtents[0] += halfLineWidth;
  10412. halfExtents[1] += halfLineWidth;
  10413. // vec3.add(
  10414. // halfExtents,
  10415. // halfExtents,
  10416. // vec3.set(tmpVec3c, halfLineWidth, halfLineWidth, 0),
  10417. // );
  10418. }
  10419. geometry.renderBounds.update(center, halfExtents);
  10420. // account for shadow, only support constant value now
  10421. if (shadowColor && shadowType && shadowType !== 'inner') {
  10422. var _geometry$renderBound = geometry.renderBounds,
  10423. min = _geometry$renderBound.min,
  10424. max = _geometry$renderBound.max;
  10425. var shadowBlur = parsedStyle.shadowBlur,
  10426. shadowOffsetX = parsedStyle.shadowOffsetX,
  10427. shadowOffsetY = parsedStyle.shadowOffsetY;
  10428. var shadowBlurInPixels = shadowBlur || 0;
  10429. var shadowOffsetXInPixels = shadowOffsetX || 0;
  10430. var shadowOffsetYInPixels = shadowOffsetY || 0;
  10431. var shadowLeft = min[0] - shadowBlurInPixels + shadowOffsetXInPixels;
  10432. var shadowRight = max[0] + shadowBlurInPixels + shadowOffsetXInPixels;
  10433. var shadowTop = min[1] - shadowBlurInPixels + shadowOffsetYInPixels;
  10434. var shadowBottom = max[1] + shadowBlurInPixels + shadowOffsetYInPixels;
  10435. min[0] = Math.min(min[0], shadowLeft);
  10436. max[0] = Math.max(max[0], shadowRight);
  10437. min[1] = Math.min(min[1], shadowTop);
  10438. max[1] = Math.max(max[1], shadowBottom);
  10439. geometry.renderBounds.setMinMax(min, max);
  10440. }
  10441. // account for filter, eg. blur(5px), drop-shadow()
  10442. filter.forEach(function (_ref) {
  10443. var name = _ref.name,
  10444. params = _ref.params;
  10445. if (name === 'blur') {
  10446. var blurRadius = params[0].value;
  10447. geometry.renderBounds.update(geometry.renderBounds.center, addVec3(geometry.renderBounds.halfExtents, geometry.renderBounds.halfExtents, [blurRadius, blurRadius, 0]));
  10448. } else if (name === 'drop-shadow') {
  10449. var _shadowOffsetX = params[0].value;
  10450. var _shadowOffsetY = params[1].value;
  10451. var _shadowBlur = params[2].value;
  10452. var _geometry$renderBound2 = geometry.renderBounds,
  10453. _min = _geometry$renderBound2.min,
  10454. _max = _geometry$renderBound2.max;
  10455. var _shadowLeft = _min[0] - _shadowBlur + _shadowOffsetX;
  10456. var _shadowRight = _max[0] + _shadowBlur + _shadowOffsetX;
  10457. var _shadowTop = _min[1] - _shadowBlur + _shadowOffsetY;
  10458. var _shadowBottom = _max[1] + _shadowBlur + _shadowOffsetY;
  10459. _min[0] = Math.min(_min[0], _shadowLeft);
  10460. _max[0] = Math.max(_max[0], _shadowRight);
  10461. _min[1] = Math.min(_min[1], _shadowTop);
  10462. _max[1] = Math.max(_max[1], _shadowBottom);
  10463. geometry.renderBounds.setMinMax(_min, _max);
  10464. }
  10465. });
  10466. anchor = parsedStyle.anchor;
  10467. // if (nodeName === Shape.RECT) {
  10468. // account for negative width / height of Rect
  10469. // @see https://github.com/antvis/g/issues/957
  10470. var flipY = width < 0;
  10471. var flipX = height < 0;
  10472. // } else {
  10473. // }
  10474. // set transform origin
  10475. var usedOriginXValue = (flipY ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[0], 0, object) : 0);
  10476. var usedOriginYValue = (flipX ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[1], 1, object) : 0);
  10477. usedOriginXValue = usedOriginXValue - (flipY ? -1 : 1) * (anchor && anchor[0] || 0) * geometry.contentBounds.halfExtents[0] * 2;
  10478. usedOriginYValue = usedOriginYValue - (flipX ? -1 : 1) * (anchor && anchor[1] || 0) * geometry.contentBounds.halfExtents[1] * 2;
  10479. object.setOrigin(usedOriginXValue, usedOriginYValue);
  10480. // FIXME setOrigin may have already dirtified to root.
  10481. runtime.sceneGraphService.dirtifyToRoot(object);
  10482. }
  10483. };
  10484. _proto.isPropertyInheritable = function isPropertyInheritable(name) {
  10485. var metadata = propertyMetadataCache[name];
  10486. if (!metadata) {
  10487. return false;
  10488. }
  10489. return metadata.inh;
  10490. };
  10491. return DefaultStyleValueRegistry;
  10492. }();
  10493. /**
  10494. * Different type of cameras, eg. simple camera used in 2D scene or
  10495. * advanced camera which can do actions & switch between landmarks.
  10496. */
  10497. (function (CameraType) {
  10498. /**
  10499. * Performs all the rotational operations with the focal point instead of the camera position.
  10500. * This type of camera is useful in applications(like CAD) where 3D objects are being designed or explored.
  10501. * Camera cannot orbits over the north & south poles.
  10502. * @see http://voxelent.com/tutorial-cameras/
  10503. *
  10504. * In Three.js it's used in OrbitControls.
  10505. * @see https://threejs.org/docs/#examples/zh/controls/OrbitControls
  10506. */
  10507. CameraType[CameraType["ORBITING"] = 0] = "ORBITING";
  10508. /**
  10509. * It's similar to the ORBITING camera, but it allows the camera to orbit over the north or south poles.
  10510. *
  10511. * In Three.js it's used in OrbitControls.
  10512. * @see https://threejs.org/docs/#examples/en/controls/TrackballControls
  10513. */
  10514. CameraType[CameraType["EXPLORING"] = 1] = "EXPLORING";
  10515. /**
  10516. * Performs all the rotational operations with the camera position.
  10517. * It's useful in first person shooting games.
  10518. * Camera cannot orbits over the north & south poles.
  10519. *
  10520. * In Three.js it's used in FirstPersonControls.
  10521. * @see https://threejs.org/docs/#examples/en/controls/FirstPersonControls
  10522. */
  10523. CameraType[CameraType["TRACKING"] = 2] = "TRACKING";
  10524. })(exports.CameraType || (exports.CameraType = {}));
  10525. (function (CameraTrackingMode) {
  10526. CameraTrackingMode[CameraTrackingMode["DEFAULT"] = 0] = "DEFAULT";
  10527. CameraTrackingMode[CameraTrackingMode["ROTATIONAL"] = 1] = "ROTATIONAL";
  10528. CameraTrackingMode[CameraTrackingMode["TRANSLATIONAL"] = 2] = "TRANSLATIONAL";
  10529. CameraTrackingMode[CameraTrackingMode["CINEMATIC"] = 3] = "CINEMATIC";
  10530. })(exports.CameraTrackingMode || (exports.CameraTrackingMode = {}));
  10531. (function (CameraProjectionMode) {
  10532. CameraProjectionMode[CameraProjectionMode["ORTHOGRAPHIC"] = 0] = "ORTHOGRAPHIC";
  10533. CameraProjectionMode[CameraProjectionMode["PERSPECTIVE"] = 1] = "PERSPECTIVE";
  10534. })(exports.CameraProjectionMode || (exports.CameraProjectionMode = {}));
  10535. var CameraEvent = {
  10536. UPDATED: 'updated'
  10537. };
  10538. var MIN_DISTANCE = 0.0002;
  10539. /**
  10540. * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计
  10541. * @see https://github.com/d13g0/nucleo.js/blob/master/source/camera/Camera.js
  10542. *
  10543. * 保存相机参数,定义相机动作:
  10544. * 1. dolly 沿 n 轴移动
  10545. * 2. pan 沿 u v 轴移动
  10546. * 3. rotate 以方位角旋转
  10547. * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互
  10548. */
  10549. var Camera = /*#__PURE__*/function () {
  10550. function Camera() {
  10551. this.canvas = void 0;
  10552. this.eventEmitter = new EventEmitter__default['default']();
  10553. /**
  10554. * 相机矩阵
  10555. */
  10556. this.matrix = glMatrix.mat4.create();
  10557. /**
  10558. * u 轴
  10559. * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition
  10560. */
  10561. this.right = glMatrix.vec3.fromValues(1, 0, 0);
  10562. /**
  10563. * v 轴 +Y is down
  10564. */
  10565. this.up = glMatrix.vec3.fromValues(0, 1, 0);
  10566. /**
  10567. * n 轴 +Z is inside
  10568. */
  10569. this.forward = glMatrix.vec3.fromValues(0, 0, 1);
  10570. /**
  10571. * 相机位置
  10572. */
  10573. this.position = glMatrix.vec3.fromValues(0, 0, 1);
  10574. /**
  10575. * 视点位置
  10576. */
  10577. this.focalPoint = glMatrix.vec3.fromValues(0, 0, 0);
  10578. /**
  10579. * 视点到相机位置的向量
  10580. * focalPoint - position
  10581. */
  10582. this.distanceVector = glMatrix.vec3.fromValues(0, 0, -1);
  10583. /**
  10584. * 相机位置到视点距离
  10585. * length(focalPoint - position)
  10586. */
  10587. this.distance = 1;
  10588. /**
  10589. * @see https://en.wikipedia.org/wiki/Azimuth
  10590. */
  10591. this.azimuth = 0;
  10592. this.elevation = 0;
  10593. this.roll = 0;
  10594. this.relAzimuth = 0;
  10595. this.relElevation = 0;
  10596. this.relRoll = 0;
  10597. /**
  10598. * 沿 n 轴移动时,保证移动速度从快到慢
  10599. */
  10600. this.dollyingStep = 0;
  10601. this.maxDistance = Infinity;
  10602. this.minDistance = -Infinity;
  10603. /**
  10604. * zoom factor of the camera, default is 1
  10605. * eg. https://threejs.org/docs/#api/en/cameras/OrthographicCamera.zoom
  10606. */
  10607. this.zoom = 1;
  10608. /**
  10609. * invert the horizontal coordinate system HCS
  10610. */
  10611. this.rotateWorld = false;
  10612. /**
  10613. * 投影矩阵参数
  10614. */
  10615. /**
  10616. * field of view [0-360]
  10617. * @see http://en.wikipedia.org/wiki/Angle_of_view
  10618. */
  10619. this.fov = 30;
  10620. this.near = 0.1;
  10621. this.far = 1000;
  10622. this.aspect = 1;
  10623. this.left = void 0;
  10624. this.rright = void 0;
  10625. this.top = void 0;
  10626. this.bottom = void 0;
  10627. this.projectionMatrix = glMatrix.mat4.create();
  10628. this.projectionMatrixInverse = glMatrix.mat4.create();
  10629. this.jitteredProjectionMatrix = undefined;
  10630. this.view = void 0;
  10631. this.enableUpdate = true;
  10632. // protected following = undefined;
  10633. this.type = exports.CameraType.EXPLORING;
  10634. this.trackingMode = exports.CameraTrackingMode.DEFAULT;
  10635. this.projectionMode = exports.CameraProjectionMode.PERSPECTIVE;
  10636. /**
  10637. * for culling use
  10638. */
  10639. this.frustum = new Frustum();
  10640. /**
  10641. * ortho matrix for Canvas2D & SVG
  10642. */
  10643. this.orthoMatrix = glMatrix.mat4.create();
  10644. }
  10645. var _proto = Camera.prototype;
  10646. // constructor(type = CameraType.EXPLORING, trackingMode = CameraTrackingMode.DEFAULT) {
  10647. // this.setType(type, trackingMode);
  10648. // }
  10649. _proto.isOrtho = function isOrtho() {
  10650. return this.projectionMode === exports.CameraProjectionMode.ORTHOGRAPHIC;
  10651. };
  10652. _proto.getProjectionMode = function getProjectionMode() {
  10653. return this.projectionMode;
  10654. };
  10655. _proto.getPerspective = function getPerspective() {
  10656. // account for TAA
  10657. return this.jitteredProjectionMatrix || this.projectionMatrix;
  10658. };
  10659. _proto.getPerspectiveInverse = function getPerspectiveInverse() {
  10660. return this.projectionMatrixInverse;
  10661. };
  10662. _proto.getFrustum = function getFrustum() {
  10663. return this.frustum;
  10664. };
  10665. _proto.getPosition = function getPosition() {
  10666. return this.position;
  10667. };
  10668. _proto.getFocalPoint = function getFocalPoint() {
  10669. return this.focalPoint;
  10670. };
  10671. _proto.getDollyingStep = function getDollyingStep() {
  10672. return this.dollyingStep;
  10673. };
  10674. _proto.getNear = function getNear() {
  10675. return this.near;
  10676. };
  10677. _proto.getFar = function getFar() {
  10678. return this.far;
  10679. };
  10680. _proto.getZoom = function getZoom() {
  10681. return this.zoom;
  10682. };
  10683. _proto.getOrthoMatrix = function getOrthoMatrix() {
  10684. return this.orthoMatrix;
  10685. };
  10686. _proto.getView = function getView() {
  10687. return this.view;
  10688. };
  10689. _proto.setEnableUpdate = function setEnableUpdate(enabled) {
  10690. this.enableUpdate = enabled;
  10691. };
  10692. _proto.setType = function setType(type, trackingMode) {
  10693. this.type = type;
  10694. if (this.type === exports.CameraType.EXPLORING) {
  10695. this.setWorldRotation(true);
  10696. } else {
  10697. this.setWorldRotation(false);
  10698. }
  10699. this._getAngles();
  10700. if (this.type === exports.CameraType.TRACKING && trackingMode !== undefined) {
  10701. this.setTrackingMode(trackingMode);
  10702. }
  10703. return this;
  10704. };
  10705. _proto.setProjectionMode = function setProjectionMode(projectionMode) {
  10706. this.projectionMode = projectionMode;
  10707. return this;
  10708. };
  10709. _proto.setTrackingMode = function setTrackingMode(trackingMode) {
  10710. if (this.type !== exports.CameraType.TRACKING) {
  10711. throw new Error('Impossible to set a tracking mode if the camera is not of tracking type');
  10712. }
  10713. this.trackingMode = trackingMode;
  10714. return this;
  10715. }
  10716. /**
  10717. * If flag is true, it reverses the azimuth and elevation angles.
  10718. * Subsequent calls to rotate, setAzimuth, setElevation,
  10719. * changeAzimuth or changeElevation will cause the inverted effect.
  10720. * setRoll or changeRoll is not affected by this method.
  10721. *
  10722. * This inversion is useful when one wants to simulate that the world
  10723. * is moving, instead of the camera.
  10724. *
  10725. * By default the camera angles are not reversed.
  10726. * @param {Boolean} flag the boolean flag to reverse the angles.
  10727. */;
  10728. _proto.setWorldRotation = function setWorldRotation(flag) {
  10729. this.rotateWorld = flag;
  10730. this._getAngles();
  10731. return this;
  10732. }
  10733. /**
  10734. * 计算 MV 矩阵,为相机矩阵的逆矩阵
  10735. */;
  10736. _proto.getViewTransform = function getViewTransform() {
  10737. return glMatrix.mat4.invert(glMatrix.mat4.create(), this.matrix);
  10738. };
  10739. _proto.getWorldTransform = function getWorldTransform() {
  10740. return this.matrix;
  10741. };
  10742. _proto.jitterProjectionMatrix = function jitterProjectionMatrix(x, y) {
  10743. var translation = glMatrix.mat4.fromTranslation(glMatrix.mat4.create(), [x, y, 0]);
  10744. this.jitteredProjectionMatrix = glMatrix.mat4.multiply(glMatrix.mat4.create(), translation, this.projectionMatrix);
  10745. };
  10746. _proto.clearJitterProjectionMatrix = function clearJitterProjectionMatrix() {
  10747. this.jitteredProjectionMatrix = undefined;
  10748. }
  10749. /**
  10750. * 设置相机矩阵
  10751. */;
  10752. _proto.setMatrix = function setMatrix(matrix) {
  10753. this.matrix = matrix;
  10754. this._update();
  10755. return this;
  10756. };
  10757. _proto.setFov = function setFov(fov) {
  10758. this.setPerspective(this.near, this.far, fov, this.aspect);
  10759. return this;
  10760. };
  10761. _proto.setAspect = function setAspect(aspect) {
  10762. this.setPerspective(this.near, this.far, this.fov, aspect);
  10763. return this;
  10764. };
  10765. _proto.setNear = function setNear(near) {
  10766. if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
  10767. this.setPerspective(near, this.far, this.fov, this.aspect);
  10768. } else {
  10769. this.setOrthographic(this.left, this.rright, this.top, this.bottom, near, this.far);
  10770. }
  10771. return this;
  10772. };
  10773. _proto.setFar = function setFar(far) {
  10774. if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
  10775. this.setPerspective(this.near, far, this.fov, this.aspect);
  10776. } else {
  10777. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, far);
  10778. }
  10779. return this;
  10780. }
  10781. /**
  10782. * Sets an offset in a larger frustum, used in PixelPicking
  10783. */;
  10784. _proto.setViewOffset = function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  10785. this.aspect = fullWidth / fullHeight;
  10786. if (this.view === undefined) {
  10787. this.view = {
  10788. enabled: true,
  10789. fullWidth: 1,
  10790. fullHeight: 1,
  10791. offsetX: 0,
  10792. offsetY: 0,
  10793. width: 1,
  10794. height: 1
  10795. };
  10796. }
  10797. this.view.enabled = true;
  10798. this.view.fullWidth = fullWidth;
  10799. this.view.fullHeight = fullHeight;
  10800. this.view.offsetX = x;
  10801. this.view.offsetY = y;
  10802. this.view.width = width;
  10803. this.view.height = height;
  10804. if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
  10805. this.setPerspective(this.near, this.far, this.fov, this.aspect);
  10806. } else {
  10807. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
  10808. }
  10809. return this;
  10810. };
  10811. _proto.clearViewOffset = function clearViewOffset() {
  10812. if (this.view !== undefined) {
  10813. this.view.enabled = false;
  10814. }
  10815. if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
  10816. this.setPerspective(this.near, this.far, this.fov, this.aspect);
  10817. } else {
  10818. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
  10819. }
  10820. return this;
  10821. };
  10822. _proto.setZoom = function setZoom(zoom) {
  10823. this.zoom = zoom;
  10824. if (this.projectionMode === exports.CameraProjectionMode.ORTHOGRAPHIC) {
  10825. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
  10826. } else if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
  10827. this.setPerspective(this.near, this.far, this.fov, this.aspect);
  10828. }
  10829. return this;
  10830. }
  10831. /**
  10832. * Zoom by specified point in viewport coordinates.
  10833. */;
  10834. _proto.setZoomByViewportPoint = function setZoomByViewportPoint(zoom, viewportPoint) {
  10835. var _this$canvas$viewport = this.canvas.viewport2Canvas({
  10836. x: viewportPoint[0],
  10837. y: viewportPoint[1]
  10838. }),
  10839. ox = _this$canvas$viewport.x,
  10840. oy = _this$canvas$viewport.y;
  10841. var roll = this.roll;
  10842. this.rotate(0, 0, -roll);
  10843. this.setPosition(ox, oy);
  10844. this.setFocalPoint(ox, oy);
  10845. this.setZoom(zoom);
  10846. this.rotate(0, 0, roll);
  10847. var _this$canvas$viewport2 = this.canvas.viewport2Canvas({
  10848. x: viewportPoint[0],
  10849. y: viewportPoint[1]
  10850. }),
  10851. cx = _this$canvas$viewport2.x,
  10852. cy = _this$canvas$viewport2.y;
  10853. // project to rotated axis
  10854. var dvec = glMatrix.vec3.fromValues(cx - ox, cy - oy, 0);
  10855. var dx = glMatrix.vec3.dot(dvec, this.right) / glMatrix.vec3.length(this.right);
  10856. var dy = glMatrix.vec3.dot(dvec, this.up) / glMatrix.vec3.length(this.up);
  10857. this.pan(-dx, -dy);
  10858. return this;
  10859. };
  10860. _proto.setPerspective = function setPerspective(near, far, fov, aspect) {
  10861. var _this$view;
  10862. this.projectionMode = exports.CameraProjectionMode.PERSPECTIVE;
  10863. this.fov = fov;
  10864. this.near = near;
  10865. this.far = far;
  10866. this.aspect = aspect;
  10867. var top = this.near * Math.tan(deg2rad(0.5 * this.fov)) / this.zoom;
  10868. var height = 2 * top;
  10869. var width = this.aspect * height;
  10870. var left = -0.5 * width;
  10871. if ((_this$view = this.view) === null || _this$view === void 0 ? void 0 : _this$view.enabled) {
  10872. var fullWidth = this.view.fullWidth;
  10873. var fullHeight = this.view.fullHeight;
  10874. left += this.view.offsetX * width / fullWidth;
  10875. top -= this.view.offsetY * height / fullHeight;
  10876. width *= this.view.width / fullWidth;
  10877. height *= this.view.height / fullHeight;
  10878. }
  10879. makePerspective(this.projectionMatrix, left, left + width, top, top - height, near, this.far);
  10880. // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
  10881. glMatrix.mat4.scale(this.projectionMatrix, this.projectionMatrix, glMatrix.vec3.fromValues(1, -1, 1));
  10882. glMatrix.mat4.invert(this.projectionMatrixInverse, this.projectionMatrix);
  10883. this.triggerUpdate();
  10884. return this;
  10885. };
  10886. _proto.setOrthographic = function setOrthographic(l, r, t, b, near, far) {
  10887. var _this$view2;
  10888. this.projectionMode = exports.CameraProjectionMode.ORTHOGRAPHIC;
  10889. this.rright = r;
  10890. this.left = l;
  10891. this.top = t;
  10892. this.bottom = b;
  10893. this.near = near;
  10894. this.far = far;
  10895. var dx = (this.rright - this.left) / (2 * this.zoom);
  10896. var dy = (this.top - this.bottom) / (2 * this.zoom);
  10897. var cx = (this.rright + this.left) / 2;
  10898. var cy = (this.top + this.bottom) / 2;
  10899. var left = cx - dx;
  10900. var right = cx + dx;
  10901. var top = cy + dy;
  10902. var bottom = cy - dy;
  10903. if ((_this$view2 = this.view) === null || _this$view2 === void 0 ? void 0 : _this$view2.enabled) {
  10904. var scaleW = (this.rright - this.left) / this.view.fullWidth / this.zoom;
  10905. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  10906. left += scaleW * this.view.offsetX;
  10907. right = left + scaleW * this.view.width;
  10908. top -= scaleH * this.view.offsetY;
  10909. bottom = top - scaleH * this.view.height;
  10910. }
  10911. glMatrix.mat4.ortho(this.projectionMatrix, left, right, bottom, top, near, far);
  10912. // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
  10913. glMatrix.mat4.scale(this.projectionMatrix, this.projectionMatrix, glMatrix.vec3.fromValues(1, -1, 1));
  10914. glMatrix.mat4.invert(this.projectionMatrixInverse, this.projectionMatrix);
  10915. this._getOrthoMatrix();
  10916. this.triggerUpdate();
  10917. return this;
  10918. }
  10919. /**
  10920. * Move the camera in world coordinates.
  10921. * It will keep looking at the current focal point.
  10922. *
  10923. * support scalars or vectors.
  10924. * @example
  10925. * setPosition(1, 2, 3);
  10926. * setPosition([1, 2, 3]);
  10927. */;
  10928. _proto.setPosition = function setPosition(x, y, z) {
  10929. if (y === void 0) {
  10930. y = this.position[1];
  10931. }
  10932. if (z === void 0) {
  10933. z = this.position[2];
  10934. }
  10935. var position = createVec3(x, y, z);
  10936. this._setPosition(position);
  10937. this.setFocalPoint(this.focalPoint);
  10938. this.triggerUpdate();
  10939. return this;
  10940. }
  10941. /**
  10942. * Sets the focal point of this camera in world coordinates.
  10943. *
  10944. * support scalars or vectors.
  10945. * @example
  10946. * setFocalPoint(1, 2, 3);
  10947. * setFocalPoint([1, 2, 3]);
  10948. */;
  10949. _proto.setFocalPoint = function setFocalPoint(x, y, z) {
  10950. if (y === void 0) {
  10951. y = this.focalPoint[1];
  10952. }
  10953. if (z === void 0) {
  10954. z = this.focalPoint[2];
  10955. }
  10956. var up = glMatrix.vec3.fromValues(0, 1, 0);
  10957. this.focalPoint = createVec3(x, y, z);
  10958. if (this.trackingMode === exports.CameraTrackingMode.CINEMATIC) {
  10959. var d = glMatrix.vec3.subtract(glMatrix.vec3.create(), this.focalPoint, this.position);
  10960. x = d[0];
  10961. y = d[1];
  10962. z = d[2];
  10963. var r = glMatrix.vec3.length(d);
  10964. var el = rad2deg(Math.asin(y / r));
  10965. var az = 90 + rad2deg(Math.atan2(z, x));
  10966. var m = glMatrix.mat4.create();
  10967. glMatrix.mat4.rotateY(m, m, deg2rad(az));
  10968. glMatrix.mat4.rotateX(m, m, deg2rad(el));
  10969. up = glMatrix.vec3.transformMat4(glMatrix.vec3.create(), [0, 1, 0], m);
  10970. }
  10971. glMatrix.mat4.invert(this.matrix, glMatrix.mat4.lookAt(glMatrix.mat4.create(), this.position, this.focalPoint, up));
  10972. this._getAxes();
  10973. this._getDistance();
  10974. this._getAngles();
  10975. this.triggerUpdate();
  10976. return this;
  10977. };
  10978. _proto.getDistance = function getDistance() {
  10979. return this.distance;
  10980. };
  10981. _proto.getDistanceVector = function getDistanceVector() {
  10982. return this.distanceVector;
  10983. }
  10984. /**
  10985. * Moves the camera towards/from the focal point.
  10986. */;
  10987. _proto.setDistance = function setDistance(d) {
  10988. if (this.distance === d || d < 0) {
  10989. return this;
  10990. }
  10991. this.distance = d;
  10992. if (this.distance < MIN_DISTANCE) {
  10993. this.distance = MIN_DISTANCE;
  10994. }
  10995. this.dollyingStep = this.distance / 100;
  10996. var pos = glMatrix.vec3.create();
  10997. d = this.distance;
  10998. var n = this.forward;
  10999. var f = this.focalPoint;
  11000. pos[0] = d * n[0] + f[0];
  11001. pos[1] = d * n[1] + f[1];
  11002. pos[2] = d * n[2] + f[2];
  11003. this._setPosition(pos);
  11004. this.triggerUpdate();
  11005. return this;
  11006. };
  11007. _proto.setMaxDistance = function setMaxDistance(d) {
  11008. this.maxDistance = d;
  11009. return this;
  11010. };
  11011. _proto.setMinDistance = function setMinDistance(d) {
  11012. this.minDistance = d;
  11013. return this;
  11014. }
  11015. /**
  11016. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  11017. * the azimuth in degrees
  11018. */;
  11019. _proto.setAzimuth = function setAzimuth(az) {
  11020. this.azimuth = getAngle(az);
  11021. this.computeMatrix();
  11022. this._getAxes();
  11023. if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
  11024. this._getPosition();
  11025. } else if (this.type === exports.CameraType.TRACKING) {
  11026. this._getFocalPoint();
  11027. }
  11028. this.triggerUpdate();
  11029. return this;
  11030. };
  11031. _proto.getAzimuth = function getAzimuth() {
  11032. return this.azimuth;
  11033. }
  11034. /**
  11035. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  11036. */;
  11037. _proto.setElevation = function setElevation(el) {
  11038. this.elevation = getAngle(el);
  11039. this.computeMatrix();
  11040. this._getAxes();
  11041. if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
  11042. this._getPosition();
  11043. } else if (this.type === exports.CameraType.TRACKING) {
  11044. this._getFocalPoint();
  11045. }
  11046. this.triggerUpdate();
  11047. return this;
  11048. };
  11049. _proto.getElevation = function getElevation() {
  11050. return this.elevation;
  11051. }
  11052. /**
  11053. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  11054. */;
  11055. _proto.setRoll = function setRoll(angle) {
  11056. this.roll = getAngle(angle);
  11057. this.computeMatrix();
  11058. this._getAxes();
  11059. if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
  11060. this._getPosition();
  11061. } else if (this.type === exports.CameraType.TRACKING) {
  11062. this._getFocalPoint();
  11063. }
  11064. this.triggerUpdate();
  11065. return this;
  11066. };
  11067. _proto.getRoll = function getRoll() {
  11068. return this.roll;
  11069. }
  11070. /**
  11071. * 根据相机矩阵重新计算各种相机参数
  11072. */;
  11073. _proto._update = function _update() {
  11074. this._getAxes();
  11075. this._getPosition();
  11076. this._getDistance();
  11077. this._getAngles();
  11078. this._getOrthoMatrix();
  11079. this.triggerUpdate();
  11080. }
  11081. /**
  11082. * 计算相机矩阵
  11083. */;
  11084. _proto.computeMatrix = function computeMatrix() {
  11085. // 使用四元数描述 3D 旋转
  11086. // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html
  11087. var rotZ = glMatrix.quat.setAxisAngle(glMatrix.quat.create(), [0, 0, 1], deg2rad(this.roll));
  11088. glMatrix.mat4.identity(this.matrix);
  11089. // only consider HCS for EXPLORING and ORBITING cameras
  11090. var rotX = glMatrix.quat.setAxisAngle(glMatrix.quat.create(), [1, 0, 0], deg2rad((this.rotateWorld && this.type !== exports.CameraType.TRACKING || this.type === exports.CameraType.TRACKING ? 1 : -1) * this.elevation));
  11091. var rotY = glMatrix.quat.setAxisAngle(glMatrix.quat.create(), [0, 1, 0], deg2rad((this.rotateWorld && this.type !== exports.CameraType.TRACKING || this.type === exports.CameraType.TRACKING ? 1 : -1) * this.azimuth));
  11092. var rotQ = glMatrix.quat.multiply(glMatrix.quat.create(), rotY, rotX);
  11093. rotQ = glMatrix.quat.multiply(glMatrix.quat.create(), rotQ, rotZ);
  11094. var rotMatrix = glMatrix.mat4.fromQuat(glMatrix.mat4.create(), rotQ);
  11095. if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
  11096. glMatrix.mat4.translate(this.matrix, this.matrix, this.focalPoint);
  11097. glMatrix.mat4.multiply(this.matrix, this.matrix, rotMatrix);
  11098. glMatrix.mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]);
  11099. } else if (this.type === exports.CameraType.TRACKING) {
  11100. glMatrix.mat4.translate(this.matrix, this.matrix, this.position);
  11101. glMatrix.mat4.multiply(this.matrix, this.matrix, rotMatrix);
  11102. }
  11103. }
  11104. /**
  11105. * Sets the camera position in the camera matrix
  11106. */;
  11107. _proto._setPosition = function _setPosition(x, y, z) {
  11108. this.position = createVec3(x, y, z);
  11109. var m = this.matrix;
  11110. m[12] = this.position[0];
  11111. m[13] = this.position[1];
  11112. m[14] = this.position[2];
  11113. m[15] = 1;
  11114. this._getOrthoMatrix();
  11115. }
  11116. /**
  11117. * Recalculates axes based on the current matrix
  11118. */;
  11119. _proto._getAxes = function _getAxes() {
  11120. glMatrix.vec3.copy(this.right, createVec3(glMatrix.vec4.transformMat4(glMatrix.vec4.create(), [1, 0, 0, 0], this.matrix)));
  11121. glMatrix.vec3.copy(this.up, createVec3(glMatrix.vec4.transformMat4(glMatrix.vec4.create(), [0, 1, 0, 0], this.matrix)));
  11122. glMatrix.vec3.copy(this.forward, createVec3(glMatrix.vec4.transformMat4(glMatrix.vec4.create(), [0, 0, 1, 0], this.matrix)));
  11123. glMatrix.vec3.normalize(this.right, this.right);
  11124. glMatrix.vec3.normalize(this.up, this.up);
  11125. glMatrix.vec3.normalize(this.forward, this.forward);
  11126. }
  11127. /**
  11128. * Recalculates euler angles based on the current state
  11129. */;
  11130. _proto._getAngles = function _getAngles() {
  11131. // Recalculates angles
  11132. var x = this.distanceVector[0];
  11133. var y = this.distanceVector[1];
  11134. var z = this.distanceVector[2];
  11135. var r = glMatrix.vec3.length(this.distanceVector);
  11136. // FAST FAIL: If there is no distance we cannot compute angles
  11137. if (r === 0) {
  11138. this.elevation = 0;
  11139. this.azimuth = 0;
  11140. return;
  11141. }
  11142. if (this.type === exports.CameraType.TRACKING) {
  11143. this.elevation = rad2deg(Math.asin(y / r));
  11144. this.azimuth = rad2deg(Math.atan2(-x, -z));
  11145. } else {
  11146. if (this.rotateWorld) {
  11147. this.elevation = rad2deg(Math.asin(y / r));
  11148. this.azimuth = rad2deg(Math.atan2(-x, -z));
  11149. } else {
  11150. this.elevation = -rad2deg(Math.asin(y / r));
  11151. this.azimuth = -rad2deg(Math.atan2(-x, -z));
  11152. }
  11153. }
  11154. }
  11155. /**
  11156. * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化
  11157. */;
  11158. _proto._getPosition = function _getPosition() {
  11159. glMatrix.vec3.copy(this.position, createVec3(glMatrix.vec4.transformMat4(glMatrix.vec4.create(), [0, 0, 0, 1], this.matrix)));
  11160. // 相机位置变化,需要重新计算视距
  11161. this._getDistance();
  11162. }
  11163. /**
  11164. * 重新计算视点,只有 TRACKING 模式视点才会发生变化
  11165. */;
  11166. _proto._getFocalPoint = function _getFocalPoint() {
  11167. glMatrix.vec3.transformMat3(this.distanceVector, [0, 0, -this.distance], glMatrix.mat3.fromMat4(glMatrix.mat3.create(), this.matrix));
  11168. glMatrix.vec3.add(this.focalPoint, this.position, this.distanceVector);
  11169. // 视点变化,需要重新计算视距
  11170. this._getDistance();
  11171. }
  11172. /**
  11173. * 重新计算视距
  11174. */;
  11175. _proto._getDistance = function _getDistance() {
  11176. this.distanceVector = glMatrix.vec3.subtract(glMatrix.vec3.create(), this.focalPoint, this.position);
  11177. this.distance = glMatrix.vec3.length(this.distanceVector);
  11178. this.dollyingStep = this.distance / 100;
  11179. };
  11180. _proto._getOrthoMatrix = function _getOrthoMatrix() {
  11181. if (this.projectionMode !== exports.CameraProjectionMode.ORTHOGRAPHIC) {
  11182. return;
  11183. }
  11184. var position = this.position;
  11185. var rotZ = glMatrix.quat.setAxisAngle(glMatrix.quat.create(), [0, 0, 1], -this.roll * Math.PI / 180);
  11186. glMatrix.mat4.fromRotationTranslationScaleOrigin(this.orthoMatrix, rotZ, glMatrix.vec3.fromValues((this.rright - this.left) / 2 - position[0], (this.top - this.bottom) / 2 - position[1], 0), glMatrix.vec3.fromValues(this.zoom, this.zoom, 1), position);
  11187. };
  11188. _proto.triggerUpdate = function triggerUpdate() {
  11189. if (this.enableUpdate) {
  11190. // update frustum
  11191. var viewMatrix = this.getViewTransform();
  11192. var vpMatrix = glMatrix.mat4.multiply(glMatrix.mat4.create(), this.getPerspective(), viewMatrix);
  11193. this.getFrustum().extractFromVPMatrix(vpMatrix);
  11194. this.eventEmitter.emit(CameraEvent.UPDATED);
  11195. }
  11196. };
  11197. _proto.rotate = function rotate(azimuth, elevation, roll) {
  11198. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11199. };
  11200. _proto.pan = function pan(tx, ty) {
  11201. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11202. };
  11203. _proto.dolly = function dolly(value) {
  11204. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11205. };
  11206. _proto.createLandmark = function createLandmark(name, params) {
  11207. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11208. };
  11209. _proto.gotoLandmark = function gotoLandmark(name, options) {
  11210. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11211. };
  11212. _proto.cancelLandmarkAnimation = function cancelLandmarkAnimation() {
  11213. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11214. };
  11215. return Camera;
  11216. }();
  11217. var CircleUpdater = /*#__PURE__*/function () {
  11218. function CircleUpdater() {}
  11219. var _proto = CircleUpdater.prototype;
  11220. _proto.update = function update(parsedStyle, object) {
  11221. var r = parsedStyle.r;
  11222. var width = r * 2;
  11223. var height = r * 2;
  11224. return {
  11225. width: width,
  11226. height: height
  11227. };
  11228. };
  11229. return CircleUpdater;
  11230. }();
  11231. var EllipseUpdater = /*#__PURE__*/function () {
  11232. function EllipseUpdater() {}
  11233. var _proto = EllipseUpdater.prototype;
  11234. _proto.update = function update(parsedStyle, object) {
  11235. var rx = parsedStyle.rx,
  11236. ry = parsedStyle.ry;
  11237. var width = rx * 2;
  11238. var height = ry * 2;
  11239. return {
  11240. width: width,
  11241. height: height
  11242. };
  11243. };
  11244. return EllipseUpdater;
  11245. }();
  11246. var LineUpdater = /*#__PURE__*/function () {
  11247. function LineUpdater() {}
  11248. var _proto = LineUpdater.prototype;
  11249. _proto.update = function update(parsedStyle) {
  11250. var x1 = parsedStyle.x1,
  11251. y1 = parsedStyle.y1,
  11252. x2 = parsedStyle.x2,
  11253. y2 = parsedStyle.y2;
  11254. var minX = Math.min(x1, x2);
  11255. var maxX = Math.max(x1, x2);
  11256. var minY = Math.min(y1, y2);
  11257. var maxY = Math.max(y1, y2);
  11258. var width = maxX - minX;
  11259. var height = maxY - minY;
  11260. return {
  11261. width: width,
  11262. height: height
  11263. };
  11264. };
  11265. return LineUpdater;
  11266. }();
  11267. var PathUpdater = /*#__PURE__*/function () {
  11268. function PathUpdater() {}
  11269. var _proto = PathUpdater.prototype;
  11270. _proto.update = function update(parsedStyle) {
  11271. var path = parsedStyle.path;
  11272. var _path$rect = path.rect,
  11273. width = _path$rect.width,
  11274. height = _path$rect.height;
  11275. return {
  11276. width: width,
  11277. height: height
  11278. };
  11279. };
  11280. return PathUpdater;
  11281. }();
  11282. var PolylineUpdater = /*#__PURE__*/function () {
  11283. function PolylineUpdater() {}
  11284. var _proto = PolylineUpdater.prototype;
  11285. _proto.update = function update(parsedStyle) {
  11286. var points = parsedStyle.points.points;
  11287. // FIXME: account for miter lineJoin
  11288. var minX = Math.min.apply(Math, points.map(function (point) {
  11289. return point[0];
  11290. }));
  11291. var maxX = Math.max.apply(Math, points.map(function (point) {
  11292. return point[0];
  11293. }));
  11294. var minY = Math.min.apply(Math, points.map(function (point) {
  11295. return point[1];
  11296. }));
  11297. var maxY = Math.max.apply(Math, points.map(function (point) {
  11298. return point[1];
  11299. }));
  11300. var width = maxX - minX;
  11301. var height = maxY - minY;
  11302. return {
  11303. width: width,
  11304. height: height
  11305. };
  11306. };
  11307. return PolylineUpdater;
  11308. }();
  11309. var RectUpdater = /*#__PURE__*/function () {
  11310. function RectUpdater() {}
  11311. var _proto = RectUpdater.prototype;
  11312. _proto.update = function update(parsedStyle, object) {
  11313. var img = parsedStyle.img,
  11314. _parsedStyle$width = parsedStyle.width,
  11315. width = _parsedStyle$width === void 0 ? 0 : _parsedStyle$width,
  11316. _parsedStyle$height = parsedStyle.height,
  11317. height = _parsedStyle$height === void 0 ? 0 : _parsedStyle$height;
  11318. var contentWidth = width;
  11319. var contentHeight = height;
  11320. // resize with HTMLImageElement's size
  11321. if (img && !util.isString(img)) {
  11322. if (!contentWidth) {
  11323. contentWidth = img.width;
  11324. parsedStyle.width = contentWidth;
  11325. }
  11326. if (!contentHeight) {
  11327. contentHeight = img.height;
  11328. parsedStyle.height = contentHeight;
  11329. }
  11330. }
  11331. return {
  11332. width: contentWidth,
  11333. height: contentHeight
  11334. };
  11335. };
  11336. return RectUpdater;
  11337. }();
  11338. var TextUpdater = /*#__PURE__*/function () {
  11339. function TextUpdater(globalRuntime) {
  11340. this.globalRuntime = void 0;
  11341. this.globalRuntime = globalRuntime;
  11342. }
  11343. var _proto = TextUpdater.prototype;
  11344. _proto.isReadyToMeasure = function isReadyToMeasure(parsedStyle, object) {
  11345. var text = parsedStyle.text,
  11346. textAlign = parsedStyle.textAlign,
  11347. textBaseline = parsedStyle.textBaseline,
  11348. fontSize = parsedStyle.fontSize,
  11349. fontStyle = parsedStyle.fontStyle,
  11350. fontWeight = parsedStyle.fontWeight,
  11351. fontVariant = parsedStyle.fontVariant,
  11352. lineWidth = parsedStyle.lineWidth;
  11353. return text && fontSize && fontStyle && fontWeight && fontVariant && textAlign && textBaseline && !util.isNil(lineWidth);
  11354. };
  11355. _proto.update = function update(parsedStyle, object) {
  11356. var _object$ownerDocument, _object$ownerDocument2;
  11357. var text = parsedStyle.text,
  11358. textAlign = parsedStyle.textAlign,
  11359. lineWidth = parsedStyle.lineWidth,
  11360. textBaseline = parsedStyle.textBaseline,
  11361. dx = parsedStyle.dx,
  11362. dy = parsedStyle.dy;
  11363. var _ref = (object === null || object === void 0 ? void 0 : (_object$ownerDocument = object.ownerDocument) === null || _object$ownerDocument === void 0 ? void 0 : (_object$ownerDocument2 = _object$ownerDocument.defaultView) === null || _object$ownerDocument2 === void 0 ? void 0 : _object$ownerDocument2.getConfig()) || {},
  11364. offscreenCanvas = _ref.offscreenCanvas;
  11365. if (!this.isReadyToMeasure(parsedStyle, object)) {
  11366. parsedStyle.metrics = {
  11367. font: '',
  11368. width: 0,
  11369. height: 0,
  11370. lines: [],
  11371. lineWidths: [],
  11372. lineHeight: 0,
  11373. maxLineWidth: 0,
  11374. fontProperties: {
  11375. ascent: 0,
  11376. descent: 0,
  11377. fontSize: 0
  11378. },
  11379. lineMetrics: []
  11380. };
  11381. return {
  11382. width: 0,
  11383. height: 0,
  11384. x: 0,
  11385. y: 0,
  11386. offsetX: 0,
  11387. offsetY: 0
  11388. };
  11389. }
  11390. var metrics = this.globalRuntime.textService.measureText(text, parsedStyle, offscreenCanvas);
  11391. parsedStyle.metrics = metrics;
  11392. var width = metrics.width,
  11393. height = metrics.height,
  11394. lineHeight = metrics.lineHeight,
  11395. fontProperties = metrics.fontProperties;
  11396. // anchor is left-top by default
  11397. var halfExtents = [width / 2, height / 2, 0];
  11398. // default 'left'
  11399. var anchor = [0, 1];
  11400. var lineXOffset = 0;
  11401. if (textAlign === 'center' || textAlign === 'middle') {
  11402. lineXOffset = lineWidth / 2;
  11403. anchor = [0.5, 1];
  11404. } else if (textAlign === 'right' || textAlign === 'end') {
  11405. lineXOffset = lineWidth;
  11406. anchor = [1, 1];
  11407. }
  11408. var lineYOffset = 0;
  11409. if (textBaseline === 'middle') {
  11410. // eslint-disable-next-line prefer-destructuring
  11411. lineYOffset = halfExtents[1];
  11412. } else if (textBaseline === 'top' || textBaseline === 'hanging') {
  11413. lineYOffset = halfExtents[1] * 2;
  11414. } else if (textBaseline === 'alphabetic') {
  11415. // prevent calling getImageData for ascent metrics
  11416. lineYOffset = runtime.enableCSSParsing ? lineHeight - fontProperties.ascent : 0;
  11417. } else if (textBaseline === 'bottom' || textBaseline === 'ideographic') {
  11418. lineYOffset = 0;
  11419. }
  11420. // TODO: ideographic & bottom
  11421. if (dx) {
  11422. lineXOffset += dx;
  11423. }
  11424. if (dy) {
  11425. lineYOffset += dy;
  11426. }
  11427. // update anchor
  11428. parsedStyle.anchor = [anchor[0], anchor[1], 0];
  11429. return {
  11430. width: halfExtents[0] * 2,
  11431. height: halfExtents[1] * 2,
  11432. offsetX: lineXOffset,
  11433. offsetY: lineYOffset
  11434. };
  11435. };
  11436. return TextUpdater;
  11437. }();
  11438. var PROPAGATION_LIMIT = 2048;
  11439. var EventService = /*#__PURE__*/function () {
  11440. function EventService(globalRuntime, context) {
  11441. var _this = this;
  11442. this.globalRuntime = void 0;
  11443. this.context = void 0;
  11444. this.rootTarget = void 0;
  11445. this.emitter = new EventEmitter__default['default']();
  11446. this.cursor = 'default';
  11447. this.mappingTable = {};
  11448. this.mappingState = {
  11449. trackingData: {}
  11450. };
  11451. this.eventPool = new Map();
  11452. this.pickHandler = void 0;
  11453. this.tmpMatrix = glMatrix.mat4.create();
  11454. this.tmpVec3 = glMatrix.vec3.create();
  11455. this.onPointerDown = function (from) {
  11456. // if (!(from instanceof FederatedPointerEvent)) {
  11457. // return;
  11458. // }
  11459. var e = _this.createPointerEvent(from);
  11460. _this.dispatchEvent(e, 'pointerdown');
  11461. if (e.pointerType === 'touch') {
  11462. _this.dispatchEvent(e, 'touchstart');
  11463. } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11464. var isRightButton = e.button === 2;
  11465. _this.dispatchEvent(e, isRightButton ? 'rightdown' : 'mousedown');
  11466. }
  11467. var trackingData = _this.trackingData(from.pointerId);
  11468. trackingData.pressTargetsByButton[from.button] = e.composedPath();
  11469. _this.freeEvent(e);
  11470. };
  11471. this.onPointerUp = function (from) {
  11472. // if (!(from instanceof FederatedPointerEvent)) {
  11473. // return;
  11474. // }
  11475. var now = performance.now();
  11476. var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
  11477. _this.dispatchEvent(e, 'pointerup');
  11478. if (e.pointerType === 'touch') {
  11479. _this.dispatchEvent(e, 'touchend');
  11480. } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11481. var isRightButton = e.button === 2;
  11482. _this.dispatchEvent(e, isRightButton ? 'rightup' : 'mouseup');
  11483. }
  11484. var trackingData = _this.trackingData(from.pointerId);
  11485. var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
  11486. var clickTarget = pressTarget;
  11487. // pointerupoutside only bubbles. It only bubbles upto the parent that doesn't contain
  11488. // the pointerup location.
  11489. if (pressTarget && !e.composedPath().includes(pressTarget)) {
  11490. var currentTarget = pressTarget;
  11491. while (currentTarget && !e.composedPath().includes(currentTarget)) {
  11492. e.currentTarget = currentTarget;
  11493. _this.notifyTarget(e, 'pointerupoutside');
  11494. if (e.pointerType === 'touch') {
  11495. _this.notifyTarget(e, 'touchendoutside');
  11496. } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11497. var _isRightButton = e.button === 2;
  11498. _this.notifyTarget(e, _isRightButton ? 'rightupoutside' : 'mouseupoutside');
  11499. }
  11500. if (Node.isNode(currentTarget)) {
  11501. currentTarget = currentTarget.parentNode;
  11502. }
  11503. }
  11504. delete trackingData.pressTargetsByButton[from.button];
  11505. // currentTarget is the most specific ancestor holding both the pointerdown and pointerup
  11506. // targets. That is - it's our click target!
  11507. clickTarget = currentTarget;
  11508. }
  11509. if (clickTarget) {
  11510. var _e$detail;
  11511. var clickEvent = _this.clonePointerEvent(e, 'click');
  11512. clickEvent.target = clickTarget;
  11513. clickEvent.path = [];
  11514. if (!trackingData.clicksByButton[from.button]) {
  11515. trackingData.clicksByButton[from.button] = {
  11516. clickCount: 0,
  11517. target: clickEvent.target,
  11518. timeStamp: now
  11519. };
  11520. }
  11521. var clickHistory = trackingData.clicksByButton[from.button];
  11522. if (clickHistory.target === clickEvent.target && now - clickHistory.timeStamp < 200) {
  11523. ++clickHistory.clickCount;
  11524. } else {
  11525. clickHistory.clickCount = 1;
  11526. }
  11527. clickHistory.target = clickEvent.target;
  11528. clickHistory.timeStamp = now;
  11529. clickEvent.detail = clickHistory.clickCount;
  11530. // @see https://github.com/antvis/G/issues/1091
  11531. if (!((_e$detail = e.detail) === null || _e$detail === void 0 ? void 0 : _e$detail.preventClick)) {
  11532. if (!_this.context.config.useNativeClickEvent && (clickEvent.pointerType === 'mouse' || clickEvent.pointerType === 'touch')) {
  11533. _this.dispatchEvent(clickEvent, 'click');
  11534. }
  11535. _this.dispatchEvent(clickEvent, 'pointertap');
  11536. }
  11537. _this.freeEvent(clickEvent);
  11538. }
  11539. _this.freeEvent(e);
  11540. };
  11541. this.onPointerMove = function (from) {
  11542. // if (!(from instanceof FederatedPointerEvent)) {
  11543. // return;
  11544. // }
  11545. var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
  11546. var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
  11547. var trackingData = _this.trackingData(from.pointerId);
  11548. var outTarget = _this.findMountedTarget(trackingData.overTargets);
  11549. // First pointerout/pointerleave
  11550. if (trackingData.overTargets && outTarget !== e.target) {
  11551. // pointerout always occurs on the overTarget when the pointer hovers over another element.
  11552. var outType = from.type === 'mousemove' ? 'mouseout' : 'pointerout';
  11553. var outEvent = _this.createPointerEvent(from, outType, outTarget || undefined);
  11554. _this.dispatchEvent(outEvent, 'pointerout');
  11555. if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
  11556. // If the pointer exits overTarget and its descendants, then a pointerleave event is also fired. This event
  11557. // is dispatched to all ancestors that no longer capture the pointer.
  11558. if (!e.composedPath().includes(outTarget)) {
  11559. var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
  11560. leaveEvent.eventPhase = leaveEvent.AT_TARGET;
  11561. while (leaveEvent.target && !e.composedPath().includes(leaveEvent.target)) {
  11562. leaveEvent.currentTarget = leaveEvent.target;
  11563. _this.notifyTarget(leaveEvent);
  11564. if (isMouse) {
  11565. _this.notifyTarget(leaveEvent, 'mouseleave');
  11566. }
  11567. if (Node.isNode(leaveEvent.target)) {
  11568. leaveEvent.target = leaveEvent.target.parentNode;
  11569. }
  11570. }
  11571. _this.freeEvent(leaveEvent);
  11572. }
  11573. _this.freeEvent(outEvent);
  11574. }
  11575. // Then pointerover
  11576. if (outTarget !== e.target) {
  11577. // pointerover always occurs on the new overTarget
  11578. var overType = from.type === 'mousemove' ? 'mouseover' : 'pointerover';
  11579. var overEvent = _this.clonePointerEvent(e, overType); // clone faster
  11580. _this.dispatchEvent(overEvent, 'pointerover');
  11581. if (isMouse) _this.dispatchEvent(overEvent, 'mouseover');
  11582. // Probe whether the newly hovered Node is an ancestor of the original overTarget.
  11583. var overTargetAncestor = outTarget && Node.isNode(outTarget) && outTarget.parentNode;
  11584. while (overTargetAncestor && overTargetAncestor !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11585. if (overTargetAncestor === e.target) break;
  11586. overTargetAncestor = overTargetAncestor.parentNode;
  11587. }
  11588. // The pointer has entered a non-ancestor of the original overTarget. This means we need a pointerentered
  11589. // event.
  11590. var didPointerEnter = !overTargetAncestor || overTargetAncestor === (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode);
  11591. if (didPointerEnter) {
  11592. var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
  11593. enterEvent.eventPhase = enterEvent.AT_TARGET;
  11594. while (enterEvent.target && enterEvent.target !== outTarget && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11595. enterEvent.currentTarget = enterEvent.target;
  11596. _this.notifyTarget(enterEvent);
  11597. if (isMouse) _this.notifyTarget(enterEvent, 'mouseenter');
  11598. if (Node.isNode(enterEvent.target)) {
  11599. enterEvent.target = enterEvent.target.parentNode;
  11600. }
  11601. }
  11602. _this.freeEvent(enterEvent);
  11603. }
  11604. _this.freeEvent(overEvent);
  11605. }
  11606. // Then pointermove
  11607. _this.dispatchEvent(e, 'pointermove');
  11608. if (e.pointerType === 'touch') _this.dispatchEvent(e, 'touchmove');
  11609. if (isMouse) {
  11610. _this.dispatchEvent(e, 'mousemove');
  11611. _this.cursor = _this.getCursor(e.target);
  11612. }
  11613. trackingData.overTargets = e.composedPath();
  11614. _this.freeEvent(e);
  11615. };
  11616. this.onPointerOut = function (from) {
  11617. // if (!(from instanceof FederatedPointerEvent)) {
  11618. // return;
  11619. // }
  11620. var trackingData = _this.trackingData(from.pointerId);
  11621. if (trackingData.overTargets) {
  11622. var isMouse = from.pointerType === 'mouse' || from.pointerType === 'pen';
  11623. var outTarget = _this.findMountedTarget(trackingData.overTargets);
  11624. // pointerout first
  11625. var outEvent = _this.createPointerEvent(from, 'pointerout', outTarget || undefined);
  11626. _this.dispatchEvent(outEvent);
  11627. if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
  11628. // pointerleave(s) are also dispatched b/c the pointer must've left rootTarget and its descendants to
  11629. // get an upstream pointerout event (upstream events do not know rootTarget has descendants).
  11630. var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
  11631. leaveEvent.eventPhase = leaveEvent.AT_TARGET;
  11632. while (leaveEvent.target && leaveEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11633. leaveEvent.currentTarget = leaveEvent.target;
  11634. _this.notifyTarget(leaveEvent);
  11635. if (isMouse) {
  11636. _this.notifyTarget(leaveEvent, 'mouseleave');
  11637. }
  11638. if (Node.isNode(leaveEvent.target)) {
  11639. leaveEvent.target = leaveEvent.target.parentNode;
  11640. }
  11641. }
  11642. trackingData.overTargets = null;
  11643. _this.freeEvent(outEvent);
  11644. _this.freeEvent(leaveEvent);
  11645. }
  11646. _this.cursor = null;
  11647. };
  11648. this.onPointerOver = function (from) {
  11649. // if (!(from instanceof FederatedPointerEvent)) {
  11650. // return;
  11651. // }
  11652. var trackingData = _this.trackingData(from.pointerId);
  11653. var e = _this.createPointerEvent(from);
  11654. var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
  11655. _this.dispatchEvent(e, 'pointerover');
  11656. if (isMouse) _this.dispatchEvent(e, 'mouseover');
  11657. if (e.pointerType === 'mouse') _this.cursor = _this.getCursor(e.target);
  11658. // pointerenter events must be fired since the pointer entered from upstream.
  11659. var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
  11660. enterEvent.eventPhase = enterEvent.AT_TARGET;
  11661. while (enterEvent.target && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11662. enterEvent.currentTarget = enterEvent.target;
  11663. _this.notifyTarget(enterEvent);
  11664. if (isMouse) {
  11665. // mouseenter should not bubble
  11666. // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event#usage_notes
  11667. _this.notifyTarget(enterEvent, 'mouseenter');
  11668. }
  11669. if (Node.isNode(enterEvent.target)) {
  11670. enterEvent.target = enterEvent.target.parentNode;
  11671. }
  11672. }
  11673. trackingData.overTargets = e.composedPath();
  11674. _this.freeEvent(e);
  11675. _this.freeEvent(enterEvent);
  11676. };
  11677. this.onPointerUpOutside = function (from) {
  11678. // if (!(from instanceof FederatedPointerEvent)) {
  11679. // return;
  11680. // }
  11681. var trackingData = _this.trackingData(from.pointerId);
  11682. var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
  11683. var e = _this.createPointerEvent(from);
  11684. if (pressTarget) {
  11685. var currentTarget = pressTarget;
  11686. while (currentTarget) {
  11687. e.currentTarget = currentTarget;
  11688. _this.notifyTarget(e, 'pointerupoutside');
  11689. if (e.pointerType === 'touch') ; else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11690. _this.notifyTarget(e, e.button === 2 ? 'rightupoutside' : 'mouseupoutside');
  11691. }
  11692. if (Node.isNode(currentTarget)) {
  11693. currentTarget = currentTarget.parentNode;
  11694. }
  11695. }
  11696. delete trackingData.pressTargetsByButton[from.button];
  11697. }
  11698. _this.freeEvent(e);
  11699. };
  11700. this.onWheel = function (from) {
  11701. // if (!(from instanceof FederatedWheelEvent)) {
  11702. // return;
  11703. // }
  11704. var wheelEvent = _this.createWheelEvent(from);
  11705. _this.dispatchEvent(wheelEvent);
  11706. _this.freeEvent(wheelEvent);
  11707. };
  11708. this.onClick = function (from) {
  11709. if (_this.context.config.useNativeClickEvent) {
  11710. var e = _this.createPointerEvent(from);
  11711. _this.dispatchEvent(e);
  11712. _this.freeEvent(e);
  11713. }
  11714. };
  11715. this.onPointerCancel = function (from) {
  11716. var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
  11717. _this.dispatchEvent(e);
  11718. _this.freeEvent(e);
  11719. };
  11720. this.globalRuntime = globalRuntime;
  11721. this.context = context;
  11722. }
  11723. var _proto = EventService.prototype;
  11724. _proto.init = function init() {
  11725. this.rootTarget = this.context.renderingContext.root.parentNode; // document
  11726. this.addEventMapping('pointerdown', this.onPointerDown);
  11727. this.addEventMapping('pointerup', this.onPointerUp);
  11728. this.addEventMapping('pointermove', this.onPointerMove);
  11729. this.addEventMapping('pointerout', this.onPointerOut);
  11730. this.addEventMapping('pointerleave', this.onPointerOut);
  11731. this.addEventMapping('pointercancel', this.onPointerCancel);
  11732. this.addEventMapping('pointerover', this.onPointerOver);
  11733. this.addEventMapping('pointerupoutside', this.onPointerUpOutside);
  11734. this.addEventMapping('wheel', this.onWheel);
  11735. this.addEventMapping('click', this.onClick);
  11736. };
  11737. _proto.destroy = function destroy() {
  11738. this.emitter.removeAllListeners();
  11739. this.mappingTable = {};
  11740. this.mappingState = {};
  11741. this.eventPool.clear();
  11742. };
  11743. _proto.client2Viewport = function client2Viewport(client) {
  11744. var bbox = this.context.contextService.getBoundingClientRect();
  11745. return new Point(client.x - ((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0), client.y - ((bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0));
  11746. };
  11747. _proto.viewport2Client = function viewport2Client(canvas) {
  11748. var bbox = this.context.contextService.getBoundingClientRect();
  11749. return new Point(canvas.x + ((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0), canvas.y + ((bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0));
  11750. };
  11751. _proto.viewport2Canvas = function viewport2Canvas(_ref) {
  11752. var x = _ref.x,
  11753. y = _ref.y;
  11754. var canvas = this.rootTarget.defaultView;
  11755. var camera = canvas.getCamera();
  11756. var _this$context$config = this.context.config,
  11757. width = _this$context$config.width,
  11758. height = _this$context$config.height;
  11759. var projectionMatrixInverse = camera.getPerspectiveInverse();
  11760. var worldMatrix = camera.getWorldTransform();
  11761. var vpMatrix = glMatrix.mat4.multiply(this.tmpMatrix, worldMatrix, projectionMatrixInverse);
  11762. var viewport = glMatrix.vec3.set(this.tmpVec3, x / width * 2 - 1, (1 - y / height) * 2 - 1, 0);
  11763. glMatrix.vec3.transformMat4(viewport, viewport, vpMatrix);
  11764. return new Point(viewport[0], viewport[1]);
  11765. };
  11766. _proto.canvas2Viewport = function canvas2Viewport(canvasP) {
  11767. var canvas = this.rootTarget.defaultView;
  11768. var camera = canvas.getCamera();
  11769. // World -> Clip
  11770. var projectionMatrix = camera.getPerspective();
  11771. var viewMatrix = camera.getViewTransform();
  11772. var vpMatrix = glMatrix.mat4.multiply(this.tmpMatrix, projectionMatrix, viewMatrix);
  11773. var clip = glMatrix.vec3.set(this.tmpVec3, canvasP.x, canvasP.y, 0);
  11774. glMatrix.vec3.transformMat4(this.tmpVec3, this.tmpVec3, vpMatrix);
  11775. // Clip -> NDC -> Viewport, flip Y
  11776. var _this$context$config2 = this.context.config,
  11777. width = _this$context$config2.width,
  11778. height = _this$context$config2.height;
  11779. return new Point((clip[0] + 1) / 2 * width, (1 - (clip[1] + 1) / 2) * height);
  11780. };
  11781. _proto.setPickHandler = function setPickHandler(pickHandler) {
  11782. this.pickHandler = pickHandler;
  11783. };
  11784. _proto.addEventMapping = function addEventMapping(type, fn) {
  11785. if (!this.mappingTable[type]) {
  11786. this.mappingTable[type] = [];
  11787. }
  11788. this.mappingTable[type].push({
  11789. fn: fn,
  11790. priority: 0
  11791. });
  11792. this.mappingTable[type].sort(function (a, b) {
  11793. return a.priority - b.priority;
  11794. });
  11795. };
  11796. _proto.mapEvent = function mapEvent(e) {
  11797. if (!this.rootTarget) {
  11798. return;
  11799. }
  11800. var mappers = this.mappingTable[e.type];
  11801. if (mappers) {
  11802. for (var i = 0, j = mappers.length; i < j; i++) {
  11803. mappers[i].fn(e);
  11804. }
  11805. } else {
  11806. console.warn("[EventService]: Event mapping not defined for " + e.type);
  11807. }
  11808. };
  11809. _proto.dispatchEvent = function dispatchEvent(e, type, skipPropagate) {
  11810. // Canvas should skip
  11811. if (!skipPropagate) {
  11812. e.propagationStopped = false;
  11813. e.propagationImmediatelyStopped = false;
  11814. this.propagate(e, type);
  11815. } else {
  11816. // target phase
  11817. e.eventPhase = e.AT_TARGET;
  11818. var canvas = this.rootTarget.defaultView || null;
  11819. e.currentTarget = canvas;
  11820. this.notifyListeners(e, type);
  11821. }
  11822. this.emitter.emit(type || e.type, e);
  11823. };
  11824. _proto.propagate = function propagate(e, type) {
  11825. if (!e.target) {
  11826. return;
  11827. }
  11828. // [target, parent, root, Canvas]
  11829. var composedPath = e.composedPath();
  11830. // event flow: capture -> target -> bubbling
  11831. // capture phase
  11832. e.eventPhase = e.CAPTURING_PHASE;
  11833. for (var i = composedPath.length - 1; i >= 1; i--) {
  11834. e.currentTarget = composedPath[i];
  11835. this.notifyTarget(e, type);
  11836. if (e.propagationStopped || e.propagationImmediatelyStopped) return;
  11837. }
  11838. // target phase
  11839. e.eventPhase = e.AT_TARGET;
  11840. e.currentTarget = e.target;
  11841. this.notifyTarget(e, type);
  11842. if (e.propagationStopped || e.propagationImmediatelyStopped) return;
  11843. // find current target in composed path
  11844. var index = composedPath.indexOf(e.currentTarget);
  11845. // bubbling phase
  11846. e.eventPhase = e.BUBBLING_PHASE;
  11847. for (var _i = index + 1; _i < composedPath.length; _i++) {
  11848. e.currentTarget = composedPath[_i];
  11849. this.notifyTarget(e, type);
  11850. if (e.propagationStopped || e.propagationImmediatelyStopped) return;
  11851. }
  11852. };
  11853. _proto.propagationPath = function propagationPath(target) {
  11854. var propagationPath = [target];
  11855. var canvas = this.rootTarget.defaultView || null;
  11856. if (canvas && canvas === target) {
  11857. propagationPath.unshift(canvas.document);
  11858. return propagationPath;
  11859. }
  11860. for (var i = 0; i < PROPAGATION_LIMIT && target !== this.rootTarget; i++) {
  11861. // if (Node.isNode(target) && !target.parentNode) {
  11862. // throw new Error('Cannot find propagation path to disconnected target');
  11863. // }
  11864. if (Node.isNode(target) && target.parentNode) {
  11865. // [target, parent, parent, root]
  11866. propagationPath.push(target.parentNode);
  11867. target = target.parentNode;
  11868. }
  11869. }
  11870. if (canvas) {
  11871. // @ts-ignore
  11872. propagationPath.push(canvas);
  11873. }
  11874. return propagationPath;
  11875. };
  11876. _proto.hitTest = function hitTest(position) {
  11877. var viewportX = position.viewportX,
  11878. viewportY = position.viewportY;
  11879. var _this$context$config3 = this.context.config,
  11880. width = _this$context$config3.width,
  11881. height = _this$context$config3.height;
  11882. // outside canvas
  11883. if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
  11884. return null;
  11885. }
  11886. return this.pickHandler(position) || this.rootTarget ||
  11887. // return Document
  11888. null;
  11889. }
  11890. /**
  11891. * whether the native event trigger came from Canvas,
  11892. * should account for HTML shape
  11893. */;
  11894. _proto.isNativeEventFromCanvas = function isNativeEventFromCanvas(event) {
  11895. var _event$nativeEvent;
  11896. var $el = this.context.contextService.getDomElement();
  11897. var target = (_event$nativeEvent = event.nativeEvent) === null || _event$nativeEvent === void 0 ? void 0 : _event$nativeEvent.target;
  11898. if (target) {
  11899. // from <canvas>
  11900. if (target === $el) {
  11901. return true;
  11902. }
  11903. // from <svg>
  11904. if ($el && $el.contains) {
  11905. return $el.contains(target);
  11906. }
  11907. }
  11908. if (event.nativeEvent.composedPath) {
  11909. return event.nativeEvent.composedPath().indexOf($el) > -1;
  11910. }
  11911. // account for Touch
  11912. return false;
  11913. }
  11914. /**
  11915. * Find HTML from composed path in native UI event.
  11916. */;
  11917. _proto.getExistedHTML = function getExistedHTML(event) {
  11918. if (event.nativeEvent.composedPath) {
  11919. for (var _iterator = _createForOfIteratorHelperLoose(event.nativeEvent.composedPath()), _step; !(_step = _iterator()).done;) {
  11920. var eventTarget = _step.value;
  11921. var existed = runtime.nativeHTMLMap.get(eventTarget);
  11922. if (existed) {
  11923. return existed;
  11924. }
  11925. }
  11926. }
  11927. return null;
  11928. };
  11929. _proto.pickTarget = function pickTarget(event) {
  11930. return this.hitTest({
  11931. clientX: event.clientX,
  11932. clientY: event.clientY,
  11933. viewportX: event.viewportX,
  11934. viewportY: event.viewportY,
  11935. x: event.canvasX,
  11936. y: event.canvasY
  11937. });
  11938. };
  11939. _proto.createPointerEvent = function createPointerEvent(from, type, target, fallbackTarget) {
  11940. var event = this.allocateEvent(FederatedPointerEvent);
  11941. this.copyPointerData(from, event);
  11942. this.copyMouseData(from, event);
  11943. this.copyData(from, event);
  11944. event.nativeEvent = from.nativeEvent;
  11945. event.originalEvent = from;
  11946. var existedHTML = this.getExistedHTML(event);
  11947. event.target = target !== null && target !== void 0 ? target : existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event) || fallbackTarget;
  11948. if (typeof type === 'string') {
  11949. event.type = type;
  11950. }
  11951. return event;
  11952. };
  11953. _proto.createWheelEvent = function createWheelEvent(from) {
  11954. var event = this.allocateEvent(FederatedWheelEvent);
  11955. this.copyWheelData(from, event);
  11956. this.copyMouseData(from, event);
  11957. this.copyData(from, event);
  11958. event.nativeEvent = from.nativeEvent;
  11959. event.originalEvent = from;
  11960. var existedHTML = this.getExistedHTML(event);
  11961. event.target = existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event);
  11962. return event;
  11963. };
  11964. _proto.trackingData = function trackingData(id) {
  11965. if (!this.mappingState.trackingData[id]) {
  11966. this.mappingState.trackingData[id] = {
  11967. pressTargetsByButton: {},
  11968. clicksByButton: {},
  11969. overTarget: null
  11970. };
  11971. }
  11972. return this.mappingState.trackingData[id];
  11973. };
  11974. _proto.cloneWheelEvent = function cloneWheelEvent(from) {
  11975. var event = this.allocateEvent(FederatedWheelEvent);
  11976. event.nativeEvent = from.nativeEvent;
  11977. event.originalEvent = from.originalEvent;
  11978. this.copyWheelData(from, event);
  11979. this.copyMouseData(from, event);
  11980. this.copyData(from, event);
  11981. event.target = from.target;
  11982. event.path = from.composedPath().slice();
  11983. event.type = from.type;
  11984. return event;
  11985. };
  11986. _proto.clonePointerEvent = function clonePointerEvent(from, type) {
  11987. var event = this.allocateEvent(FederatedPointerEvent);
  11988. event.nativeEvent = from.nativeEvent;
  11989. event.originalEvent = from.originalEvent;
  11990. this.copyPointerData(from, event);
  11991. this.copyMouseData(from, event);
  11992. this.copyData(from, event);
  11993. event.target = from.target;
  11994. event.path = from.composedPath().slice();
  11995. event.type = type !== null && type !== void 0 ? type : event.type;
  11996. return event;
  11997. };
  11998. _proto.copyPointerData = function copyPointerData(from, to) {
  11999. // if (
  12000. // !(
  12001. // from instanceof FederatedPointerEvent &&
  12002. // to instanceof FederatedPointerEvent
  12003. // )
  12004. // )
  12005. // return;
  12006. to.pointerId = from.pointerId;
  12007. to.width = from.width;
  12008. to.height = from.height;
  12009. to.isPrimary = from.isPrimary;
  12010. to.pointerType = from.pointerType;
  12011. to.pressure = from.pressure;
  12012. to.tangentialPressure = from.tangentialPressure;
  12013. to.tiltX = from.tiltX;
  12014. to.tiltY = from.tiltY;
  12015. to.twist = from.twist;
  12016. };
  12017. _proto.copyMouseData = function copyMouseData(from, to) {
  12018. // if (
  12019. // !(
  12020. // from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent
  12021. // )
  12022. // )
  12023. // return;
  12024. to.altKey = from.altKey;
  12025. to.button = from.button;
  12026. to.buttons = from.buttons;
  12027. to.ctrlKey = from.ctrlKey;
  12028. to.metaKey = from.metaKey;
  12029. to.shiftKey = from.shiftKey;
  12030. to.client.copyFrom(from.client);
  12031. to.movement.copyFrom(from.movement);
  12032. to.canvas.copyFrom(from.canvas);
  12033. to.screen.copyFrom(from.screen);
  12034. to.global.copyFrom(from.global);
  12035. to.offset.copyFrom(from.offset);
  12036. };
  12037. _proto.copyWheelData = function copyWheelData(from, to) {
  12038. to.deltaMode = from.deltaMode;
  12039. to.deltaX = from.deltaX;
  12040. to.deltaY = from.deltaY;
  12041. to.deltaZ = from.deltaZ;
  12042. };
  12043. _proto.copyData = function copyData(from, to) {
  12044. to.isTrusted = from.isTrusted;
  12045. to.timeStamp = performance.now();
  12046. to.type = from.type;
  12047. to.detail = from.detail;
  12048. to.view = from.view;
  12049. to.page.copyFrom(from.page);
  12050. to.viewport.copyFrom(from.viewport);
  12051. };
  12052. _proto.allocateEvent = function allocateEvent(constructor) {
  12053. if (!this.eventPool.has(constructor)) {
  12054. this.eventPool.set(constructor, []);
  12055. }
  12056. // @ts-ignore
  12057. var event = this.eventPool.get(constructor).pop() || new constructor(this);
  12058. event.eventPhase = event.NONE;
  12059. event.currentTarget = null;
  12060. event.path = [];
  12061. event.target = null;
  12062. return event;
  12063. };
  12064. _proto.freeEvent = function freeEvent(event) {
  12065. if (event.manager !== this) throw new Error('It is illegal to free an event not managed by this EventBoundary!');
  12066. var constructor = event.constructor;
  12067. if (!this.eventPool.has(constructor)) {
  12068. this.eventPool.set(constructor, []);
  12069. }
  12070. // @ts-ignore
  12071. this.eventPool.get(constructor).push(event);
  12072. };
  12073. _proto.notifyTarget = function notifyTarget(e, type) {
  12074. var _type;
  12075. type = (_type = type) !== null && _type !== void 0 ? _type : e.type;
  12076. var key = e.eventPhase === e.CAPTURING_PHASE || e.eventPhase === e.AT_TARGET ? type + "capture" : type;
  12077. this.notifyListeners(e, key);
  12078. if (e.eventPhase === e.AT_TARGET) {
  12079. this.notifyListeners(e, type);
  12080. }
  12081. };
  12082. _proto.notifyListeners = function notifyListeners(e, type) {
  12083. // hack EventEmitter, stops if the `propagationImmediatelyStopped` flag is set
  12084. // @ts-ignore
  12085. var emitter = e.currentTarget.emitter;
  12086. // @ts-ignore
  12087. var listeners = emitter._events[type];
  12088. if (!listeners) return;
  12089. if ('fn' in listeners) {
  12090. if (listeners.once) {
  12091. emitter.removeListener(type, listeners.fn, undefined, true);
  12092. }
  12093. listeners.fn.call(e.currentTarget || listeners.context, e);
  12094. // listeners.fn.call(listeners.context, e);
  12095. } else {
  12096. for (var i = 0; i < listeners.length && !e.propagationImmediatelyStopped; i++) {
  12097. if (listeners[i].once) {
  12098. emitter.removeListener(type, listeners[i].fn, undefined, true);
  12099. }
  12100. listeners[i].fn.call(e.currentTarget || listeners[i].context, e);
  12101. // listeners[i].fn.call(listeners[i].context, e);
  12102. }
  12103. }
  12104. }
  12105. /**
  12106. * some detached nodes may exist in propagation path, need to skip them
  12107. */;
  12108. _proto.findMountedTarget = function findMountedTarget(propagationPath) {
  12109. if (!propagationPath) {
  12110. return null;
  12111. }
  12112. var currentTarget = propagationPath[propagationPath.length - 1];
  12113. for (var i = propagationPath.length - 2; i >= 0; i--) {
  12114. var target = propagationPath[i];
  12115. if (target === this.rootTarget || Node.isNode(target) && target.parentNode === currentTarget) {
  12116. currentTarget = propagationPath[i];
  12117. } else {
  12118. break;
  12119. }
  12120. }
  12121. return currentTarget;
  12122. };
  12123. _proto.getCursor = function getCursor(target) {
  12124. var tmp = target;
  12125. while (tmp) {
  12126. var cursor = Element.isElement(tmp) && tmp.getAttribute('cursor');
  12127. if (cursor) {
  12128. return cursor;
  12129. }
  12130. tmp = Node.isNode(tmp) && tmp.parentNode;
  12131. }
  12132. };
  12133. return EventService;
  12134. }();
  12135. /**
  12136. * used in following scenes:
  12137. * - g `ctx.measureText`
  12138. * - g-plugin-canvas-picker `ctx.isPointInPath`
  12139. * - g-plugin-device-renderer `ctx.createLinearGradient` and generate texture
  12140. *
  12141. * @see https://blog.scottlogic.com/2020/03/19/offscreen-canvas.html
  12142. */
  12143. var OffscreenCanvasCreator = /*#__PURE__*/function () {
  12144. function OffscreenCanvasCreator() {
  12145. this.canvas = void 0;
  12146. this.context = void 0;
  12147. }
  12148. var _proto = OffscreenCanvasCreator.prototype;
  12149. _proto.getOrCreateCanvas = function getOrCreateCanvas(offscreenCanvas, contextAttributes) {
  12150. if (this.canvas) {
  12151. return this.canvas;
  12152. }
  12153. // user-defined offscreen canvas
  12154. if (offscreenCanvas) {
  12155. this.canvas = offscreenCanvas;
  12156. this.context = this.canvas.getContext('2d', contextAttributes);
  12157. } else {
  12158. try {
  12159. // OffscreenCanvas2D measureText can be up to 40% faster.
  12160. this.canvas = new window.OffscreenCanvas(0, 0);
  12161. this.context = this.canvas.getContext('2d', contextAttributes);
  12162. if (!this.context || !this.context.measureText) {
  12163. this.canvas = document.createElement('canvas');
  12164. this.context = this.canvas.getContext('2d');
  12165. }
  12166. } catch (ex) {
  12167. this.canvas = document.createElement('canvas');
  12168. this.context = this.canvas.getContext('2d', contextAttributes);
  12169. }
  12170. }
  12171. this.canvas.width = 10;
  12172. this.canvas.height = 10;
  12173. return this.canvas;
  12174. };
  12175. _proto.getOrCreateContext = function getOrCreateContext(offscreenCanvas, contextAttributes) {
  12176. if (this.context) {
  12177. return this.context;
  12178. }
  12179. this.getOrCreateCanvas(offscreenCanvas, contextAttributes);
  12180. return this.context;
  12181. };
  12182. return OffscreenCanvasCreator;
  12183. }();
  12184. /**
  12185. * why we need re-render
  12186. */
  12187. (function (RenderReason) {
  12188. RenderReason[RenderReason["CAMERA_CHANGED"] = 0] = "CAMERA_CHANGED";
  12189. RenderReason[RenderReason["DISPLAY_OBJECT_CHANGED"] = 1] = "DISPLAY_OBJECT_CHANGED";
  12190. RenderReason[RenderReason["NONE"] = 2] = "NONE";
  12191. })(exports.RenderReason || (exports.RenderReason = {}));
  12192. /**
  12193. * Use frame renderer implemented by `g-canvas/svg/webgl`, in every frame we do followings:
  12194. * * update & merge dirty rectangles
  12195. * * begin frame
  12196. * * filter by visible
  12197. * * sort by z-index in scene graph
  12198. * * culling with strategies registered in `g-canvas/webgl`
  12199. * * end frame
  12200. */
  12201. var RenderingService = /*#__PURE__*/function () {
  12202. function RenderingService(globalRuntime, context) {
  12203. this.globalRuntime = void 0;
  12204. this.context = void 0;
  12205. this.inited = false;
  12206. this.stats = {
  12207. /**
  12208. * total display objects in scenegraph
  12209. */
  12210. total: 0,
  12211. /**
  12212. * number of display objects need to render in current frame
  12213. */
  12214. rendered: 0
  12215. };
  12216. this.zIndexCounter = 0;
  12217. this.hooks = {
  12218. /**
  12219. * called before any frame rendered
  12220. */
  12221. init: new SyncHook(),
  12222. initAsync: new AsyncParallelHook(),
  12223. /**
  12224. * only dirty object which has sth changed will be rendered
  12225. */
  12226. dirtycheck: new SyncWaterfallHook(),
  12227. /**
  12228. * do culling
  12229. */
  12230. cull: new SyncWaterfallHook(),
  12231. /**
  12232. * called at beginning of each frame, won't get called if nothing to re-render
  12233. */
  12234. beginFrame: new SyncHook(),
  12235. /**
  12236. * called before every dirty object get rendered
  12237. */
  12238. beforeRender: new SyncHook(),
  12239. /**
  12240. * called when every dirty object rendering even it's culled
  12241. */
  12242. render: new SyncHook(),
  12243. /**
  12244. * called after every dirty object get rendered
  12245. */
  12246. afterRender: new SyncHook(),
  12247. endFrame: new SyncHook(),
  12248. destroy: new SyncHook(),
  12249. /**
  12250. * use async but faster method such as GPU-based picking in `g-plugin-device-renderer`
  12251. */
  12252. pick: new AsyncSeriesWaterfallHook(),
  12253. /**
  12254. * Unsafe but sync version of pick.
  12255. */
  12256. pickSync: new SyncWaterfallHook(),
  12257. /**
  12258. * used in event system
  12259. */
  12260. pointerDown: new SyncHook(),
  12261. pointerUp: new SyncHook(),
  12262. pointerMove: new SyncHook(),
  12263. pointerOut: new SyncHook(),
  12264. pointerOver: new SyncHook(),
  12265. pointerWheel: new SyncHook(),
  12266. pointerCancel: new SyncHook(),
  12267. click: new SyncHook()
  12268. };
  12269. this.globalRuntime = globalRuntime;
  12270. this.context = context;
  12271. }
  12272. var _proto = RenderingService.prototype;
  12273. _proto.init = function init(callback) {
  12274. var _this = this;
  12275. var context = _extends({}, this.globalRuntime, this.context);
  12276. // register rendering plugins
  12277. this.context.renderingPlugins.forEach(function (plugin) {
  12278. plugin.apply(context, runtime);
  12279. });
  12280. this.hooks.init.call();
  12281. if (this.hooks.initAsync.getCallbacksNum() === 0) {
  12282. this.inited = true;
  12283. callback();
  12284. } else {
  12285. this.hooks.initAsync.promise().then(function () {
  12286. _this.inited = true;
  12287. callback();
  12288. });
  12289. }
  12290. };
  12291. _proto.getStats = function getStats() {
  12292. return this.stats;
  12293. }
  12294. /**
  12295. * Meet the following conditions:
  12296. * * disable DirtyRectangleRendering
  12297. * * camera changed
  12298. */;
  12299. _proto.disableDirtyRectangleRendering = function disableDirtyRectangleRendering() {
  12300. var renderer = this.context.config.renderer;
  12301. var _renderer$getConfig = renderer.getConfig(),
  12302. enableDirtyRectangleRendering = _renderer$getConfig.enableDirtyRectangleRendering;
  12303. return !enableDirtyRectangleRendering || this.context.renderingContext.renderReasons.has(exports.RenderReason.CAMERA_CHANGED);
  12304. };
  12305. _proto.render = function render(canvasConfig, rerenderCallback) {
  12306. var _this2 = this;
  12307. this.stats.total = 0;
  12308. this.stats.rendered = 0;
  12309. this.zIndexCounter = 0;
  12310. var renderingContext = this.context.renderingContext;
  12311. this.globalRuntime.sceneGraphService.syncHierarchy(renderingContext.root);
  12312. this.globalRuntime.sceneGraphService.triggerPendingEvents();
  12313. if (renderingContext.renderReasons.size && this.inited) {
  12314. this.renderDisplayObject(renderingContext.root, canvasConfig, renderingContext);
  12315. this.hooks.beginFrame.call();
  12316. renderingContext.renderListCurrentFrame.forEach(function (object) {
  12317. _this2.hooks.beforeRender.call(object);
  12318. _this2.hooks.render.call(object);
  12319. _this2.hooks.afterRender.call(object);
  12320. });
  12321. this.hooks.endFrame.call();
  12322. renderingContext.renderListCurrentFrame = [];
  12323. renderingContext.renderReasons.clear();
  12324. rerenderCallback();
  12325. }
  12326. // console.log('stats', this.stats);
  12327. };
  12328. _proto.renderDisplayObject = function renderDisplayObject(displayObject, canvasConfig, renderingContext) {
  12329. var _this3 = this;
  12330. var _canvasConfig$rendere = canvasConfig.renderer.getConfig(),
  12331. enableDirtyCheck = _canvasConfig$rendere.enableDirtyCheck,
  12332. enableCulling = _canvasConfig$rendere.enableCulling;
  12333. // recalc style values
  12334. if (this.globalRuntime.enableCSSParsing) {
  12335. this.globalRuntime.styleValueRegistry.recalc(displayObject);
  12336. }
  12337. // TODO: relayout
  12338. // dirtycheck first
  12339. var objectChanged = enableDirtyCheck ? this.hooks.dirtycheck.call(displayObject) : displayObject;
  12340. if (objectChanged) {
  12341. var objectToRender = enableCulling ? this.hooks.cull.call(objectChanged, this.context.camera) : objectChanged;
  12342. if (objectToRender) {
  12343. this.stats.rendered++;
  12344. renderingContext.renderListCurrentFrame.push(objectToRender);
  12345. }
  12346. }
  12347. displayObject.renderable.dirty = false;
  12348. displayObject.sortable.renderOrder = this.zIndexCounter++;
  12349. this.stats.total++;
  12350. // sort is very expensive, use cached result if possible
  12351. var sortable = displayObject.sortable;
  12352. if (sortable.dirty) {
  12353. this.sort(displayObject, sortable);
  12354. sortable.dirty = false;
  12355. sortable.dirtyChildren = [];
  12356. sortable.dirtyReason = undefined;
  12357. }
  12358. // recursive rendering its children
  12359. (sortable.sorted || displayObject.childNodes).forEach(function (child) {
  12360. _this3.renderDisplayObject(child, canvasConfig, renderingContext);
  12361. });
  12362. };
  12363. _proto.sort = function sort(displayObject, sortable) {
  12364. if (sortable.sorted && sortable.dirtyReason !== exports.SortReason.Z_INDEX_CHANGED) {
  12365. // avoid re-sorting the whole children list
  12366. sortable.dirtyChildren.forEach(function (child) {
  12367. var index = displayObject.childNodes.indexOf(child);
  12368. if (index === -1) {
  12369. // remove from sorted list
  12370. var _index = sortable.sorted.indexOf(child);
  12371. if (_index >= 0) {
  12372. sortable.sorted.splice(_index, 1);
  12373. }
  12374. } else {
  12375. if (sortable.sorted.length === 0) {
  12376. sortable.sorted.push(child);
  12377. } else {
  12378. var _index2 = sortedIndex(sortable.sorted, child);
  12379. sortable.sorted.splice(_index2, 0, child);
  12380. }
  12381. }
  12382. });
  12383. } else {
  12384. sortable.sorted = displayObject.childNodes.slice().sort(sortByZIndex);
  12385. }
  12386. };
  12387. _proto.destroy = function destroy() {
  12388. this.inited = false;
  12389. this.hooks.destroy.call();
  12390. this.globalRuntime.sceneGraphService.clearPendingEvents();
  12391. };
  12392. _proto.dirtify = function dirtify() {
  12393. // need re-render
  12394. this.context.renderingContext.renderReasons.add(exports.RenderReason.DISPLAY_OBJECT_CHANGED);
  12395. };
  12396. return RenderingService;
  12397. }();
  12398. var ATTRIBUTE_REGEXP = /\[\s*(.*)=(.*)\s*\]/;
  12399. /**
  12400. * support the following DOM API:
  12401. * * getElementById
  12402. * * getElementsByClassName
  12403. * * getElementsByName
  12404. * * getElementsByTag
  12405. * * querySelector
  12406. * * querySelectorAll
  12407. */
  12408. var DefaultSceneGraphSelector = /*#__PURE__*/function () {
  12409. function DefaultSceneGraphSelector() {}
  12410. var _proto = DefaultSceneGraphSelector.prototype;
  12411. _proto.selectOne = function selectOne(query, root) {
  12412. var _this = this;
  12413. if (query.startsWith('.')) {
  12414. return root.find(function (node) {
  12415. // return !node.shadow && node.id === query.substring(1);
  12416. return ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this.getIdOrClassname(query)) > -1;
  12417. });
  12418. } else if (query.startsWith('#')) {
  12419. // getElementById('id')
  12420. return root.find(function (node) {
  12421. // return !node.shadow && node.id === query.substring(1);
  12422. return node.id === _this.getIdOrClassname(query);
  12423. });
  12424. } else if (query.startsWith('[')) {
  12425. var _this$getAttribute = this.getAttribute(query),
  12426. name = _this$getAttribute.name,
  12427. value = _this$getAttribute.value;
  12428. if (name) {
  12429. // getElementByName();
  12430. return root.find(function (node) {
  12431. return root !== node && (name === 'name' ? node.name === value : _this.attributeToString(node, name) === value);
  12432. });
  12433. } else {
  12434. return null;
  12435. }
  12436. } else {
  12437. // getElementsByTag('circle');
  12438. return root.find(function (node) {
  12439. return root !== node && node.nodeName === query;
  12440. });
  12441. }
  12442. };
  12443. _proto.selectAll = function selectAll(query, root) {
  12444. var _this2 = this;
  12445. // only support `[name="${name}"]` `.className` `#id`
  12446. if (query.startsWith('.')) {
  12447. // getElementsByClassName('className');
  12448. // should not include itself
  12449. return root.findAll(function (node) {
  12450. return root !== node && ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this2.getIdOrClassname(query)) > -1;
  12451. });
  12452. } else if (query.startsWith('#')) {
  12453. return root.findAll(function (node) {
  12454. return root !== node && node.id === _this2.getIdOrClassname(query);
  12455. });
  12456. } else if (query.startsWith('[')) {
  12457. var _this$getAttribute2 = this.getAttribute(query),
  12458. name = _this$getAttribute2.name,
  12459. value = _this$getAttribute2.value;
  12460. if (name) {
  12461. // getElementsByName();
  12462. return root.findAll(function (node) {
  12463. return root !== node && (name === 'name' ? node.name === value : _this2.attributeToString(node, name) === value);
  12464. });
  12465. } else {
  12466. return [];
  12467. }
  12468. } else {
  12469. // getElementsByTag('circle');
  12470. return root.findAll(function (node) {
  12471. return root !== node && node.nodeName === query;
  12472. });
  12473. }
  12474. };
  12475. _proto.is = function is(query, node) {
  12476. // a simple `matches` implementation
  12477. if (query.startsWith('.')) {
  12478. return node.className === this.getIdOrClassname(query);
  12479. } else if (query.startsWith('#')) {
  12480. return node.id === this.getIdOrClassname(query);
  12481. } else if (query.startsWith('[')) {
  12482. var _this$getAttribute3 = this.getAttribute(query),
  12483. name = _this$getAttribute3.name,
  12484. value = _this$getAttribute3.value;
  12485. return name === 'name' ? node.name === value : this.attributeToString(node, name) === value;
  12486. } else {
  12487. return node.nodeName === query;
  12488. }
  12489. };
  12490. _proto.getIdOrClassname = function getIdOrClassname(query) {
  12491. return query.substring(1);
  12492. };
  12493. _proto.getAttribute = function getAttribute(query) {
  12494. var matches = query.match(ATTRIBUTE_REGEXP);
  12495. var name = '';
  12496. var value = '';
  12497. if (matches && matches.length > 2) {
  12498. name = matches[1].replace(/"/g, '');
  12499. value = matches[2].replace(/"/g, '');
  12500. }
  12501. return {
  12502. name: name,
  12503. value: value
  12504. };
  12505. };
  12506. _proto.attributeToString = function attributeToString(node, name) {
  12507. if (!node.getAttribute) {
  12508. return '';
  12509. }
  12510. var value = node.getAttribute(name);
  12511. if (util.isNil(value)) {
  12512. return '';
  12513. }
  12514. if (value.toString) {
  12515. return value.toString();
  12516. }
  12517. return '';
  12518. };
  12519. return DefaultSceneGraphSelector;
  12520. }();
  12521. function markRenderableDirty(e) {
  12522. var renderable = e.renderable;
  12523. if (renderable) {
  12524. renderable.renderBoundsDirty = true;
  12525. renderable.boundsDirty = true;
  12526. }
  12527. }
  12528. var reparentEvent = new MutationEvent(exports.ElementEvent.REPARENT, null, '', '', '', 0, '', '');
  12529. /**
  12530. * update transform in scene graph
  12531. *
  12532. * @see https://community.khronos.org/t/scene-graphs/50542/7
  12533. */
  12534. var DefaultSceneGraphService = /*#__PURE__*/function () {
  12535. function DefaultSceneGraphService(runtime) {
  12536. var _this = this;
  12537. this.runtime = void 0;
  12538. this.pendingEvents = [];
  12539. this.boundsChangedEvent = new CustomEvent(exports.ElementEvent.BOUNDS_CHANGED);
  12540. /**
  12541. * rotate in world space
  12542. */
  12543. this.rotate = function () {
  12544. var parentInvertRotation = glMatrix.quat.create();
  12545. return function (element, degrees, y, z) {
  12546. if (y === void 0) {
  12547. y = 0;
  12548. }
  12549. if (z === void 0) {
  12550. z = 0;
  12551. }
  12552. if (typeof degrees === 'number') {
  12553. degrees = glMatrix.vec3.fromValues(degrees, y, z);
  12554. }
  12555. var transform = element.transformable;
  12556. if (element.parentNode === null || !element.parentNode.transformable) {
  12557. _this.rotateLocal(element, degrees);
  12558. } else {
  12559. var rotation = glMatrix.quat.create();
  12560. glMatrix.quat.fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
  12561. var rot = _this.getRotation(element);
  12562. var parentRot = _this.getRotation(element.parentNode);
  12563. glMatrix.quat.copy(parentInvertRotation, parentRot);
  12564. glMatrix.quat.invert(parentInvertRotation, parentInvertRotation);
  12565. glMatrix.quat.multiply(rotation, parentInvertRotation, rotation);
  12566. glMatrix.quat.multiply(transform.localRotation, rotation, rot);
  12567. glMatrix.quat.normalize(transform.localRotation, transform.localRotation);
  12568. _this.dirtifyLocal(element, transform);
  12569. }
  12570. };
  12571. }();
  12572. /**
  12573. * rotate in local space
  12574. * @see @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw
  12575. */
  12576. this.rotateLocal = function () {
  12577. var rotation = glMatrix.quat.create();
  12578. return function (element, degrees, y, z) {
  12579. if (y === void 0) {
  12580. y = 0;
  12581. }
  12582. if (z === void 0) {
  12583. z = 0;
  12584. }
  12585. if (typeof degrees === 'number') {
  12586. degrees = glMatrix.vec3.fromValues(degrees, y, z);
  12587. }
  12588. var transform = element.transformable;
  12589. glMatrix.quat.fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
  12590. glMatrix.quat.mul(transform.localRotation, transform.localRotation, rotation);
  12591. _this.dirtifyLocal(element, transform);
  12592. };
  12593. }();
  12594. /**
  12595. * set euler angles(degrees) in world space
  12596. */
  12597. this.setEulerAngles = function () {
  12598. var invParentRot = glMatrix.quat.create();
  12599. return function (element, degrees, y, z) {
  12600. if (y === void 0) {
  12601. y = 0;
  12602. }
  12603. if (z === void 0) {
  12604. z = 0;
  12605. }
  12606. if (typeof degrees === 'number') {
  12607. degrees = glMatrix.vec3.fromValues(degrees, y, z);
  12608. }
  12609. var transform = element.transformable;
  12610. if (element.parentNode === null || !element.parentNode.transformable) {
  12611. _this.setLocalEulerAngles(element, degrees);
  12612. } else {
  12613. glMatrix.quat.fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
  12614. var parentRotation = _this.getRotation(element.parentNode);
  12615. glMatrix.quat.copy(invParentRot, glMatrix.quat.invert(glMatrix.quat.create(), parentRotation));
  12616. glMatrix.quat.mul(transform.localRotation, transform.localRotation, invParentRot);
  12617. _this.dirtifyLocal(element, transform);
  12618. }
  12619. };
  12620. }();
  12621. /**
  12622. * translate in local space
  12623. *
  12624. * @example
  12625. * ```
  12626. * translateLocal(x, y, z)
  12627. * translateLocal(vec3(x, y, z))
  12628. * ```
  12629. */
  12630. this.translateLocal = function () {
  12631. return function (element, translation, y, z) {
  12632. if (y === void 0) {
  12633. y = 0;
  12634. }
  12635. if (z === void 0) {
  12636. z = 0;
  12637. }
  12638. if (typeof translation === 'number') {
  12639. translation = glMatrix.vec3.fromValues(translation, y, z);
  12640. }
  12641. var transform = element.transformable;
  12642. if (glMatrix.vec3.equals(translation, glMatrix.vec3.create())) {
  12643. return;
  12644. }
  12645. glMatrix.vec3.transformQuat(translation, translation, transform.localRotation);
  12646. glMatrix.vec3.add(transform.localPosition, transform.localPosition, translation);
  12647. _this.dirtifyLocal(element, transform);
  12648. };
  12649. }();
  12650. /**
  12651. * move to position in world space
  12652. *
  12653. * 对应 g 原版的 move/moveTo
  12654. * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L684-L689
  12655. */
  12656. this.setPosition = function () {
  12657. var parentInvertMatrix = glMatrix.mat4.create();
  12658. var tmpPosition = glMatrix.vec3.create();
  12659. return function (element, position) {
  12660. var transform = element.transformable;
  12661. tmpPosition[0] = position[0];
  12662. tmpPosition[1] = position[1];
  12663. tmpPosition[2] = position[2] || 0;
  12664. if (glMatrix.vec3.equals(_this.getPosition(element), tmpPosition)) {
  12665. return;
  12666. }
  12667. glMatrix.vec3.copy(transform.position, tmpPosition);
  12668. if (element.parentNode === null || !element.parentNode.transformable) {
  12669. glMatrix.vec3.copy(transform.localPosition, tmpPosition);
  12670. } else {
  12671. var parentTransform = element.parentNode.transformable;
  12672. glMatrix.mat4.copy(parentInvertMatrix, parentTransform.worldTransform);
  12673. glMatrix.mat4.invert(parentInvertMatrix, parentInvertMatrix);
  12674. glMatrix.vec3.transformMat4(transform.localPosition, tmpPosition, parentInvertMatrix);
  12675. }
  12676. _this.dirtifyLocal(element, transform);
  12677. };
  12678. }();
  12679. /**
  12680. * move to position in local space
  12681. */
  12682. this.setLocalPosition = function () {
  12683. var tmpPosition = glMatrix.vec3.create();
  12684. return function (element, position) {
  12685. var transform = element.transformable;
  12686. tmpPosition[0] = position[0];
  12687. tmpPosition[1] = position[1];
  12688. tmpPosition[2] = position[2] || 0;
  12689. if (glMatrix.vec3.equals(transform.localPosition, tmpPosition)) {
  12690. return;
  12691. }
  12692. glMatrix.vec3.copy(transform.localPosition, tmpPosition);
  12693. _this.dirtifyLocal(element, transform);
  12694. };
  12695. }();
  12696. /**
  12697. * translate in world space
  12698. *
  12699. * @example
  12700. * ```
  12701. * translate(x, y, z)
  12702. * translate(vec3(x, y, z))
  12703. * ```
  12704. *
  12705. * 对应 g 原版的 translate 2D
  12706. * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L665-L676
  12707. */
  12708. this.translate = function () {
  12709. var zeroVec3 = glMatrix.vec3.create();
  12710. var tmpVec3 = glMatrix.vec3.create();
  12711. var tr = glMatrix.vec3.create();
  12712. return function (element, translation, y, z) {
  12713. if (y === void 0) {
  12714. y = 0;
  12715. }
  12716. if (z === void 0) {
  12717. z = 0;
  12718. }
  12719. if (typeof translation === 'number') {
  12720. translation = glMatrix.vec3.set(tmpVec3, translation, y, z);
  12721. }
  12722. if (glMatrix.vec3.equals(translation, zeroVec3)) {
  12723. return;
  12724. }
  12725. glMatrix.vec3.add(tr, _this.getPosition(element), translation);
  12726. _this.setPosition(element, tr);
  12727. };
  12728. }();
  12729. this.setRotation = function () {
  12730. var parentInvertRotation = glMatrix.quat.create();
  12731. return function (element, rotation, y, z, w) {
  12732. var transform = element.transformable;
  12733. if (typeof rotation === 'number') {
  12734. rotation = glMatrix.quat.fromValues(rotation, y, z, w);
  12735. }
  12736. if (element.parentNode === null || !element.parentNode.transformable) {
  12737. _this.setLocalRotation(element, rotation);
  12738. } else {
  12739. var parentRot = _this.getRotation(element.parentNode);
  12740. glMatrix.quat.copy(parentInvertRotation, parentRot);
  12741. glMatrix.quat.invert(parentInvertRotation, parentInvertRotation);
  12742. glMatrix.quat.multiply(transform.localRotation, parentInvertRotation, rotation);
  12743. glMatrix.quat.normalize(transform.localRotation, transform.localRotation);
  12744. _this.dirtifyLocal(element, transform);
  12745. }
  12746. };
  12747. };
  12748. this.displayObjectDependencyMap = new WeakMap();
  12749. this.calcLocalTransform = function () {
  12750. var tmpMat = glMatrix.mat4.create();
  12751. var tmpPosition = glMatrix.vec3.create();
  12752. var tmpQuat = glMatrix.quat.fromValues(0, 0, 0, 1);
  12753. return function (transform) {
  12754. var hasSkew = transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0;
  12755. if (hasSkew) {
  12756. glMatrix.mat4.fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, glMatrix.vec3.fromValues(1, 1, 1), transform.origin);
  12757. // apply skew2D
  12758. if (transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0) {
  12759. var tmpMat4 = glMatrix.mat4.identity(tmpMat);
  12760. tmpMat4[4] = Math.tan(transform.localSkew[0]);
  12761. tmpMat4[1] = Math.tan(transform.localSkew[1]);
  12762. glMatrix.mat4.multiply(transform.localTransform, transform.localTransform, tmpMat4);
  12763. }
  12764. var scaling = glMatrix.mat4.fromRotationTranslationScaleOrigin(tmpMat, tmpQuat, tmpPosition, transform.localScale, transform.origin);
  12765. glMatrix.mat4.multiply(transform.localTransform, transform.localTransform, scaling);
  12766. } else {
  12767. // @see https://github.com/mattdesl/css-mat4/blob/master/index.js
  12768. glMatrix.mat4.fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, transform.localScale, transform.origin);
  12769. }
  12770. };
  12771. }();
  12772. this.runtime = runtime;
  12773. }
  12774. var _proto = DefaultSceneGraphService.prototype;
  12775. _proto.matches = function matches(query, root) {
  12776. return this.runtime.sceneGraphSelector.is(query, root);
  12777. };
  12778. _proto.querySelector = function querySelector(query, root) {
  12779. return this.runtime.sceneGraphSelector.selectOne(query, root);
  12780. };
  12781. _proto.querySelectorAll = function querySelectorAll(query, root) {
  12782. return this.runtime.sceneGraphSelector.selectAll(query, root);
  12783. // .filter((node) => !node.shadow);
  12784. };
  12785. _proto.attach = function attach(child, parent, index) {
  12786. var _sortable$sorted, _child$style;
  12787. var detached = false;
  12788. if (child.parentNode) {
  12789. detached = child.parentNode !== parent;
  12790. this.detach(child);
  12791. }
  12792. child.parentNode = parent;
  12793. if (!util.isNil(index)) {
  12794. child.parentNode.childNodes.splice(index, 0, child);
  12795. } else {
  12796. child.parentNode.childNodes.push(child);
  12797. }
  12798. // parent needs re-sort
  12799. var sortable = parent.sortable;
  12800. if ((sortable === null || sortable === void 0 ? void 0 : (_sortable$sorted = sortable.sorted) === null || _sortable$sorted === void 0 ? void 0 : _sortable$sorted.length) || ((_child$style = child.style) === null || _child$style === void 0 ? void 0 : _child$style.zIndex)) {
  12801. if (sortable.dirtyChildren.indexOf(child) === -1) {
  12802. sortable.dirtyChildren.push(child);
  12803. }
  12804. // if (sortable) {
  12805. // only child has z-Index
  12806. sortable.dirty = true;
  12807. sortable.dirtyReason = exports.SortReason.ADDED;
  12808. }
  12809. // this.updateGraphDepth(child);
  12810. var transform = child.transformable;
  12811. if (transform) {
  12812. this.dirtifyWorld(child, transform);
  12813. }
  12814. if (transform.frozen) {
  12815. this.unfreezeParentToRoot(child);
  12816. }
  12817. if (detached) {
  12818. child.dispatchEvent(reparentEvent);
  12819. }
  12820. };
  12821. _proto.detach = function detach(child) {
  12822. if (child.parentNode) {
  12823. var _sortable$sorted2, _child$style2;
  12824. var transform = child.transformable;
  12825. // if (transform) {
  12826. // const worldTransform = this.getWorldTransform(child, transform);
  12827. // mat4.getScaling(transform.localScale, worldTransform);
  12828. // mat4.getTranslation(transform.localPosition, worldTransform);
  12829. // mat4.getRotation(transform.localRotation, worldTransform);
  12830. // transform.localDirtyFlag = true;
  12831. // }
  12832. // parent needs re-sort
  12833. var sortable = child.parentNode.sortable;
  12834. // if (sortable) {
  12835. if ((sortable === null || sortable === void 0 ? void 0 : (_sortable$sorted2 = sortable.sorted) === null || _sortable$sorted2 === void 0 ? void 0 : _sortable$sorted2.length) || ((_child$style2 = child.style) === null || _child$style2 === void 0 ? void 0 : _child$style2.zIndex)) {
  12836. if (sortable.dirtyChildren.indexOf(child) === -1) {
  12837. sortable.dirtyChildren.push(child);
  12838. }
  12839. sortable.dirty = true;
  12840. sortable.dirtyReason = exports.SortReason.REMOVED;
  12841. }
  12842. var index = child.parentNode.childNodes.indexOf(child);
  12843. if (index > -1) {
  12844. child.parentNode.childNodes.splice(index, 1);
  12845. }
  12846. if (transform) {
  12847. this.dirtifyWorld(child, transform);
  12848. }
  12849. child.parentNode = null;
  12850. }
  12851. };
  12852. _proto.getOrigin = function getOrigin(element) {
  12853. return element.transformable.origin;
  12854. }
  12855. /**
  12856. * same as pivot in Pixi.js
  12857. *
  12858. * @see https://stackoverflow.com/questions/40748452/how-to-change-css-transform-origin-but-preserve-transformation
  12859. */;
  12860. _proto.setOrigin = function setOrigin(element, origin, y, z) {
  12861. if (y === void 0) {
  12862. y = 0;
  12863. }
  12864. if (z === void 0) {
  12865. z = 0;
  12866. }
  12867. if (typeof origin === 'number') {
  12868. origin = [origin, y, z];
  12869. }
  12870. var transform = element.transformable;
  12871. if (origin[0] === transform.origin[0] && origin[1] === transform.origin[1] && origin[2] === transform.origin[2]) {
  12872. return;
  12873. }
  12874. var originVec = transform.origin;
  12875. // const delta = vec3.subtract(vec3.create(), origin, originVec);
  12876. // vec3.add(transform.localPosition, transform.localPosition, delta);
  12877. // update origin
  12878. originVec[0] = origin[0];
  12879. originVec[1] = origin[1];
  12880. originVec[2] = origin[2] || 0;
  12881. this.dirtifyLocal(element, transform);
  12882. };
  12883. /**
  12884. * set euler angles(degrees) in local space
  12885. */
  12886. _proto.setLocalEulerAngles = function setLocalEulerAngles(element, degrees, y, z) {
  12887. if (y === void 0) {
  12888. y = 0;
  12889. }
  12890. if (z === void 0) {
  12891. z = 0;
  12892. }
  12893. if (typeof degrees === 'number') {
  12894. degrees = glMatrix.vec3.fromValues(degrees, y, z);
  12895. }
  12896. var transform = element.transformable;
  12897. glMatrix.quat.fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
  12898. this.dirtifyLocal(element, transform);
  12899. };
  12900. /**
  12901. * scale in local space
  12902. */
  12903. _proto.scaleLocal = function scaleLocal(element, scaling) {
  12904. var transform = element.transformable;
  12905. glMatrix.vec3.multiply(transform.localScale, transform.localScale, glMatrix.vec3.fromValues(scaling[0], scaling[1], scaling[2] || 1));
  12906. this.dirtifyLocal(element, transform);
  12907. };
  12908. _proto.setLocalScale = function setLocalScale(element, scaling) {
  12909. var transform = element.transformable;
  12910. var updatedScaling = glMatrix.vec3.fromValues(scaling[0], scaling[1], scaling[2] || transform.localScale[2]);
  12911. if (glMatrix.vec3.equals(updatedScaling, transform.localScale)) {
  12912. return;
  12913. }
  12914. glMatrix.vec3.copy(transform.localScale, updatedScaling);
  12915. this.dirtifyLocal(element, transform);
  12916. };
  12917. _proto.setLocalRotation = function setLocalRotation(element, rotation, y, z, w) {
  12918. if (typeof rotation === 'number') {
  12919. rotation = glMatrix.quat.fromValues(rotation, y, z, w);
  12920. }
  12921. var transform = element.transformable;
  12922. glMatrix.quat.copy(transform.localRotation, rotation);
  12923. this.dirtifyLocal(element, transform);
  12924. };
  12925. _proto.setLocalSkew = function setLocalSkew(element, skew, y) {
  12926. if (typeof skew === 'number') {
  12927. skew = glMatrix.vec2.fromValues(skew, y);
  12928. }
  12929. var transform = element.transformable;
  12930. glMatrix.vec2.copy(transform.localSkew, skew);
  12931. this.dirtifyLocal(element, transform);
  12932. };
  12933. _proto.dirtifyLocal = function dirtifyLocal(element, transform) {
  12934. if (!transform.localDirtyFlag) {
  12935. transform.localDirtyFlag = true;
  12936. if (!transform.dirtyFlag) {
  12937. this.dirtifyWorld(element, transform);
  12938. }
  12939. }
  12940. };
  12941. _proto.dirtifyWorld = function dirtifyWorld(element, transform) {
  12942. if (!transform.dirtyFlag) {
  12943. this.unfreezeParentToRoot(element);
  12944. }
  12945. this.dirtifyWorldInternal(element, transform);
  12946. this.dirtifyToRoot(element, true);
  12947. };
  12948. _proto.triggerPendingEvents = function triggerPendingEvents() {
  12949. var _this2 = this;
  12950. var set = new Set();
  12951. var trigger = function trigger(element, detail) {
  12952. if (element.isConnected && !set.has(element.entity)) {
  12953. _this2.boundsChangedEvent.detail = detail;
  12954. _this2.boundsChangedEvent.target = element;
  12955. if (element.isMutationObserved) {
  12956. element.dispatchEvent(_this2.boundsChangedEvent);
  12957. } else {
  12958. element.ownerDocument.defaultView.dispatchEvent(_this2.boundsChangedEvent, true);
  12959. }
  12960. set.add(element.entity);
  12961. }
  12962. };
  12963. this.pendingEvents.forEach(function (_ref) {
  12964. var element = _ref[0],
  12965. detail = _ref[1];
  12966. if (detail.affectChildren) {
  12967. element.forEach(function (e) {
  12968. trigger(e, detail);
  12969. });
  12970. } else {
  12971. trigger(element, detail);
  12972. }
  12973. });
  12974. this.clearPendingEvents();
  12975. set.clear();
  12976. };
  12977. _proto.clearPendingEvents = function clearPendingEvents() {
  12978. this.pendingEvents = [];
  12979. };
  12980. _proto.dirtifyToRoot = function dirtifyToRoot(element, affectChildren) {
  12981. if (affectChildren === void 0) {
  12982. affectChildren = false;
  12983. }
  12984. var p = element;
  12985. // only need to re-render itself
  12986. if (p.renderable) {
  12987. p.renderable.dirty = true;
  12988. }
  12989. while (p) {
  12990. markRenderableDirty(p);
  12991. p = p.parentNode;
  12992. }
  12993. if (affectChildren) {
  12994. element.forEach(function (e) {
  12995. markRenderableDirty(e);
  12996. });
  12997. }
  12998. // inform dependencies
  12999. this.informDependentDisplayObjects(element);
  13000. // reuse the same custom event
  13001. this.pendingEvents.push([element, {
  13002. affectChildren: affectChildren
  13003. }]);
  13004. };
  13005. _proto.updateDisplayObjectDependency = function updateDisplayObjectDependency(name, oldPath, newPath, object) {
  13006. // clear ref to old clip path
  13007. if (oldPath && oldPath !== newPath) {
  13008. var oldDependencyMap = this.displayObjectDependencyMap.get(oldPath);
  13009. if (oldDependencyMap && oldDependencyMap[name]) {
  13010. var index = oldDependencyMap[name].indexOf(object);
  13011. oldDependencyMap[name].splice(index, 1);
  13012. }
  13013. }
  13014. if (newPath) {
  13015. var newDependencyMap = this.displayObjectDependencyMap.get(newPath);
  13016. if (!newDependencyMap) {
  13017. this.displayObjectDependencyMap.set(newPath, {});
  13018. newDependencyMap = this.displayObjectDependencyMap.get(newPath);
  13019. }
  13020. if (!newDependencyMap[name]) {
  13021. newDependencyMap[name] = [];
  13022. }
  13023. newDependencyMap[name].push(object);
  13024. }
  13025. };
  13026. _proto.informDependentDisplayObjects = function informDependentDisplayObjects(object) {
  13027. var _this3 = this;
  13028. var dependencyMap = this.displayObjectDependencyMap.get(object);
  13029. if (dependencyMap) {
  13030. Object.keys(dependencyMap).forEach(function (name) {
  13031. dependencyMap[name].forEach(function (target) {
  13032. _this3.dirtifyToRoot(target, true);
  13033. target.dispatchEvent(new MutationEvent(exports.ElementEvent.ATTR_MODIFIED, target, _this3, _this3, name, MutationEvent.MODIFICATION, _this3, _this3));
  13034. if (target.isCustomElement && target.isConnected) {
  13035. if (target.attributeChangedCallback) {
  13036. target.attributeChangedCallback(name, _this3, _this3);
  13037. }
  13038. }
  13039. });
  13040. });
  13041. }
  13042. };
  13043. _proto.getPosition = function getPosition(element) {
  13044. var transform = element.transformable;
  13045. return glMatrix.mat4.getTranslation(transform.position, this.getWorldTransform(element, transform));
  13046. };
  13047. _proto.getRotation = function getRotation(element) {
  13048. var transform = element.transformable;
  13049. return glMatrix.mat4.getRotation(transform.rotation, this.getWorldTransform(element, transform));
  13050. };
  13051. _proto.getScale = function getScale(element) {
  13052. var transform = element.transformable;
  13053. return glMatrix.mat4.getScaling(transform.scaling, this.getWorldTransform(element, transform));
  13054. };
  13055. _proto.getWorldTransform = function getWorldTransform(element, transform) {
  13056. if (transform === void 0) {
  13057. transform = element.transformable;
  13058. }
  13059. if (!transform.localDirtyFlag && !transform.dirtyFlag) {
  13060. return transform.worldTransform;
  13061. }
  13062. if (element.parentNode && element.parentNode.transformable) {
  13063. this.getWorldTransform(element.parentNode);
  13064. }
  13065. this.sync(element, transform);
  13066. return transform.worldTransform;
  13067. };
  13068. _proto.getLocalPosition = function getLocalPosition(element) {
  13069. return element.transformable.localPosition;
  13070. };
  13071. _proto.getLocalRotation = function getLocalRotation(element) {
  13072. return element.transformable.localRotation;
  13073. };
  13074. _proto.getLocalScale = function getLocalScale(element) {
  13075. return element.transformable.localScale;
  13076. };
  13077. _proto.getLocalSkew = function getLocalSkew(element) {
  13078. return element.transformable.localSkew;
  13079. };
  13080. _proto.getLocalTransform = function getLocalTransform(element) {
  13081. var transform = element.transformable;
  13082. if (transform.localDirtyFlag) {
  13083. this.calcLocalTransform(transform);
  13084. transform.localDirtyFlag = false;
  13085. }
  13086. return transform.localTransform;
  13087. };
  13088. _proto.setLocalTransform = function setLocalTransform(element, transform) {
  13089. var t = glMatrix.mat4.getTranslation(glMatrix.vec3.create(), transform);
  13090. var r = glMatrix.mat4.getRotation(glMatrix.quat.create(), transform);
  13091. var s = glMatrix.mat4.getScaling(glMatrix.vec3.create(), transform);
  13092. this.setLocalScale(element, s);
  13093. this.setLocalPosition(element, t);
  13094. this.setLocalRotation(element, r);
  13095. };
  13096. _proto.resetLocalTransform = function resetLocalTransform(element) {
  13097. this.setLocalScale(element, [1, 1, 1]);
  13098. this.setLocalPosition(element, [0, 0, 0]);
  13099. this.setLocalEulerAngles(element, [0, 0, 0]);
  13100. this.setLocalSkew(element, [0, 0]);
  13101. };
  13102. _proto.getTransformedGeometryBounds = function getTransformedGeometryBounds(element, render, existedAABB) {
  13103. if (render === void 0) {
  13104. render = false;
  13105. }
  13106. var bounds = this.getGeometryBounds(element, render);
  13107. if (!AABB.isEmpty(bounds)) {
  13108. var aabb = existedAABB || new AABB();
  13109. aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
  13110. return aabb;
  13111. } else {
  13112. return null;
  13113. }
  13114. }
  13115. /**
  13116. * won't account for children
  13117. */;
  13118. _proto.getGeometryBounds = function getGeometryBounds(element, render) {
  13119. if (render === void 0) {
  13120. render = false;
  13121. }
  13122. var geometry = element.geometry;
  13123. var bounds = render ? geometry.renderBounds : geometry.contentBounds || null;
  13124. // return (bounds && new AABB(bounds.center, bounds.halfExtents)) || new AABB();
  13125. return bounds || new AABB();
  13126. }
  13127. /**
  13128. * account for children in world space
  13129. */;
  13130. _proto.getBounds = function getBounds(element, render) {
  13131. var _this4 = this;
  13132. if (render === void 0) {
  13133. render = false;
  13134. }
  13135. var renderable = element.renderable;
  13136. if (!renderable.boundsDirty && !render && renderable.bounds) {
  13137. return renderable.bounds;
  13138. }
  13139. if (!renderable.renderBoundsDirty && render && renderable.renderBounds) {
  13140. return renderable.renderBounds;
  13141. }
  13142. // reuse existed if possible
  13143. var existedAABB = render ? renderable.renderBounds : renderable.bounds;
  13144. // reset with geometry's aabb
  13145. var aabb = this.getTransformedGeometryBounds(element, render, existedAABB);
  13146. // merge children's aabbs
  13147. var children = element.childNodes;
  13148. children.forEach(function (child) {
  13149. var childBounds = _this4.getBounds(child, render);
  13150. if (childBounds) {
  13151. if (!aabb) {
  13152. aabb = existedAABB || new AABB();
  13153. aabb.update(childBounds.center, childBounds.halfExtents);
  13154. } else {
  13155. aabb.add(childBounds);
  13156. }
  13157. }
  13158. });
  13159. if (render) {
  13160. // FIXME: account for clip path
  13161. var clipped = findClosestClipPathTarget(element);
  13162. if (clipped) {
  13163. // use bounds under world space
  13164. var clipPathBounds = clipped.parsedStyle.clipPath.getBounds(render);
  13165. if (!aabb) {
  13166. aabb = clipPathBounds;
  13167. } else if (clipPathBounds) {
  13168. aabb = clipPathBounds.intersection(aabb);
  13169. }
  13170. }
  13171. }
  13172. if (!aabb) {
  13173. aabb = new AABB();
  13174. }
  13175. if (aabb) {
  13176. if (render) {
  13177. renderable.renderBounds = aabb;
  13178. } else {
  13179. renderable.bounds = aabb;
  13180. }
  13181. }
  13182. if (render) {
  13183. renderable.renderBoundsDirty = false;
  13184. } else {
  13185. renderable.boundsDirty = false;
  13186. }
  13187. return aabb;
  13188. }
  13189. /**
  13190. * account for children in local space
  13191. */;
  13192. _proto.getLocalBounds = function getLocalBounds(element) {
  13193. if (element.parentNode) {
  13194. var parentInvert = glMatrix.mat4.create();
  13195. if (element.parentNode.transformable) {
  13196. parentInvert = glMatrix.mat4.invert(glMatrix.mat4.create(), this.getWorldTransform(element.parentNode));
  13197. }
  13198. var bounds = this.getBounds(element);
  13199. if (!AABB.isEmpty(bounds)) {
  13200. var localBounds = new AABB();
  13201. localBounds.setFromTransformedAABB(bounds, parentInvert);
  13202. return localBounds;
  13203. }
  13204. }
  13205. return this.getBounds(element);
  13206. };
  13207. _proto.getBoundingClientRect = function getBoundingClientRect(element) {
  13208. var _element$ownerDocumen, _element$ownerDocumen2;
  13209. var aabb;
  13210. var bounds = this.getGeometryBounds(element);
  13211. if (!AABB.isEmpty(bounds)) {
  13212. aabb = new AABB();
  13213. // apply transformation to aabb
  13214. aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
  13215. }
  13216. // calc context's offset
  13217. var bbox = (_element$ownerDocumen = element.ownerDocument) === null || _element$ownerDocumen === void 0 ? void 0 : (_element$ownerDocumen2 = _element$ownerDocumen.defaultView) === null || _element$ownerDocumen2 === void 0 ? void 0 : _element$ownerDocumen2.getContextService().getBoundingClientRect();
  13218. if (aabb) {
  13219. var _aabb$getMin = aabb.getMin(),
  13220. left = _aabb$getMin[0],
  13221. top = _aabb$getMin[1];
  13222. var _aabb$getMax = aabb.getMax(),
  13223. right = _aabb$getMax[0],
  13224. bottom = _aabb$getMax[1];
  13225. return new Rectangle(left + ((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0), top + ((bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0), right - left, bottom - top);
  13226. }
  13227. return new Rectangle((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0, (bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0, 0, 0);
  13228. };
  13229. _proto.dirtifyWorldInternal = function dirtifyWorldInternal(element, transform) {
  13230. var _this5 = this;
  13231. if (!transform.dirtyFlag) {
  13232. transform.dirtyFlag = true;
  13233. transform.frozen = false;
  13234. element.childNodes.forEach(function (child) {
  13235. var childTransform = child.transformable;
  13236. if (!childTransform.dirtyFlag) {
  13237. _this5.dirtifyWorldInternal(child, childTransform);
  13238. }
  13239. });
  13240. var renderable = element.renderable;
  13241. if (renderable) {
  13242. renderable.renderBoundsDirty = true;
  13243. renderable.boundsDirty = true;
  13244. renderable.dirty = true;
  13245. }
  13246. }
  13247. };
  13248. _proto.syncHierarchy = function syncHierarchy(element) {
  13249. var transform = element.transformable;
  13250. if (transform.frozen) {
  13251. return;
  13252. }
  13253. transform.frozen = true;
  13254. if (transform.localDirtyFlag || transform.dirtyFlag) {
  13255. this.sync(element, transform);
  13256. }
  13257. var children = element.childNodes;
  13258. for (var i = 0; i < children.length; i++) {
  13259. this.syncHierarchy(children[i]);
  13260. }
  13261. };
  13262. _proto.sync = function sync(element, transform) {
  13263. if (transform.localDirtyFlag) {
  13264. this.calcLocalTransform(transform);
  13265. transform.localDirtyFlag = false;
  13266. }
  13267. if (transform.dirtyFlag) {
  13268. var parent = element.parentNode;
  13269. var parentTransform = parent && parent.transformable;
  13270. if (parent === null || !parentTransform) {
  13271. glMatrix.mat4.copy(transform.worldTransform, transform.localTransform);
  13272. } else {
  13273. // TODO: should we support scale compensation?
  13274. // @see https://github.com/playcanvas/engine/issues/1077#issuecomment-359765557
  13275. glMatrix.mat4.multiply(transform.worldTransform, parentTransform.worldTransform, transform.localTransform);
  13276. }
  13277. transform.dirtyFlag = false;
  13278. }
  13279. };
  13280. _proto.unfreezeParentToRoot = function unfreezeParentToRoot(child) {
  13281. var p = child.parentNode;
  13282. while (p) {
  13283. var transform = p.transformable;
  13284. if (transform) {
  13285. transform.frozen = false;
  13286. }
  13287. p = p.parentNode;
  13288. }
  13289. };
  13290. return DefaultSceneGraphService;
  13291. }();
  13292. var TEXT_METRICS = {
  13293. MetricsString: '|ÉqÅ',
  13294. BaselineSymbol: 'M',
  13295. BaselineMultiplier: 1.4,
  13296. HeightMultiplier: 2,
  13297. Newlines: [0x000a, 0x000d // carriage return
  13298. ],
  13299. BreakingSpaces: [0x0009, 0x0020, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2008, 0x2009, 0x200a, 0x205f, 0x3000 // ideographic space
  13300. ]
  13301. };
  13302. var LATIN_REGEX = /[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00f6\u00f8-\u00ff!"#$%&'()*+,-./:;]/;
  13303. // Line breaking rules in CJK (Kinsoku Shori)
  13304. // Refer from https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
  13305. var regexCannotStartZhCn = /[!%),.:;?\]}¢°·'""†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~]/;
  13306. var regexCannotEndZhCn = /[$(£¥·'"〈《「『【〔〖〝﹙﹛$(.[{£¥]/;
  13307. var regexCannotStartZhTw = /[!),.:;?\]}¢·–—'"•"、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、]/;
  13308. var regexCannotEndZhTw = /[([{£¥'"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏]/;
  13309. var regexCannotStartJaJp = /[)\]}〕〉》」』】〙〗〟'"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.]/;
  13310. var regexCannotEndJaJp = /[([{〔〈《「『【〘〖〝'"⦅«—...‥〳〴〵]/;
  13311. var regexCannotStartKoKr = /[!%),.:;?\]}¢°'"†‡℃〆〈《「『〕!%),.:;?]}]/;
  13312. var regexCannotEndKoKr = /[$([{£¥'"々〇〉》」〔$([{⦆¥₩#]/;
  13313. var regexCannotStart = new RegExp(regexCannotStartZhCn.source + "|" + regexCannotStartZhTw.source + "|" + regexCannotStartJaJp.source + "|" + regexCannotStartKoKr.source);
  13314. var regexCannotEnd = new RegExp(regexCannotEndZhCn.source + "|" + regexCannotEndZhTw.source + "|" + regexCannotEndJaJp.source + "|" + regexCannotEndKoKr.source);
  13315. /**
  13316. * Borrow from pixi/packages/text/src/TextMetrics.ts
  13317. */
  13318. var TextService = /*#__PURE__*/function () {
  13319. function TextService(runtime) {
  13320. var _this = this;
  13321. this.runtime = void 0;
  13322. /**
  13323. * font metrics cache
  13324. */
  13325. this.fontMetricsCache = {};
  13326. this.shouldBreakByKinsokuShorui = function (char, nextChar) {
  13327. if (_this.isBreakingSpace(nextChar)) return false;
  13328. if (char) {
  13329. // Line breaking rules in CJK (Kinsoku Shori)
  13330. if (regexCannotEnd.exec(nextChar) || regexCannotStart.exec(char)) {
  13331. return true;
  13332. }
  13333. }
  13334. return false;
  13335. };
  13336. this.trimByKinsokuShorui = function (prev) {
  13337. var next = [].concat(prev);
  13338. var prevLine = next[next.length - 2];
  13339. if (!prevLine) {
  13340. return prev;
  13341. }
  13342. var lastChar = prevLine[prevLine.length - 1];
  13343. next[next.length - 2] = prevLine.slice(0, -1);
  13344. next[next.length - 1] = lastChar + next[next.length - 1];
  13345. return next;
  13346. };
  13347. this.runtime = runtime;
  13348. }
  13349. var _proto = TextService.prototype;
  13350. /**
  13351. * Calculates the ascent, descent and fontSize of a given font-style.
  13352. */
  13353. _proto.measureFont = function measureFont(font, offscreenCanvas) {
  13354. // as this method is used for preparing assets, don't recalculate things if we don't need to
  13355. if (this.fontMetricsCache[font]) {
  13356. return this.fontMetricsCache[font];
  13357. }
  13358. var properties = {
  13359. ascent: 0,
  13360. descent: 0,
  13361. fontSize: 0
  13362. };
  13363. var canvas = this.runtime.offscreenCanvas.getOrCreateCanvas(offscreenCanvas);
  13364. var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas, {
  13365. willReadFrequently: true
  13366. });
  13367. context.font = font;
  13368. var metricsString = TEXT_METRICS.MetricsString + TEXT_METRICS.BaselineSymbol;
  13369. var width = Math.ceil(context.measureText(metricsString).width);
  13370. var baseline = Math.ceil(context.measureText(TEXT_METRICS.BaselineSymbol).width);
  13371. var height = TEXT_METRICS.HeightMultiplier * baseline;
  13372. baseline = baseline * TEXT_METRICS.BaselineMultiplier | 0;
  13373. // @ts-ignore
  13374. canvas.width = width;
  13375. // @ts-ignore
  13376. canvas.height = height;
  13377. context.fillStyle = '#f00';
  13378. context.fillRect(0, 0, width, height);
  13379. context.font = font;
  13380. context.textBaseline = 'alphabetic';
  13381. context.fillStyle = '#000';
  13382. context.fillText(metricsString, 0, baseline);
  13383. var imagedata = context.getImageData(0, 0, width || 1, height || 1).data;
  13384. var pixels = imagedata.length;
  13385. var line = width * 4;
  13386. var i = 0;
  13387. var idx = 0;
  13388. var stop = false;
  13389. // ascent. scan from top to bottom until we find a non red pixel
  13390. for (i = 0; i < baseline; ++i) {
  13391. for (var j = 0; j < line; j += 4) {
  13392. if (imagedata[idx + j] !== 255) {
  13393. stop = true;
  13394. break;
  13395. }
  13396. }
  13397. if (!stop) {
  13398. idx += line;
  13399. } else {
  13400. break;
  13401. }
  13402. }
  13403. properties.ascent = baseline - i;
  13404. idx = pixels - line;
  13405. stop = false;
  13406. // descent. scan from bottom to top until we find a non red pixel
  13407. for (i = height; i > baseline; --i) {
  13408. for (var _j = 0; _j < line; _j += 4) {
  13409. if (imagedata[idx + _j] !== 255) {
  13410. stop = true;
  13411. break;
  13412. }
  13413. }
  13414. if (!stop) {
  13415. idx -= line;
  13416. } else {
  13417. break;
  13418. }
  13419. }
  13420. properties.descent = i - baseline;
  13421. properties.fontSize = properties.ascent + properties.descent;
  13422. this.fontMetricsCache[font] = properties;
  13423. return properties;
  13424. };
  13425. _proto.measureText = function measureText(text, parsedStyle, offscreenCanvas) {
  13426. var fontSize = parsedStyle.fontSize,
  13427. wordWrap = parsedStyle.wordWrap,
  13428. strokeHeight = parsedStyle.lineHeight,
  13429. lineWidth = parsedStyle.lineWidth,
  13430. textBaseline = parsedStyle.textBaseline,
  13431. textAlign = parsedStyle.textAlign,
  13432. letterSpacing = parsedStyle.letterSpacing,
  13433. textPath = parsedStyle.textPath,
  13434. textPathSide = parsedStyle.textPathSide,
  13435. textPathStartOffset = parsedStyle.textPathStartOffset,
  13436. _parsedStyle$leading = parsedStyle.leading,
  13437. leading = _parsedStyle$leading === void 0 ? 0 : _parsedStyle$leading;
  13438. var font = toFontString(parsedStyle);
  13439. // if (runtime.enableCSSParsing) {
  13440. var fontProperties = this.measureFont(font, offscreenCanvas);
  13441. // fallback in case UA disallow canvas data extraction
  13442. // (toDataURI, getImageData functions)
  13443. if (fontProperties.fontSize === 0) {
  13444. fontProperties.fontSize = fontSize;
  13445. fontProperties.ascent = fontSize;
  13446. }
  13447. // } else {
  13448. // fontProperties = {
  13449. // fontSize,
  13450. // };
  13451. // }
  13452. var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
  13453. context.font = font;
  13454. // no overflowing by default
  13455. parsedStyle.isOverflowing = false;
  13456. var outputText = wordWrap ? this.wordWrap(text, parsedStyle, offscreenCanvas) : text;
  13457. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  13458. var lineWidths = new Array(lines.length);
  13459. var maxLineWidth = 0;
  13460. // account for textPath
  13461. if (textPath) {
  13462. var totalPathLength = textPath.getTotalLength();
  13463. // const startingPoint = textPath.getPoint(0);
  13464. for (var i = 0; i < lines.length; i++) {
  13465. var width = context.measureText(lines[i]).width + (lines[i].length - 1) * letterSpacing;
  13466. // for (
  13467. // let i = reverse ? lines[0].length - 1 : 0;
  13468. // reverse ? i >= 0 : i < lines[0].length;
  13469. // reverse ? i-- : i++
  13470. // ) {
  13471. // graphemeInfo = lineBounds[i];
  13472. // if (positionInPath > totalPathLength) {
  13473. // positionInPath %= totalPathLength;
  13474. // } else if (positionInPath < 0) {
  13475. // positionInPath += totalPathLength;
  13476. // }
  13477. // // it would probably much faster to send all the grapheme position for a line
  13478. // // and calculate path position/angle at once.
  13479. // this.setGraphemeOnPath(
  13480. // positionInPath,
  13481. // graphemeInfo,
  13482. // startingPoint
  13483. // );
  13484. // positionInPath += graphemeInfo.kernedWidth;
  13485. // }
  13486. }
  13487. } else {
  13488. for (var _i = 0; _i < lines.length; _i++) {
  13489. // char width + letterSpacing
  13490. var _lineWidth = context.measureText(lines[_i]).width + (lines[_i].length - 1) * letterSpacing;
  13491. lineWidths[_i] = _lineWidth;
  13492. maxLineWidth = Math.max(maxLineWidth, _lineWidth);
  13493. }
  13494. var _width = maxLineWidth + lineWidth;
  13495. // if (dropShadow) {
  13496. // width += dropShadowDistance;
  13497. // }
  13498. var lineHeight = strokeHeight || fontProperties.fontSize + lineWidth;
  13499. var height = Math.max(lineHeight, fontProperties.fontSize + lineWidth) + (lines.length - 1) * (lineHeight + leading);
  13500. // if (dropShadow) {
  13501. // height += dropShadowDistance;
  13502. // }
  13503. lineHeight += leading;
  13504. // handle vertical text baseline
  13505. var offsetY = 0;
  13506. if (textBaseline === 'middle') {
  13507. offsetY = -height / 2;
  13508. } else if (textBaseline === 'bottom' || textBaseline === 'alphabetic' || textBaseline === 'ideographic') {
  13509. offsetY = -height;
  13510. } else if (textBaseline === 'top' || textBaseline === 'hanging') {
  13511. offsetY = 0;
  13512. }
  13513. return {
  13514. font: font,
  13515. width: _width,
  13516. height: height,
  13517. lines: lines,
  13518. lineWidths: lineWidths,
  13519. lineHeight: lineHeight,
  13520. maxLineWidth: maxLineWidth,
  13521. fontProperties: fontProperties,
  13522. lineMetrics: lineWidths.map(function (width, i) {
  13523. var offsetX = 0;
  13524. // handle horizontal text align
  13525. if (textAlign === 'center' || textAlign === 'middle') {
  13526. offsetX -= width / 2;
  13527. } else if (textAlign === 'right' || textAlign === 'end') {
  13528. offsetX -= width;
  13529. }
  13530. return new Rectangle(offsetX - lineWidth / 2, offsetY + i * lineHeight, width + lineWidth, lineHeight);
  13531. })
  13532. };
  13533. }
  13534. };
  13535. _proto.setGraphemeOnPath = function setGraphemeOnPath() {};
  13536. _proto.wordWrap = function wordWrap(text, parsedStyle, offscreenCanvas) {
  13537. var _this2 = this;
  13538. var _parsedStyle$wordWrap = parsedStyle.wordWrapWidth,
  13539. wordWrapWidth = _parsedStyle$wordWrap === void 0 ? 0 : _parsedStyle$wordWrap,
  13540. letterSpacing = parsedStyle.letterSpacing,
  13541. _parsedStyle$maxLines = parsedStyle.maxLines,
  13542. maxLines = _parsedStyle$maxLines === void 0 ? Infinity : _parsedStyle$maxLines,
  13543. textOverflow = parsedStyle.textOverflow;
  13544. var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
  13545. var maxWidth = wordWrapWidth + letterSpacing;
  13546. var ellipsis = '';
  13547. if (textOverflow === 'ellipsis') {
  13548. ellipsis = '...';
  13549. } else if (textOverflow && textOverflow !== 'clip') {
  13550. ellipsis = textOverflow;
  13551. }
  13552. var lines = [];
  13553. var currentIndex = 0;
  13554. var currentWidth = 0;
  13555. var cache = {};
  13556. var calcWidth = function calcWidth(char) {
  13557. return _this2.getFromCache(char, letterSpacing, cache, context);
  13558. };
  13559. var ellipsisWidth = Array.from(ellipsis).reduce(function (prev, cur) {
  13560. return prev + calcWidth(cur);
  13561. }, 0);
  13562. var chars = Array.from(text);
  13563. for (var i = 0; i < chars.length; i++) {
  13564. var char = chars[i];
  13565. var prevChar = text[i - 1];
  13566. var nextChar = text[i + 1];
  13567. var charWidth = calcWidth(char);
  13568. if (this.isNewline(char)) {
  13569. currentIndex++;
  13570. // exceed maxLines, break immediately
  13571. if (currentIndex >= maxLines) {
  13572. parsedStyle.isOverflowing = true;
  13573. break;
  13574. }
  13575. currentWidth = 0;
  13576. lines[currentIndex] = '';
  13577. continue;
  13578. }
  13579. if (currentWidth > 0 && currentWidth + charWidth > maxWidth) {
  13580. if (currentIndex + 1 >= maxLines) {
  13581. parsedStyle.isOverflowing = true;
  13582. // If there is not enough space to display the string itself, it is clipped.
  13583. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#values
  13584. if (ellipsisWidth > 0 && ellipsisWidth <= maxWidth) {
  13585. // Backspace from line's end.
  13586. var currentLineLength = lines[currentIndex].length;
  13587. var lastLineWidth = 0;
  13588. var lastLineIndex = currentLineLength;
  13589. for (var _i2 = 0; _i2 < currentLineLength; _i2++) {
  13590. var width = calcWidth(lines[currentIndex][_i2]);
  13591. if (lastLineWidth + width + ellipsisWidth > maxWidth) {
  13592. lastLineIndex = _i2;
  13593. break;
  13594. }
  13595. lastLineWidth += width;
  13596. }
  13597. lines[currentIndex] = (lines[currentIndex] || '').slice(0, lastLineIndex) + ellipsis;
  13598. }
  13599. break;
  13600. }
  13601. currentIndex++;
  13602. currentWidth = 0;
  13603. lines[currentIndex] = '';
  13604. if (this.isBreakingSpace(char)) {
  13605. continue;
  13606. }
  13607. if (!this.canBreakInLastChar(char)) {
  13608. lines = this.trimToBreakable(lines);
  13609. currentWidth = this.sumTextWidthByCache(lines[currentIndex] || '', cache);
  13610. }
  13611. if (this.shouldBreakByKinsokuShorui(char, nextChar)) {
  13612. lines = this.trimByKinsokuShorui(lines);
  13613. currentWidth += calcWidth(prevChar || '');
  13614. }
  13615. }
  13616. currentWidth += charWidth;
  13617. lines[currentIndex] = (lines[currentIndex] || '') + char;
  13618. }
  13619. return lines.join('\n');
  13620. };
  13621. _proto.isBreakingSpace = function isBreakingSpace(char) {
  13622. if (typeof char !== 'string') {
  13623. return false;
  13624. }
  13625. return TEXT_METRICS.BreakingSpaces.indexOf(char.charCodeAt(0)) >= 0;
  13626. };
  13627. _proto.isNewline = function isNewline(char) {
  13628. if (typeof char !== 'string') {
  13629. return false;
  13630. }
  13631. return TEXT_METRICS.Newlines.indexOf(char.charCodeAt(0)) >= 0;
  13632. };
  13633. _proto.trimToBreakable = function trimToBreakable(prev) {
  13634. var next = [].concat(prev);
  13635. var prevLine = next[next.length - 2];
  13636. var index = this.findBreakableIndex(prevLine);
  13637. if (index === -1 || !prevLine) return next;
  13638. var trimmedChar = prevLine.slice(index, index + 1);
  13639. var isTrimmedWithSpace = this.isBreakingSpace(trimmedChar);
  13640. var trimFrom = index + 1;
  13641. var trimTo = index + (isTrimmedWithSpace ? 0 : 1);
  13642. next[next.length - 1] += prevLine.slice(trimFrom, prevLine.length);
  13643. next[next.length - 2] = prevLine.slice(0, trimTo);
  13644. return next;
  13645. };
  13646. _proto.canBreakInLastChar = function canBreakInLastChar(char) {
  13647. if (char && LATIN_REGEX.test(char)) return false;
  13648. return true;
  13649. };
  13650. _proto.sumTextWidthByCache = function sumTextWidthByCache(text, cache) {
  13651. return text.split('').reduce(function (sum, c) {
  13652. if (!cache[c]) throw Error('cannot count the word without cache');
  13653. return sum + cache[c];
  13654. }, 0);
  13655. };
  13656. _proto.findBreakableIndex = function findBreakableIndex(line) {
  13657. for (var i = line.length - 1; i >= 0; i--) {
  13658. if (!LATIN_REGEX.test(line[i])) return i;
  13659. }
  13660. return -1;
  13661. };
  13662. _proto.getFromCache = function getFromCache(key, letterSpacing, cache, context) {
  13663. var width = cache[key];
  13664. if (typeof width !== 'number') {
  13665. var spacing = key.length * letterSpacing;
  13666. width = context.measureText(key).width + spacing;
  13667. cache[key] = width;
  13668. }
  13669. return width;
  13670. };
  13671. return TextService;
  13672. }();
  13673. var _this = undefined;
  13674. var runtime = {};
  13675. /**
  13676. * Replace with IoC container
  13677. */
  13678. var geometryUpdaterFactory = function () {
  13679. var _ref;
  13680. var rectUpdater = new RectUpdater();
  13681. var polylineUpdater = new PolylineUpdater();
  13682. return _ref = {}, _ref[exports.Shape.CIRCLE] = new CircleUpdater(), _ref[exports.Shape.ELLIPSE] = new EllipseUpdater(), _ref[exports.Shape.RECT] = rectUpdater, _ref[exports.Shape.IMAGE] = rectUpdater, _ref[exports.Shape.GROUP] = rectUpdater, _ref[exports.Shape.LINE] = new LineUpdater(), _ref[exports.Shape.TEXT] = new TextUpdater(runtime), _ref[exports.Shape.POLYLINE] = polylineUpdater, _ref[exports.Shape.POLYGON] = polylineUpdater, _ref[exports.Shape.PATH] = new PathUpdater(), _ref[exports.Shape.HTML] = null, _ref[exports.Shape.MESH] = null, _ref;
  13683. }();
  13684. var CSSPropertySyntaxFactory = function () {
  13685. var _ref2;
  13686. var color = new CSSPropertyColor();
  13687. var length = new CSSPropertyLengthOrPercentage();
  13688. return _ref2 = {}, _ref2[exports.PropertySyntax.PERCENTAGE] = null, _ref2[exports.PropertySyntax.NUMBER] = new CSSPropertyNumber(), _ref2[exports.PropertySyntax.ANGLE] = new CSSPropertyAngle(), _ref2[exports.PropertySyntax.DEFINED_PATH] = new CSSPropertyClipPath(), _ref2[exports.PropertySyntax.PAINT] = color, _ref2[exports.PropertySyntax.COLOR] = color, _ref2[exports.PropertySyntax.FILTER] = new CSSPropertyFilter(), _ref2[exports.PropertySyntax.LENGTH] = length, _ref2[exports.PropertySyntax.LENGTH_PERCENTAGE] = length, _ref2[exports.PropertySyntax.LENGTH_PERCENTAGE_12] = new CSSPropertyLengthOrPercentage12(), _ref2[exports.PropertySyntax.LENGTH_PERCENTAGE_14] = new CSSPropertyLengthOrPercentage14(), _ref2[exports.PropertySyntax.COORDINATE] = new CSSPropertyLocalPosition(), _ref2[exports.PropertySyntax.OFFSET_DISTANCE] = new CSSPropertyOffsetDistance(), _ref2[exports.PropertySyntax.OPACITY_VALUE] = new CSSPropertyOpacity(), _ref2[exports.PropertySyntax.PATH] = new CSSPropertyPath(), _ref2[exports.PropertySyntax.LIST_OF_POINTS] = new CSSPropertyPoints(), _ref2[exports.PropertySyntax.SHADOW_BLUR] = new CSSPropertyShadowBlur(), _ref2[exports.PropertySyntax.TEXT] = new CSSPropertyText(), _ref2[exports.PropertySyntax.TEXT_TRANSFORM] = new CSSPropertyTextTransform(), _ref2[exports.PropertySyntax.TRANSFORM] = new CSSPropertyTransform(), _ref2[exports.PropertySyntax.TRANSFORM_ORIGIN] = new CSSPropertyTransformOrigin(), _ref2[exports.PropertySyntax.Z_INDEX] = new CSSPropertyZIndex(), _ref2[exports.PropertySyntax.MARKER] = new CSSPropertyMarker(), _ref2;
  13689. }();
  13690. var getGlobalThis = function getGlobalThis() {
  13691. if (typeof globalThis !== 'undefined') return globalThis;
  13692. if (typeof self !== 'undefined') return self;
  13693. if (typeof window !== 'undefined') return window;
  13694. // @ts-ignore
  13695. if (typeof global !== 'undefined') return global;
  13696. if (typeof _this !== 'undefined') return _this;
  13697. throw new Error('Unable to locate global `this`');
  13698. };
  13699. /**
  13700. * Camera
  13701. * `g-camera-api` will provide an advanced implementation
  13702. */
  13703. runtime.CameraContribution = Camera;
  13704. /**
  13705. * `g-web-animations-api` will provide an AnimationTimeline
  13706. */
  13707. runtime.AnimationTimeline = null;
  13708. runtime.EasingFunction = null;
  13709. runtime.offscreenCanvas = new OffscreenCanvasCreator();
  13710. runtime.nativeHTMLMap = new WeakMap();
  13711. runtime.sceneGraphSelector = new DefaultSceneGraphSelector();
  13712. runtime.sceneGraphService = new DefaultSceneGraphService(runtime);
  13713. runtime.textService = new TextService(runtime);
  13714. runtime.geometryUpdaterFactory = geometryUpdaterFactory;
  13715. runtime.CSSPropertySyntaxFactory = CSSPropertySyntaxFactory;
  13716. runtime.styleValueRegistry = new DefaultStyleValueRegistry();
  13717. runtime.layoutRegistry = null;
  13718. runtime.globalThis = getGlobalThis();
  13719. runtime.enableCSSParsing = true;
  13720. runtime.enableDataset = false;
  13721. runtime.enableStyleSyntax = true;
  13722. var AbstractRendererPlugin = /*#__PURE__*/function () {
  13723. function AbstractRendererPlugin() {
  13724. this.context = void 0;
  13725. this.plugins = [];
  13726. }
  13727. var _proto = AbstractRendererPlugin.prototype;
  13728. _proto.addRenderingPlugin = function addRenderingPlugin(plugin) {
  13729. this.plugins.push(plugin);
  13730. this.context.renderingPlugins.push(plugin);
  13731. };
  13732. _proto.removeAllRenderingPlugins = function removeAllRenderingPlugins() {
  13733. var _this = this;
  13734. this.plugins.forEach(function (plugin) {
  13735. var index = _this.context.renderingPlugins.indexOf(plugin);
  13736. if (index >= 0) {
  13737. _this.context.renderingPlugins.splice(index, 1);
  13738. }
  13739. });
  13740. };
  13741. return AbstractRendererPlugin;
  13742. }();
  13743. var AbstractRenderer = /*#__PURE__*/function () {
  13744. function AbstractRenderer(config) {
  13745. this.plugins = [];
  13746. this.config = void 0;
  13747. this.config = _extends({
  13748. /**
  13749. * only dirty object will cause re-render
  13750. */
  13751. enableDirtyCheck: true,
  13752. enableCulling: false,
  13753. /**
  13754. * enable auto rendering by default
  13755. */
  13756. enableAutoRendering: true,
  13757. /**
  13758. * enable dirty rectangle rendering by default
  13759. */
  13760. enableDirtyRectangleRendering: true,
  13761. enableDirtyRectangleRenderingDebug: false
  13762. }, config);
  13763. }
  13764. var _proto2 = AbstractRenderer.prototype;
  13765. _proto2.registerPlugin = function registerPlugin(plugin) {
  13766. var index = this.plugins.findIndex(function (p) {
  13767. return p === plugin;
  13768. });
  13769. if (index === -1) {
  13770. this.plugins.push(plugin);
  13771. }
  13772. };
  13773. _proto2.unregisterPlugin = function unregisterPlugin(plugin) {
  13774. var index = this.plugins.findIndex(function (p) {
  13775. return p === plugin;
  13776. });
  13777. if (index > -1) {
  13778. this.plugins.splice(index, 1);
  13779. }
  13780. };
  13781. _proto2.getPlugins = function getPlugins() {
  13782. return this.plugins;
  13783. };
  13784. _proto2.getPlugin = function getPlugin(name) {
  13785. return this.plugins.find(function (plugin) {
  13786. return plugin.name === name;
  13787. });
  13788. };
  13789. _proto2.getConfig = function getConfig() {
  13790. return this.config;
  13791. };
  13792. _proto2.setConfig = function setConfig(config) {
  13793. Object.assign(this.config, config);
  13794. };
  13795. return AbstractRenderer;
  13796. }();
  13797. /**
  13798. * apply following rules:
  13799. * 1. `visibility` in scenegraph node
  13800. * 2. other custom culling strategies, eg. frustum culling
  13801. */
  13802. var CullingPlugin = /*#__PURE__*/function () {
  13803. function CullingPlugin(strategies) {
  13804. this.strategies = void 0;
  13805. this.strategies = strategies;
  13806. }
  13807. var _proto = CullingPlugin.prototype;
  13808. _proto.apply = function apply(context) {
  13809. var camera = context.camera,
  13810. renderingService = context.renderingService,
  13811. renderingContext = context.renderingContext;
  13812. var strategies = this.strategies;
  13813. renderingService.hooks.cull.tap(CullingPlugin.tag, function (object) {
  13814. if (object) {
  13815. var cullable = object.cullable;
  13816. // cullable.visible = true;
  13817. // const renderBounds = object.getRenderBounds();
  13818. // if (AABB.isEmpty(renderBounds)) {
  13819. // cullable.visible = false;
  13820. // } else {
  13821. // const isShape2D = shape2D.indexOf(object.nodeName as Shape) > -1;
  13822. // const [p0, p1, p2, p3] = camera.getFrustum().planes;
  13823. // tmpAABB.setMinMax([-p1.distance, -p3.distance, 0], [p0.distance, p2.distance, 0]);
  13824. // cullable.visible = isShape2D ? renderBounds.intersects(tmpAABB) : true;
  13825. // }
  13826. if (strategies.length === 0) {
  13827. cullable.visible = renderingContext.unculledEntities.indexOf(object.entity) > -1;
  13828. } else {
  13829. // eg. implemented by g-webgl(frustum culling)
  13830. cullable.visible = strategies.every(function (strategy) {
  13831. return strategy.isVisible(camera, object);
  13832. });
  13833. }
  13834. if (!object.isCulled() && object.isVisible()) {
  13835. return object;
  13836. } else {
  13837. // if (this.renderingContext.renderListLastFrame.indexOf(object) > -1) {
  13838. object.dispatchEvent(new CustomEvent(exports.ElementEvent.CULLED));
  13839. // }
  13840. }
  13841. return null;
  13842. }
  13843. return object;
  13844. });
  13845. renderingService.hooks.afterRender.tap(CullingPlugin.tag, function (object) {
  13846. object.cullable.visibilityPlaneMask = -1;
  13847. });
  13848. };
  13849. return CullingPlugin;
  13850. }();
  13851. CullingPlugin.tag = 'Culling';
  13852. /**
  13853. * Filter dirty renderables and calculate the "dirty rectangle" which will be clear when frame began
  13854. */
  13855. var DirtyCheckPlugin = /*#__PURE__*/function () {
  13856. function DirtyCheckPlugin() {}
  13857. var _proto = DirtyCheckPlugin.prototype;
  13858. _proto.apply = function apply(context) {
  13859. var renderingService = context.renderingService;
  13860. renderingService.hooks.dirtycheck.tap(DirtyCheckPlugin.tag, function (object) {
  13861. if (object) {
  13862. var renderable = object.renderable;
  13863. var isDirty = renderable.dirty || renderingService.disableDirtyRectangleRendering();
  13864. if (isDirty) {
  13865. return object;
  13866. } else {
  13867. return null;
  13868. }
  13869. }
  13870. return object;
  13871. });
  13872. };
  13873. return DirtyCheckPlugin;
  13874. }();
  13875. DirtyCheckPlugin.tag = 'DirtyCheck';
  13876. /**
  13877. * support mouse & touch events
  13878. * @see https://github.com/pixijs/pixi.js/blob/dev/packages/interaction/README.md
  13879. *
  13880. * also provide some extra events such as `drag`
  13881. */
  13882. var EventPlugin = /*#__PURE__*/function () {
  13883. function EventPlugin() {
  13884. var _this = this;
  13885. this.autoPreventDefault = false;
  13886. this.rootPointerEvent = new FederatedPointerEvent(null);
  13887. this.rootWheelEvent = new FederatedWheelEvent(null);
  13888. this.context = void 0;
  13889. this.onPointerMove = function (nativeEvent) {
  13890. var _this$context$renderi, _this$context$renderi2;
  13891. var canvas = (_this$context$renderi = _this.context.renderingContext.root) === null || _this$context$renderi === void 0 ? void 0 : (_this$context$renderi2 = _this$context$renderi.ownerDocument) === null || _this$context$renderi2 === void 0 ? void 0 : _this$context$renderi2.defaultView;
  13892. if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
  13893. var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
  13894. for (var _iterator = _createForOfIteratorHelperLoose(normalizedEvents), _step; !(_step = _iterator()).done;) {
  13895. var normalizedEvent = _step.value;
  13896. var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13897. _this.context.eventService.mapEvent(event);
  13898. }
  13899. _this.setCursor(_this.context.eventService.cursor);
  13900. };
  13901. this.onClick = function (nativeEvent) {
  13902. var _this$context$renderi3, _this$context$renderi4;
  13903. var canvas = (_this$context$renderi3 = _this.context.renderingContext.root) === null || _this$context$renderi3 === void 0 ? void 0 : (_this$context$renderi4 = _this$context$renderi3.ownerDocument) === null || _this$context$renderi4 === void 0 ? void 0 : _this$context$renderi4.defaultView;
  13904. var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
  13905. for (var _iterator2 = _createForOfIteratorHelperLoose(normalizedEvents), _step2; !(_step2 = _iterator2()).done;) {
  13906. var normalizedEvent = _step2.value;
  13907. var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13908. _this.context.eventService.mapEvent(event);
  13909. }
  13910. _this.setCursor(_this.context.eventService.cursor);
  13911. };
  13912. }
  13913. var _proto = EventPlugin.prototype;
  13914. _proto.apply = function apply(context) {
  13915. var _this2 = this;
  13916. this.context = context;
  13917. var renderingService = context.renderingService;
  13918. var canvas = this.context.renderingContext.root.ownerDocument.defaultView;
  13919. this.context.eventService.setPickHandler(function (position) {
  13920. var _this2$context$render = _this2.context.renderingService.hooks.pickSync.call({
  13921. position: position,
  13922. picked: [],
  13923. topmost: true // we only concern the topmost element
  13924. }),
  13925. picked = _this2$context$render.picked;
  13926. return picked[0] || null;
  13927. });
  13928. renderingService.hooks.pointerWheel.tap(EventPlugin.tag, function (nativeEvent) {
  13929. var wheelEvent = _this2.normalizeWheelEvent(nativeEvent);
  13930. _this2.context.eventService.mapEvent(wheelEvent);
  13931. });
  13932. renderingService.hooks.pointerDown.tap(EventPlugin.tag, function (nativeEvent) {
  13933. if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
  13934. var events = _this2.normalizeToPointerEvent(nativeEvent, canvas);
  13935. if (_this2.autoPreventDefault && events[0].isNormalized) {
  13936. var cancelable = nativeEvent.cancelable || !('cancelable' in nativeEvent);
  13937. if (cancelable) {
  13938. nativeEvent.preventDefault();
  13939. }
  13940. }
  13941. for (var _iterator3 = _createForOfIteratorHelperLoose(events), _step3; !(_step3 = _iterator3()).done;) {
  13942. var event = _step3.value;
  13943. var federatedEvent = _this2.bootstrapEvent(_this2.rootPointerEvent, event, canvas, nativeEvent);
  13944. _this2.context.eventService.mapEvent(federatedEvent);
  13945. }
  13946. _this2.setCursor(_this2.context.eventService.cursor);
  13947. });
  13948. renderingService.hooks.pointerUp.tap(EventPlugin.tag, function (nativeEvent) {
  13949. if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
  13950. // account for element in SVG
  13951. var $element = _this2.context.contextService.getDomElement();
  13952. var outside = 'outside';
  13953. try {
  13954. outside = $element && nativeEvent.target && nativeEvent.target !== $element && $element.contains && !$element.contains(nativeEvent.target) ? 'outside' : '';
  13955. } catch (e) {
  13956. // nativeEvent.target maybe not Node, such as Window
  13957. // @see https://github.com/antvis/G/issues/1235
  13958. }
  13959. var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
  13960. for (var _iterator4 = _createForOfIteratorHelperLoose(normalizedEvents), _step4; !(_step4 = _iterator4()).done;) {
  13961. var normalizedEvent = _step4.value;
  13962. var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13963. event.type += outside;
  13964. _this2.context.eventService.mapEvent(event);
  13965. }
  13966. _this2.setCursor(_this2.context.eventService.cursor);
  13967. });
  13968. renderingService.hooks.pointerMove.tap(EventPlugin.tag, this.onPointerMove);
  13969. renderingService.hooks.pointerOver.tap(EventPlugin.tag, this.onPointerMove);
  13970. renderingService.hooks.pointerOut.tap(EventPlugin.tag, this.onPointerMove);
  13971. renderingService.hooks.click.tap(EventPlugin.tag, this.onClick);
  13972. renderingService.hooks.pointerCancel.tap(EventPlugin.tag, function (nativeEvent) {
  13973. var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
  13974. for (var _iterator5 = _createForOfIteratorHelperLoose(normalizedEvents), _step5; !(_step5 = _iterator5()).done;) {
  13975. var normalizedEvent = _step5.value;
  13976. var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13977. _this2.context.eventService.mapEvent(event);
  13978. }
  13979. _this2.setCursor(_this2.context.eventService.cursor);
  13980. });
  13981. };
  13982. _proto.getViewportXY = function getViewportXY(nativeEvent) {
  13983. var x;
  13984. var y;
  13985. /**
  13986. * Should account for CSS Transform applied on container.
  13987. * @see https://github.com/antvis/G/issues/1161
  13988. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/offsetX
  13989. */
  13990. var offsetX = nativeEvent.offsetX,
  13991. offsetY = nativeEvent.offsetY,
  13992. clientX = nativeEvent.clientX,
  13993. clientY = nativeEvent.clientY;
  13994. if (this.context.config.supportsCSSTransform && !util.isNil(offsetX) && !util.isNil(offsetY)) {
  13995. x = offsetX;
  13996. y = offsetY;
  13997. } else {
  13998. var point = this.context.eventService.client2Viewport(new Point(clientX, clientY));
  13999. x = point.x;
  14000. y = point.y;
  14001. }
  14002. return {
  14003. x: x,
  14004. y: y
  14005. };
  14006. };
  14007. _proto.bootstrapEvent = function bootstrapEvent(event, normalizedEvent, view, nativeEvent) {
  14008. event.view = view;
  14009. event.originalEvent = null;
  14010. event.nativeEvent = nativeEvent;
  14011. event.pointerId = normalizedEvent.pointerId;
  14012. event.width = normalizedEvent.width;
  14013. event.height = normalizedEvent.height;
  14014. event.isPrimary = normalizedEvent.isPrimary;
  14015. event.pointerType = normalizedEvent.pointerType;
  14016. event.pressure = normalizedEvent.pressure;
  14017. event.tangentialPressure = normalizedEvent.tangentialPressure;
  14018. event.tiltX = normalizedEvent.tiltX;
  14019. event.tiltY = normalizedEvent.tiltY;
  14020. event.twist = normalizedEvent.twist;
  14021. this.transferMouseData(event, normalizedEvent);
  14022. var _this$getViewportXY = this.getViewportXY(normalizedEvent),
  14023. x = _this$getViewportXY.x,
  14024. y = _this$getViewportXY.y;
  14025. event.viewport.x = x;
  14026. event.viewport.y = y;
  14027. var _this$context$eventSe = this.context.eventService.viewport2Canvas(event.viewport),
  14028. canvasX = _this$context$eventSe.x,
  14029. canvasY = _this$context$eventSe.y;
  14030. event.canvas.x = canvasX;
  14031. event.canvas.y = canvasY;
  14032. event.global.copyFrom(event.canvas);
  14033. event.offset.copyFrom(event.canvas);
  14034. event.isTrusted = nativeEvent.isTrusted;
  14035. if (event.type === 'pointerleave') {
  14036. event.type = 'pointerout';
  14037. }
  14038. if (event.type.startsWith('mouse')) {
  14039. event.type = event.type.replace('mouse', 'pointer');
  14040. }
  14041. if (event.type.startsWith('touch')) {
  14042. event.type = TOUCH_TO_POINTER[event.type] || event.type;
  14043. }
  14044. return event;
  14045. };
  14046. _proto.normalizeWheelEvent = function normalizeWheelEvent(nativeEvent) {
  14047. var event = this.rootWheelEvent;
  14048. this.transferMouseData(event, nativeEvent);
  14049. event.deltaMode = nativeEvent.deltaMode;
  14050. event.deltaX = nativeEvent.deltaX;
  14051. event.deltaY = nativeEvent.deltaY;
  14052. event.deltaZ = nativeEvent.deltaZ;
  14053. var _this$getViewportXY2 = this.getViewportXY(nativeEvent),
  14054. x = _this$getViewportXY2.x,
  14055. y = _this$getViewportXY2.y;
  14056. event.viewport.x = x;
  14057. event.viewport.y = y;
  14058. var _this$context$eventSe2 = this.context.eventService.viewport2Canvas(event.viewport),
  14059. canvasX = _this$context$eventSe2.x,
  14060. canvasY = _this$context$eventSe2.y;
  14061. event.canvas.x = canvasX;
  14062. event.canvas.y = canvasY;
  14063. event.global.copyFrom(event.canvas);
  14064. event.offset.copyFrom(event.canvas);
  14065. event.nativeEvent = nativeEvent;
  14066. event.type = nativeEvent.type;
  14067. return event;
  14068. }
  14069. /**
  14070. * Transfers base & mouse event data from the nativeEvent to the federated event.
  14071. */;
  14072. _proto.transferMouseData = function transferMouseData(event, nativeEvent) {
  14073. event.isTrusted = nativeEvent.isTrusted;
  14074. event.srcElement = nativeEvent.srcElement;
  14075. event.timeStamp = performance.now();
  14076. event.type = nativeEvent.type;
  14077. event.altKey = nativeEvent.altKey;
  14078. event.metaKey = nativeEvent.metaKey;
  14079. event.shiftKey = nativeEvent.shiftKey;
  14080. event.ctrlKey = nativeEvent.ctrlKey;
  14081. event.button = nativeEvent.button;
  14082. event.buttons = nativeEvent.buttons;
  14083. event.client.x = nativeEvent.clientX;
  14084. event.client.y = nativeEvent.clientY;
  14085. event.movement.x = nativeEvent.movementX;
  14086. event.movement.y = nativeEvent.movementY;
  14087. event.page.x = nativeEvent.pageX;
  14088. event.page.y = nativeEvent.pageY;
  14089. event.screen.x = nativeEvent.screenX;
  14090. event.screen.y = nativeEvent.screenY;
  14091. event.relatedTarget = null;
  14092. };
  14093. _proto.setCursor = function setCursor(cursor) {
  14094. this.context.contextService.applyCursorStyle(cursor || this.context.config.cursor || 'default');
  14095. };
  14096. _proto.normalizeToPointerEvent = function normalizeToPointerEvent(event, canvas) {
  14097. var normalizedEvents = [];
  14098. if (canvas.isTouchEvent(event)) {
  14099. for (var i = 0; i < event.changedTouches.length; i++) {
  14100. var touch = event.changedTouches[i];
  14101. // use changedTouches instead of touches since touchend has no touches
  14102. // @see https://stackoverflow.com/a/10079076
  14103. if (util.isUndefined(touch.button)) touch.button = 0;
  14104. if (util.isUndefined(touch.buttons)) touch.buttons = 1;
  14105. if (util.isUndefined(touch.isPrimary)) {
  14106. touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
  14107. }
  14108. if (util.isUndefined(touch.width)) touch.width = touch.radiusX || 1;
  14109. if (util.isUndefined(touch.height)) touch.height = touch.radiusY || 1;
  14110. if (util.isUndefined(touch.tiltX)) touch.tiltX = 0;
  14111. if (util.isUndefined(touch.tiltY)) touch.tiltY = 0;
  14112. if (util.isUndefined(touch.pointerType)) touch.pointerType = 'touch';
  14113. // @see https://developer.mozilla.org/zh-CN/docs/Web/API/Touch/identifier
  14114. if (util.isUndefined(touch.pointerId)) touch.pointerId = touch.identifier || 0;
  14115. if (util.isUndefined(touch.pressure)) touch.pressure = touch.force || 0.5;
  14116. if (util.isUndefined(touch.twist)) touch.twist = 0;
  14117. if (util.isUndefined(touch.tangentialPressure)) touch.tangentialPressure = 0;
  14118. touch.isNormalized = true;
  14119. touch.type = event.type;
  14120. normalizedEvents.push(touch);
  14121. }
  14122. } else if (canvas.isMouseEvent(event)) {
  14123. var tempEvent = event;
  14124. if (util.isUndefined(tempEvent.isPrimary)) tempEvent.isPrimary = true;
  14125. if (util.isUndefined(tempEvent.width)) tempEvent.width = 1;
  14126. if (util.isUndefined(tempEvent.height)) tempEvent.height = 1;
  14127. if (util.isUndefined(tempEvent.tiltX)) tempEvent.tiltX = 0;
  14128. if (util.isUndefined(tempEvent.tiltY)) tempEvent.tiltY = 0;
  14129. if (util.isUndefined(tempEvent.pointerType)) tempEvent.pointerType = 'mouse';
  14130. if (util.isUndefined(tempEvent.pointerId)) tempEvent.pointerId = MOUSE_POINTER_ID;
  14131. if (util.isUndefined(tempEvent.pressure)) tempEvent.pressure = 0.5;
  14132. if (util.isUndefined(tempEvent.twist)) tempEvent.twist = 0;
  14133. if (util.isUndefined(tempEvent.tangentialPressure)) tempEvent.tangentialPressure = 0;
  14134. tempEvent.isNormalized = true;
  14135. normalizedEvents.push(tempEvent);
  14136. } else {
  14137. normalizedEvents.push(event);
  14138. }
  14139. return normalizedEvents;
  14140. };
  14141. return EventPlugin;
  14142. }();
  14143. EventPlugin.tag = 'Event';
  14144. // group is not a 2d shape
  14145. var shape2D = [exports.Shape.CIRCLE, exports.Shape.ELLIPSE, exports.Shape.IMAGE, exports.Shape.RECT, exports.Shape.LINE, exports.Shape.POLYLINE, exports.Shape.POLYGON, exports.Shape.TEXT, exports.Shape.PATH, exports.Shape.HTML];
  14146. var FrustumCullingStrategy = /*#__PURE__*/function () {
  14147. function FrustumCullingStrategy() {}
  14148. var _proto = FrustumCullingStrategy.prototype;
  14149. _proto.isVisible = function isVisible(camera, object) {
  14150. var _object$parentNode, _object$parentNode$cu;
  14151. // return true;
  14152. var cullable = object.cullable;
  14153. if (!cullable.enable) {
  14154. return true;
  14155. }
  14156. var renderBounds = object.getRenderBounds();
  14157. if (AABB.isEmpty(renderBounds)) {
  14158. return false;
  14159. }
  14160. // get VP matrix from camera
  14161. var frustum = camera.getFrustum();
  14162. var parentVisibilityPlaneMask = (_object$parentNode = object.parentNode) === null || _object$parentNode === void 0 ? void 0 : (_object$parentNode$cu = _object$parentNode.cullable) === null || _object$parentNode$cu === void 0 ? void 0 : _object$parentNode$cu.visibilityPlaneMask;
  14163. cullable.visibilityPlaneMask = this.computeVisibilityWithPlaneMask(object, renderBounds, parentVisibilityPlaneMask || exports.Mask.INDETERMINATE, frustum.planes);
  14164. cullable.visible = cullable.visibilityPlaneMask !== exports.Mask.OUTSIDE;
  14165. return cullable.visible;
  14166. }
  14167. /**
  14168. *
  14169. * @see「Optimized View Frustum Culling Algorithms for Bounding Boxes」
  14170. * @see https://github.com/antvis/GWebGPUEngine/issues/3
  14171. *
  14172. * * 基础相交测试 the basic intersection test
  14173. * * 标记 masking @see https://cesium.com/blog/2015/08/04/fast-hierarchical-culling/
  14174. * * TODO: 平面一致性测试 the plane-coherency test
  14175. * * TODO: 支持 mesh 指定自身的剔除策略,参考 Babylon.js @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
  14176. *
  14177. * @param aabb aabb
  14178. * @param parentPlaneMask mask of parent
  14179. * @param planes planes of frustum
  14180. */;
  14181. _proto.computeVisibilityWithPlaneMask = function computeVisibilityWithPlaneMask(object, aabb, parentPlaneMask, planes) {
  14182. if (parentPlaneMask === exports.Mask.OUTSIDE || parentPlaneMask === exports.Mask.INSIDE) {
  14183. // 父节点完全位于视锥内或者外部,直接返回
  14184. return parentPlaneMask;
  14185. }
  14186. // Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
  14187. // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
  14188. var mask = exports.Mask.INSIDE;
  14189. var isShape2D = shape2D.indexOf(object.nodeName) > -1;
  14190. // Use viewport culling for 2D shapes
  14191. // @see https://github.com/antvis/g/issues/914
  14192. for (var k = 0, len = planes.length; k < len; ++k) {
  14193. // For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.
  14194. var flag = 1 << k;
  14195. if ((parentPlaneMask & flag) === 0) {
  14196. // 父节点处于当前面内部,可以跳过
  14197. continue;
  14198. }
  14199. // skip near & far planes when testing 2D shapes
  14200. if (isShape2D && (k === 4 || k === 5)) {
  14201. continue;
  14202. }
  14203. // p-vertex n-vertex <-|plane p-vertex n-vertex
  14204. // 使用 p-vertex 和 n-vertex 加速,避免进行平面和 aabb 全部顶点的相交检测
  14205. var _planes$k = planes[k],
  14206. normal = _planes$k.normal,
  14207. distance = _planes$k.distance;
  14208. if (glMatrix.vec3.dot(normal, aabb.getPositiveFarPoint(planes[k])) + distance < 0) {
  14209. return exports.Mask.OUTSIDE;
  14210. }
  14211. if (glMatrix.vec3.dot(normal, aabb.getNegativeFarPoint(planes[k])) + distance < 0) {
  14212. // 和当前面相交,对应位置为1,继续检测下一个面
  14213. mask |= flag;
  14214. }
  14215. }
  14216. return mask;
  14217. };
  14218. return FrustumCullingStrategy;
  14219. }();
  14220. var PrepareRendererPlugin = /*#__PURE__*/function () {
  14221. function PrepareRendererPlugin() {
  14222. this.rBush = void 0;
  14223. /**
  14224. * sync to RBush later
  14225. */
  14226. this.toSync = new Set();
  14227. }
  14228. var _proto = PrepareRendererPlugin.prototype;
  14229. // private isFirstTimeRendering = true;
  14230. // private syncing = false;
  14231. _proto.apply = function apply(context) {
  14232. var _this = this;
  14233. var renderingService = context.renderingService,
  14234. renderingContext = context.renderingContext,
  14235. rBushRoot = context.rBushRoot;
  14236. var canvas = renderingContext.root.ownerDocument.defaultView;
  14237. this.rBush = rBushRoot;
  14238. var handleAttributeChanged = function handleAttributeChanged(e) {
  14239. var object = e.target;
  14240. object.renderable.dirty = true;
  14241. renderingService.dirtify();
  14242. };
  14243. var handleBoundsChanged = function handleBoundsChanged(e) {
  14244. var affectChildren = e.detail.affectChildren;
  14245. var object = e.target;
  14246. if (affectChildren) {
  14247. object.forEach(function (node) {
  14248. _this.toSync.add(node);
  14249. });
  14250. }
  14251. var p = object;
  14252. while (p) {
  14253. if (p.renderable) {
  14254. _this.toSync.add(p);
  14255. }
  14256. p = p.parentElement;
  14257. }
  14258. // this.pushToSync(e.composedPath().slice(0, -2) as DisplayObject[]);
  14259. renderingService.dirtify();
  14260. };
  14261. var handleMounted = function handleMounted(e) {
  14262. var object = e.target;
  14263. if (runtime.enableCSSParsing) {
  14264. // recalc style values
  14265. runtime.styleValueRegistry.recalc(object);
  14266. }
  14267. runtime.sceneGraphService.dirtifyToRoot(object);
  14268. renderingService.dirtify();
  14269. };
  14270. var handleUnmounted = function handleUnmounted(e) {
  14271. var object = e.target;
  14272. var rBushNode = object.rBushNode;
  14273. if (rBushNode.aabb) {
  14274. _this.rBush.remove(rBushNode.aabb);
  14275. }
  14276. _this.toSync.delete(object);
  14277. runtime.sceneGraphService.dirtifyToRoot(object);
  14278. renderingService.dirtify();
  14279. };
  14280. renderingService.hooks.init.tap(PrepareRendererPlugin.tag, function () {
  14281. canvas.addEventListener(exports.ElementEvent.MOUNTED, handleMounted);
  14282. canvas.addEventListener(exports.ElementEvent.UNMOUNTED, handleUnmounted);
  14283. canvas.addEventListener(exports.ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
  14284. canvas.addEventListener(exports.ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
  14285. });
  14286. renderingService.hooks.destroy.tap(PrepareRendererPlugin.tag, function () {
  14287. canvas.removeEventListener(exports.ElementEvent.MOUNTED, handleMounted);
  14288. canvas.removeEventListener(exports.ElementEvent.UNMOUNTED, handleUnmounted);
  14289. canvas.removeEventListener(exports.ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
  14290. canvas.removeEventListener(exports.ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
  14291. _this.toSync.clear();
  14292. });
  14293. renderingService.hooks.endFrame.tap(PrepareRendererPlugin.tag, function () {
  14294. // if (this.isFirstTimeRendering) {
  14295. // this.isFirstTimeRendering = false;
  14296. // this.syncing = true;
  14297. // // @see https://github.com/antvis/G/issues/1117
  14298. // setTimeout(() => {
  14299. // this.syncRTree();
  14300. // console.log('fcp...');
  14301. // });
  14302. // } else {
  14303. // console.log('next...');
  14304. _this.syncRTree();
  14305. // }
  14306. });
  14307. };
  14308. _proto.syncRTree = function syncRTree() {
  14309. var _this2 = this;
  14310. // if (this.syncing) {
  14311. // return;
  14312. // }
  14313. // bounds changed, need re-inserting its children
  14314. var bulk = [];
  14315. Array.from(this.toSync)
  14316. // some objects may be removed since last frame
  14317. .filter(function (object) {
  14318. return object.isConnected;
  14319. }).forEach(function (node) {
  14320. var rBushNode = node.rBushNode;
  14321. // clear dirty node
  14322. if (rBushNode && rBushNode.aabb) {
  14323. _this2.rBush.remove(rBushNode.aabb);
  14324. }
  14325. var renderBounds = node.getRenderBounds();
  14326. if (renderBounds) {
  14327. var _renderBounds$getMin = renderBounds.getMin(),
  14328. minX = _renderBounds$getMin[0],
  14329. minY = _renderBounds$getMin[1];
  14330. var _renderBounds$getMax = renderBounds.getMax(),
  14331. maxX = _renderBounds$getMax[0],
  14332. maxY = _renderBounds$getMax[1];
  14333. if (!rBushNode.aabb) {
  14334. rBushNode.aabb = {};
  14335. }
  14336. rBushNode.aabb.displayObject = node;
  14337. rBushNode.aabb.minX = minX;
  14338. rBushNode.aabb.minY = minY;
  14339. rBushNode.aabb.maxX = maxX;
  14340. rBushNode.aabb.maxY = maxY;
  14341. }
  14342. if (rBushNode.aabb) {
  14343. // TODO: NaN occurs when width/height of Rect is 0
  14344. if (!isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.minX) && !isNaN(rBushNode.aabb.minY)) {
  14345. bulk.push(rBushNode.aabb);
  14346. }
  14347. }
  14348. });
  14349. // use bulk inserting, which is ~2-3 times faster
  14350. // @see https://github.com/mourner/rbush#bulk-inserting-data
  14351. this.rBush.load(bulk);
  14352. bulk.length = 0;
  14353. this.toSync.clear();
  14354. // this.syncing = false;
  14355. };
  14356. return PrepareRendererPlugin;
  14357. }();
  14358. PrepareRendererPlugin.tag = 'Prepare';
  14359. function isCanvas(value) {
  14360. return !!value.document;
  14361. }
  14362. (function (CanvasEvent) {
  14363. CanvasEvent["READY"] = "ready";
  14364. CanvasEvent["BEFORE_RENDER"] = "beforerender";
  14365. CanvasEvent["RERENDER"] = "rerender";
  14366. CanvasEvent["AFTER_RENDER"] = "afterrender";
  14367. CanvasEvent["BEFORE_DESTROY"] = "beforedestroy";
  14368. CanvasEvent["AFTER_DESTROY"] = "afterdestroy";
  14369. CanvasEvent["RESIZE"] = "resize";
  14370. CanvasEvent["DIRTY_RECTANGLE"] = "dirtyrectangle";
  14371. CanvasEvent["RENDERER_CHANGED"] = "rendererchanged";
  14372. })(exports.CanvasEvent || (exports.CanvasEvent = {}));
  14373. var DEFAULT_CAMERA_Z = 500;
  14374. var DEFAULT_CAMERA_NEAR = 0.1;
  14375. var DEFAULT_CAMERA_FAR = 1000;
  14376. /**
  14377. * reuse custom event preventing from re-create them in every frame
  14378. */
  14379. var mountedEvent = new CustomEvent(exports.ElementEvent.MOUNTED);
  14380. var unmountedEvent = new CustomEvent(exports.ElementEvent.UNMOUNTED);
  14381. var beforeRenderEvent = new CustomEvent(exports.CanvasEvent.BEFORE_RENDER);
  14382. var rerenderEvent = new CustomEvent(exports.CanvasEvent.RERENDER);
  14383. var afterRenderEvent = new CustomEvent(exports.CanvasEvent.AFTER_RENDER);
  14384. /**
  14385. * can be treated like Window in DOM
  14386. * provide some extra methods like `window`, such as:
  14387. * * `window.requestAnimationFrame`
  14388. * * `window.devicePixelRatio`
  14389. *
  14390. * prototype chains: Canvas(Window) -> EventTarget
  14391. */
  14392. var Canvas = /*#__PURE__*/function (_EventTarget) {
  14393. _inheritsLoose(Canvas, _EventTarget);
  14394. function Canvas(config) {
  14395. var _this;
  14396. _this = _EventTarget.call(this) || this;
  14397. // create document
  14398. /**
  14399. * window.document
  14400. */
  14401. _this.document = void 0;
  14402. /**
  14403. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
  14404. */
  14405. _this.customElements = void 0;
  14406. /**
  14407. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
  14408. */
  14409. _this.requestAnimationFrame = void 0;
  14410. /**
  14411. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
  14412. */
  14413. _this.cancelAnimationFrame = void 0;
  14414. /**
  14415. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  14416. */
  14417. _this.devicePixelRatio = void 0;
  14418. /**
  14419. * whether the runtime supports PointerEvent?
  14420. * if not, the event system won't trigger pointer events like `pointerdown`
  14421. */
  14422. _this.supportsPointerEvents = void 0;
  14423. /**
  14424. * whether the runtime supports TouchEvent?
  14425. * if not, the event system won't trigger touch events like `touchstart`
  14426. */
  14427. _this.supportsTouchEvents = void 0;
  14428. /**
  14429. * is this native event a TouchEvent?
  14430. */
  14431. _this.isTouchEvent = void 0;
  14432. /**
  14433. * is this native event a MouseEvent?
  14434. */
  14435. _this.isMouseEvent = void 0;
  14436. /**
  14437. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element
  14438. */
  14439. _this.Element = DisplayObject;
  14440. /**
  14441. * rAF in auto rendering
  14442. */
  14443. _this.frameId = void 0;
  14444. _this.inited = false;
  14445. _this.readyPromise = void 0;
  14446. _this.resolveReadyPromise = void 0;
  14447. _this.context = {};
  14448. _this.document = new Document();
  14449. _this.document.defaultView = _assertThisInitialized(_this);
  14450. // create registry of custom elements
  14451. _this.customElements = new CustomElementRegistry();
  14452. var container = config.container,
  14453. canvas = config.canvas,
  14454. offscreenCanvas = config.offscreenCanvas,
  14455. width = config.width,
  14456. height = config.height,
  14457. devicePixelRatio = config.devicePixelRatio,
  14458. renderer = config.renderer,
  14459. background = config.background,
  14460. cursor = config.cursor,
  14461. document = config.document,
  14462. requestAnimationFrame = config.requestAnimationFrame,
  14463. cancelAnimationFrame = config.cancelAnimationFrame,
  14464. createImage = config.createImage,
  14465. supportsPointerEvents = config.supportsPointerEvents,
  14466. supportsTouchEvents = config.supportsTouchEvents,
  14467. supportsCSSTransform = config.supportsCSSTransform,
  14468. useNativeClickEvent = config.useNativeClickEvent,
  14469. alwaysTriggerPointerEventOnCanvas = config.alwaysTriggerPointerEventOnCanvas,
  14470. isTouchEvent = config.isTouchEvent,
  14471. isMouseEvent = config.isMouseEvent;
  14472. cleanExistedCanvas(container, _assertThisInitialized(_this));
  14473. var canvasWidth = width;
  14474. var canvasHeight = height;
  14475. var dpr = devicePixelRatio;
  14476. // use user-defined <canvas> or OffscreenCanvas
  14477. if (canvas) {
  14478. // infer width & height with dpr
  14479. dpr = devicePixelRatio || isBrowser && window.devicePixelRatio || 1;
  14480. dpr = dpr >= 1 ? Math.ceil(dpr) : 1;
  14481. canvasWidth = width || getWidth(canvas) || canvas.width / dpr;
  14482. canvasHeight = height || getHeight(canvas) || canvas.height / dpr;
  14483. }
  14484. /**
  14485. * implements `Window` interface
  14486. */
  14487. _this.devicePixelRatio = dpr;
  14488. _this.requestAnimationFrame = requestAnimationFrame !== null && requestAnimationFrame !== void 0 ? requestAnimationFrame : raf.bind(runtime.globalThis);
  14489. _this.cancelAnimationFrame = cancelAnimationFrame !== null && cancelAnimationFrame !== void 0 ? cancelAnimationFrame : caf.bind(runtime.globalThis);
  14490. /**
  14491. * limits query
  14492. */
  14493. // the following feature-detect from hammer.js
  14494. // @see https://github.com/hammerjs/hammer.js/blob/master/src/inputjs/input-consts.js#L5
  14495. _this.supportsTouchEvents = supportsTouchEvents !== null && supportsTouchEvents !== void 0 ? supportsTouchEvents : 'ontouchstart' in runtime.globalThis;
  14496. _this.supportsPointerEvents = supportsPointerEvents !== null && supportsPointerEvents !== void 0 ? supportsPointerEvents : !!runtime.globalThis.PointerEvent;
  14497. _this.isTouchEvent = isTouchEvent !== null && isTouchEvent !== void 0 ? isTouchEvent : function (event) {
  14498. return _this.supportsTouchEvents && event instanceof runtime.globalThis.TouchEvent;
  14499. };
  14500. _this.isMouseEvent = isMouseEvent !== null && isMouseEvent !== void 0 ? isMouseEvent : function (event) {
  14501. return !runtime.globalThis.MouseEvent || event instanceof runtime.globalThis.MouseEvent && (!_this.supportsPointerEvents || !(event instanceof runtime.globalThis.PointerEvent));
  14502. };
  14503. _this.initRenderingContext({
  14504. container: container,
  14505. canvas: canvas,
  14506. width: canvasWidth,
  14507. height: canvasHeight,
  14508. renderer: renderer,
  14509. offscreenCanvas: offscreenCanvas,
  14510. devicePixelRatio: dpr,
  14511. cursor: cursor || 'default',
  14512. background: background || 'transparent',
  14513. createImage: createImage,
  14514. document: document,
  14515. supportsCSSTransform: supportsCSSTransform,
  14516. useNativeClickEvent: useNativeClickEvent,
  14517. alwaysTriggerPointerEventOnCanvas: alwaysTriggerPointerEventOnCanvas
  14518. });
  14519. _this.initDefaultCamera(canvasWidth, canvasHeight);
  14520. _this.initRenderer(renderer, true);
  14521. return _this;
  14522. }
  14523. var _proto = Canvas.prototype;
  14524. _proto.initRenderingContext = function initRenderingContext(mergedConfig) {
  14525. this.context.config = mergedConfig;
  14526. // bind rendering context, shared by all renderers
  14527. this.context.renderingContext = {
  14528. /**
  14529. * the root node in scene graph
  14530. */
  14531. root: this.document.documentElement,
  14532. renderListCurrentFrame: [],
  14533. unculledEntities: [],
  14534. renderReasons: new Set(),
  14535. force: false,
  14536. dirty: false
  14537. };
  14538. };
  14539. _proto.initDefaultCamera = function initDefaultCamera(width, height) {
  14540. var _this2 = this;
  14541. // set a default ortho camera
  14542. var camera = new runtime.CameraContribution();
  14543. camera.setType(exports.CameraType.EXPLORING, exports.CameraTrackingMode.DEFAULT).setPosition(width / 2, height / 2, DEFAULT_CAMERA_Z).setFocalPoint(width / 2, height / 2, 0).setOrthographic(width / -2, width / 2, height / 2, height / -2, DEFAULT_CAMERA_NEAR, DEFAULT_CAMERA_FAR);
  14544. // keep ref since it will use raf in camera animation
  14545. camera.canvas = this;
  14546. // redraw when camera changed
  14547. camera.eventEmitter.on(CameraEvent.UPDATED, function () {
  14548. _this2.context.renderingContext.renderReasons.add(exports.RenderReason.CAMERA_CHANGED);
  14549. });
  14550. // bind camera
  14551. this.context.camera = camera;
  14552. };
  14553. _proto.getConfig = function getConfig() {
  14554. return this.context.config;
  14555. }
  14556. /**
  14557. * get the root displayObject in scenegraph
  14558. * @alias this.document.documentElement
  14559. */;
  14560. _proto.getRoot = function getRoot() {
  14561. return this.document.documentElement;
  14562. }
  14563. /**
  14564. * get the camera of canvas
  14565. */;
  14566. _proto.getCamera = function getCamera() {
  14567. return this.context.camera;
  14568. };
  14569. _proto.getContextService = function getContextService() {
  14570. return this.context.contextService;
  14571. };
  14572. _proto.getEventService = function getEventService() {
  14573. return this.context.eventService;
  14574. };
  14575. _proto.getRenderingService = function getRenderingService() {
  14576. return this.context.renderingService;
  14577. };
  14578. _proto.getRenderingContext = function getRenderingContext() {
  14579. return this.context.renderingContext;
  14580. };
  14581. _proto.getStats = function getStats() {
  14582. return this.getRenderingService().getStats();
  14583. }
  14584. // /**
  14585. // * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
  14586. // */
  14587. // getComputedStyle(node: DisplayObject) {
  14588. // return node.computedStyle;
  14589. // }
  14590. ;
  14591. /**
  14592. * `cleanUp` means clean all the internal services of Canvas which happens when calling `canvas.destroy()`.
  14593. */
  14594. _proto.destroy = function destroy(cleanUp, skipTriggerEvent) {
  14595. if (cleanUp === void 0) {
  14596. cleanUp = true;
  14597. }
  14598. if (skipTriggerEvent === void 0) {
  14599. skipTriggerEvent = false;
  14600. }
  14601. if (!skipTriggerEvent) {
  14602. this.dispatchEvent(new CustomEvent(exports.CanvasEvent.BEFORE_DESTROY));
  14603. }
  14604. if (this.frameId) {
  14605. var cancelRAF = this.getConfig().cancelAnimationFrame || cancelAnimationFrame;
  14606. cancelRAF(this.frameId);
  14607. }
  14608. // unmount all children
  14609. var root = this.getRoot();
  14610. this.unmountChildren(root);
  14611. if (cleanUp) {
  14612. // destroy Document
  14613. this.document.destroy();
  14614. this.getEventService().destroy();
  14615. }
  14616. // destroy services
  14617. this.getRenderingService().destroy();
  14618. this.getContextService().destroy();
  14619. // clear root after renderservice destroyed
  14620. if (cleanUp && this.context.rBushRoot) {
  14621. // clear rbush
  14622. this.context.rBushRoot.clear();
  14623. this.context.rBushRoot = null;
  14624. this.context.renderingContext.root = null;
  14625. }
  14626. if (!skipTriggerEvent) {
  14627. this.dispatchEvent(new CustomEvent(exports.CanvasEvent.AFTER_DESTROY));
  14628. }
  14629. }
  14630. /**
  14631. * compatible with G 3.0
  14632. * @deprecated
  14633. * @alias resize
  14634. */;
  14635. _proto.changeSize = function changeSize(width, height) {
  14636. this.resize(width, height);
  14637. };
  14638. _proto.resize = function resize(width, height) {
  14639. // update canvas' config
  14640. var canvasConfig = this.context.config;
  14641. canvasConfig.width = width;
  14642. canvasConfig.height = height;
  14643. // resize context
  14644. this.getContextService().resize(width, height);
  14645. // resize camera
  14646. var camera = this.context.camera;
  14647. var projectionMode = camera.getProjectionMode();
  14648. camera.setPosition(width / 2, height / 2, DEFAULT_CAMERA_Z).setFocalPoint(width / 2, height / 2, 0);
  14649. if (projectionMode === exports.CameraProjectionMode.ORTHOGRAPHIC) {
  14650. camera.setOrthographic(width / -2, width / 2, height / 2, height / -2, camera.getNear(), camera.getFar());
  14651. } else {
  14652. camera.setAspect(width / height);
  14653. }
  14654. this.dispatchEvent(new CustomEvent(exports.CanvasEvent.RESIZE, {
  14655. width: width,
  14656. height: height
  14657. }));
  14658. }
  14659. // proxy to document.documentElement
  14660. ;
  14661. _proto.appendChild = function appendChild(child, index) {
  14662. return this.document.documentElement.appendChild(child, index);
  14663. };
  14664. _proto.insertBefore = function insertBefore(newChild, refChild) {
  14665. return this.document.documentElement.insertBefore(newChild, refChild);
  14666. };
  14667. _proto.removeChild = function removeChild(child) {
  14668. return this.document.documentElement.removeChild(child);
  14669. }
  14670. /**
  14671. * Remove all children which can be appended to its original parent later again.
  14672. */;
  14673. _proto.removeChildren = function removeChildren() {
  14674. this.document.documentElement.removeChildren();
  14675. }
  14676. /**
  14677. * Recursively destroy all children which can not be appended to its original parent later again.
  14678. * But the canvas remains running which means display objects can be appended later.
  14679. */;
  14680. _proto.destroyChildren = function destroyChildren() {
  14681. this.document.documentElement.destroyChildren();
  14682. };
  14683. _proto.render = function render() {
  14684. var _this3 = this;
  14685. this.dispatchEvent(beforeRenderEvent);
  14686. var renderingService = this.getRenderingService();
  14687. renderingService.render(this.getConfig(), function () {
  14688. // trigger actual rerender event
  14689. // @see https://github.com/antvis/G/issues/1268
  14690. _this3.dispatchEvent(rerenderEvent);
  14691. });
  14692. this.dispatchEvent(afterRenderEvent);
  14693. };
  14694. _proto.run = function run() {
  14695. var _this4 = this;
  14696. var tick = function tick() {
  14697. _this4.render();
  14698. _this4.frameId = _this4.requestAnimationFrame(tick);
  14699. };
  14700. tick();
  14701. };
  14702. _proto.initRenderer = function initRenderer(renderer, firstContentfullPaint) {
  14703. var _this5 = this;
  14704. if (firstContentfullPaint === void 0) {
  14705. firstContentfullPaint = false;
  14706. }
  14707. if (!renderer) {
  14708. throw new Error('Renderer is required.');
  14709. }
  14710. // reset
  14711. this.inited = false;
  14712. this.readyPromise = undefined;
  14713. // FIXME: should re-create here?
  14714. this.context.rBushRoot = new RBush__default['default']();
  14715. // reset rendering plugins
  14716. this.context.renderingPlugins = [];
  14717. this.context.renderingPlugins.push(new EventPlugin(), new PrepareRendererPlugin(), new DirtyCheckPlugin(), new CullingPlugin([new FrustumCullingStrategy()]));
  14718. //
  14719. this.loadRendererContainerModule(renderer);
  14720. // init context service
  14721. this.context.contextService = new this.context.ContextService(_extends({}, runtime, this.context));
  14722. // init rendering service
  14723. this.context.renderingService = new RenderingService(runtime, this.context);
  14724. // init event service
  14725. this.context.eventService = new EventService(runtime, this.context);
  14726. this.context.eventService.init();
  14727. if (this.context.contextService.init) {
  14728. this.context.contextService.init();
  14729. this.initRenderingService(renderer, firstContentfullPaint, true);
  14730. } else {
  14731. this.context.contextService.initAsync().then(function () {
  14732. _this5.initRenderingService(renderer, firstContentfullPaint);
  14733. });
  14734. }
  14735. };
  14736. _proto.initRenderingService = function initRenderingService(renderer, firstContentfullPaint, async) {
  14737. var _this6 = this;
  14738. if (firstContentfullPaint === void 0) {
  14739. firstContentfullPaint = false;
  14740. }
  14741. if (async === void 0) {
  14742. async = false;
  14743. }
  14744. this.context.renderingService.init(function () {
  14745. _this6.inited = true;
  14746. if (firstContentfullPaint) {
  14747. if (async) {
  14748. _this6.requestAnimationFrame(function () {
  14749. _this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.READY));
  14750. });
  14751. } else {
  14752. _this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.READY));
  14753. }
  14754. if (_this6.readyPromise) {
  14755. _this6.resolveReadyPromise();
  14756. }
  14757. } else {
  14758. _this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.RENDERER_CHANGED));
  14759. }
  14760. if (!firstContentfullPaint) {
  14761. _this6.getRoot().forEach(function (node) {
  14762. var renderable = node.renderable;
  14763. if (renderable) {
  14764. renderable.renderBoundsDirty = true;
  14765. renderable.boundsDirty = true;
  14766. renderable.dirty = true;
  14767. }
  14768. });
  14769. }
  14770. // keep current scenegraph unchanged, just trigger mounted event
  14771. _this6.mountChildren(_this6.getRoot());
  14772. if (renderer.getConfig().enableAutoRendering) {
  14773. _this6.run();
  14774. }
  14775. });
  14776. };
  14777. _proto.loadRendererContainerModule = function loadRendererContainerModule(renderer) {
  14778. var _this7 = this;
  14779. // load other container modules provided by g-canvas/g-svg/g-webgl
  14780. var plugins = renderer.getPlugins();
  14781. plugins.forEach(function (plugin) {
  14782. plugin.context = _this7.context;
  14783. plugin.init(runtime);
  14784. });
  14785. };
  14786. _proto.setRenderer = function setRenderer(renderer) {
  14787. // update canvas' config
  14788. var canvasConfig = this.getConfig();
  14789. if (canvasConfig.renderer === renderer) {
  14790. return;
  14791. }
  14792. var oldRenderer = canvasConfig.renderer;
  14793. canvasConfig.renderer = renderer;
  14794. // keep all children undestroyed
  14795. this.destroy(false, true);
  14796. // destroy all plugins, reverse will mutate origin array
  14797. [].concat(oldRenderer === null || oldRenderer === void 0 ? void 0 : oldRenderer.getPlugins()).reverse().forEach(function (plugin) {
  14798. plugin.destroy(runtime);
  14799. });
  14800. this.initRenderer(renderer);
  14801. };
  14802. _proto.setCursor = function setCursor(cursor) {
  14803. var canvasConfig = this.getConfig();
  14804. canvasConfig.cursor = cursor;
  14805. this.getContextService().applyCursorStyle(cursor);
  14806. };
  14807. _proto.unmountChildren = function unmountChildren(parent) {
  14808. var _this8 = this;
  14809. // unmountChildren recursively
  14810. parent.childNodes.forEach(function (child) {
  14811. _this8.unmountChildren(child);
  14812. });
  14813. if (this.inited) {
  14814. if (parent.isMutationObserved) {
  14815. parent.dispatchEvent(unmountedEvent);
  14816. } else {
  14817. unmountedEvent.target = parent;
  14818. this.dispatchEvent(unmountedEvent, true);
  14819. }
  14820. // skip document.documentElement
  14821. if (parent !== this.document.documentElement) {
  14822. parent.ownerDocument = null;
  14823. }
  14824. parent.isConnected = false;
  14825. }
  14826. // trigger after unmounted
  14827. if (parent.isCustomElement) {
  14828. if (parent.disconnectedCallback) {
  14829. parent.disconnectedCallback();
  14830. }
  14831. }
  14832. };
  14833. _proto.mountChildren = function mountChildren(parent) {
  14834. var _this9 = this;
  14835. if (this.inited) {
  14836. if (!parent.isConnected) {
  14837. parent.ownerDocument = this.document;
  14838. parent.isConnected = true;
  14839. if (parent.isMutationObserved) {
  14840. parent.dispatchEvent(mountedEvent);
  14841. } else {
  14842. mountedEvent.target = parent;
  14843. this.dispatchEvent(mountedEvent, true);
  14844. }
  14845. }
  14846. } else {
  14847. console.warn("[g]: You are trying to call `canvas.appendChild` before canvas' initialization finished. You can either await `canvas.ready` or listen to `CanvasEvent.READY` manually.", 'appended child: ', parent.nodeName);
  14848. }
  14849. // recursively mount children
  14850. parent.childNodes.forEach(function (child) {
  14851. _this9.mountChildren(child);
  14852. });
  14853. // trigger after mounted
  14854. if (parent.isCustomElement) {
  14855. if (parent.connectedCallback) {
  14856. parent.connectedCallback();
  14857. }
  14858. }
  14859. };
  14860. _proto.client2Viewport = function client2Viewport(client) {
  14861. return this.getEventService().client2Viewport(client);
  14862. };
  14863. _proto.viewport2Client = function viewport2Client(canvas) {
  14864. return this.getEventService().viewport2Client(canvas);
  14865. };
  14866. _proto.viewport2Canvas = function viewport2Canvas(viewport) {
  14867. return this.getEventService().viewport2Canvas(viewport);
  14868. };
  14869. _proto.canvas2Viewport = function canvas2Viewport(canvas) {
  14870. return this.getEventService().canvas2Viewport(canvas);
  14871. }
  14872. /**
  14873. * @deprecated
  14874. * @alias client2Viewport
  14875. */;
  14876. _proto.getPointByClient = function getPointByClient(clientX, clientY) {
  14877. return this.client2Viewport({
  14878. x: clientX,
  14879. y: clientY
  14880. });
  14881. }
  14882. /**
  14883. * @deprecated
  14884. * @alias viewport2Client
  14885. */;
  14886. _proto.getClientByPoint = function getClientByPoint(x, y) {
  14887. return this.viewport2Client({
  14888. x: x,
  14889. y: y
  14890. });
  14891. };
  14892. _createClass(Canvas, [{
  14893. key: "ready",
  14894. get: function get() {
  14895. var _this10 = this;
  14896. if (!this.readyPromise) {
  14897. this.readyPromise = new Promise(function (resolve) {
  14898. _this10.resolveReadyPromise = function () {
  14899. resolve(_this10);
  14900. };
  14901. });
  14902. if (this.inited) {
  14903. this.resolveReadyPromise();
  14904. }
  14905. }
  14906. return this.readyPromise;
  14907. }
  14908. }]);
  14909. return Canvas;
  14910. }(EventTarget);
  14911. Object.defineProperty(exports, 'RBush', {
  14912. enumerable: true,
  14913. get: function () {
  14914. return RBush__default['default'];
  14915. }
  14916. });
  14917. exports.AABB = AABB;
  14918. exports.AbstractRenderer = AbstractRenderer;
  14919. exports.AbstractRendererPlugin = AbstractRendererPlugin;
  14920. exports.BUILT_IN_PROPERTIES = BUILT_IN_PROPERTIES;
  14921. exports.CSS = CSS;
  14922. exports.CSSGradientValue = CSSGradientValue;
  14923. exports.CSSKeywordValue = CSSKeywordValue;
  14924. exports.CSSRGB = CSSRGB;
  14925. exports.CSSStyleValue = CSSStyleValue;
  14926. exports.CSSUnitValue = CSSUnitValue;
  14927. exports.Camera = Camera;
  14928. exports.CameraEvent = CameraEvent;
  14929. exports.Canvas = Canvas;
  14930. exports.Circle = Circle;
  14931. exports.CircleUpdater = CircleUpdater;
  14932. exports.CustomElement = CustomElement;
  14933. exports.CustomElementRegistry = CustomElementRegistry;
  14934. exports.CustomEvent = CustomEvent;
  14935. exports.DefaultSceneGraphSelector = DefaultSceneGraphSelector;
  14936. exports.DefaultSceneGraphService = DefaultSceneGraphService;
  14937. exports.DisplayObject = DisplayObject;
  14938. exports.Document = Document;
  14939. exports.EMPTY_PARSED_PATH = EMPTY_PARSED_PATH;
  14940. exports.ERROR_MSG_METHOD_NOT_IMPLEMENTED = ERROR_MSG_METHOD_NOT_IMPLEMENTED;
  14941. exports.Element = Element;
  14942. exports.Ellipse = Ellipse;
  14943. exports.EllipseUpdater = EllipseUpdater;
  14944. exports.EventService = EventService;
  14945. exports.EventTarget = EventTarget;
  14946. exports.FederatedEvent = FederatedEvent;
  14947. exports.FederatedMouseEvent = FederatedMouseEvent;
  14948. exports.FederatedPointerEvent = FederatedPointerEvent;
  14949. exports.FederatedWheelEvent = FederatedWheelEvent;
  14950. exports.Frustum = Frustum;
  14951. exports.Group = Group;
  14952. exports.HTML = HTML;
  14953. exports.Image = Image;
  14954. exports.Line = Line;
  14955. exports.LineUpdater = LineUpdater;
  14956. exports.MutationEvent = MutationEvent;
  14957. exports.Node = Node;
  14958. exports.OffscreenCanvasCreator = OffscreenCanvasCreator;
  14959. exports.Path = Path;
  14960. exports.PathUpdater = PathUpdater;
  14961. exports.Plane = Plane;
  14962. exports.Point = Point;
  14963. exports.Polygon = Polygon;
  14964. exports.Polyline = Polyline;
  14965. exports.PolylineUpdater = PolylineUpdater;
  14966. exports.Rect = Rect;
  14967. exports.RectUpdater = RectUpdater;
  14968. exports.Rectangle = Rectangle;
  14969. exports.RenderingService = RenderingService;
  14970. exports.Text = Text;
  14971. exports.TextService = TextService;
  14972. exports.TextUpdater = TextUpdater;
  14973. exports.computeLinearGradient = computeLinearGradient;
  14974. exports.computeRadialGradient = computeRadialGradient;
  14975. exports.convertToPath = convertToPath;
  14976. exports.createVec3 = createVec3;
  14977. exports.decompose = decompose;
  14978. exports.definedProps = definedProps;
  14979. exports.deg2rad = deg2rad;
  14980. exports.deg2turn = deg2turn;
  14981. exports.findClosestClipPathTarget = findClosestClipPathTarget;
  14982. exports.fromRotationTranslationScale = fromRotationTranslationScale;
  14983. exports.getAngle = getAngle;
  14984. exports.getEuler = getEuler;
  14985. exports.getOrCalculatePathTotalLength = getOrCalculatePathTotalLength;
  14986. exports.grad2deg = grad2deg;
  14987. exports.isBrowser = isBrowser;
  14988. exports.isCSSGradientValue = isCSSGradientValue;
  14989. exports.isCSSRGB = isCSSRGB;
  14990. exports.isCanvas = isCanvas;
  14991. exports.isDisplayObject = isDisplayObject;
  14992. exports.isFederatedEvent = isFederatedEvent;
  14993. exports.isFillOrStrokeAffected = isFillOrStrokeAffected;
  14994. exports.isPattern = isPattern;
  14995. exports.mergeColors = mergeColors;
  14996. exports.parseColor = parseColor;
  14997. exports.parseLength = parseLength;
  14998. exports.parsePath = parsePath;
  14999. exports.parseTransform = parseTransform;
  15000. exports.parsedTransformToMat4 = parsedTransformToMat4;
  15001. exports.propertyMetadataCache = propertyMetadataCache;
  15002. exports.rad2deg = rad2deg;
  15003. exports.resetEntityCounter = resetEntityCounter;
  15004. exports.runtime = runtime;
  15005. exports.setDOMSize = setDOMSize;
  15006. exports.translatePathToString = translatePathToString;
  15007. exports.turn2deg = turn2deg;