index.esm.js 503 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052
  1. import RBush from 'rbush/rbush.js';
  2. export { default as RBush } from 'rbush/rbush.js';
  3. import { isNumber, distanceSquareRoot, getTotalLength, clamp, min, max, isNumberEqual, mod, isString, isNil, normalizePath, path2Curve, equalizeSegments, getDrawDirection, reverseCurve, clonePath, getRotatedCurve, isBoolean, isObject, isUndefined, getPointAtLength } from '@antv/util';
  4. import { color } from 'd3-color';
  5. import { vec3, mat3, mat4, vec4, quat as quat$1, vec2 } from 'gl-matrix';
  6. import { Arc, Cubic, Quad, Polyline as Polyline$1, Line as Line$1 } from '@antv/g-math';
  7. import EventEmitter from 'eventemitter3';
  8. /**
  9. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type
  10. */
  11. var PropertySyntax;
  12. (function (PropertySyntax) {
  13. /**
  14. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#coordinate
  15. */
  16. PropertySyntax["COORDINATE"] = "<coordinate>";
  17. /**
  18. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#color
  19. */
  20. PropertySyntax["COLOR"] = "<color>";
  21. /**
  22. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#paint
  23. */
  24. PropertySyntax["PAINT"] = "<paint>";
  25. /**
  26. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number
  27. */
  28. PropertySyntax["NUMBER"] = "<number>";
  29. /**
  30. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/angle
  31. */
  32. PropertySyntax["ANGLE"] = "<angle>";
  33. /**
  34. * <number> with range 0..1
  35. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#opacity_value
  36. */
  37. PropertySyntax["OPACITY_VALUE"] = "<opacity-value>";
  38. /**
  39. * <number> with range 0..Infinity
  40. */
  41. PropertySyntax["SHADOW_BLUR"] = "<shadow-blur>";
  42. /**
  43. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#length
  44. */
  45. PropertySyntax["LENGTH"] = "<length>";
  46. /**
  47. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage
  48. */
  49. PropertySyntax["PERCENTAGE"] = "<percentage>";
  50. PropertySyntax["LENGTH_PERCENTAGE"] = "<length> | <percentage>";
  51. PropertySyntax["LENGTH_PERCENTAGE_12"] = "[<length> | <percentage>]{1,2}";
  52. /**
  53. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin#formal_syntax
  54. */
  55. PropertySyntax["LENGTH_PERCENTAGE_14"] = "[<length> | <percentage>]{1,4}";
  56. /**
  57. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts
  58. */
  59. PropertySyntax["LIST_OF_POINTS"] = "<list-of-points>";
  60. PropertySyntax["PATH"] = "<path>";
  61. /**
  62. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter#formal_syntax
  63. */
  64. PropertySyntax["FILTER"] = "<filter>";
  65. PropertySyntax["Z_INDEX"] = "<z-index>";
  66. PropertySyntax["OFFSET_DISTANCE"] = "<offset-distance>";
  67. PropertySyntax["DEFINED_PATH"] = "<defined-path>";
  68. PropertySyntax["MARKER"] = "<marker>";
  69. PropertySyntax["TRANSFORM"] = "<transform>";
  70. PropertySyntax["TRANSFORM_ORIGIN"] = "<transform-origin>";
  71. PropertySyntax["TEXT"] = "<text>";
  72. PropertySyntax["TEXT_TRANSFORM"] = "<text-transform>";
  73. })(PropertySyntax || (PropertySyntax = {}));
  74. function _regeneratorRuntime() {
  75. _regeneratorRuntime = function () {
  76. return exports;
  77. };
  78. var exports = {},
  79. Op = Object.prototype,
  80. hasOwn = Op.hasOwnProperty,
  81. defineProperty = Object.defineProperty || function (obj, key, desc) {
  82. obj[key] = desc.value;
  83. },
  84. $Symbol = "function" == typeof Symbol ? Symbol : {},
  85. iteratorSymbol = $Symbol.iterator || "@@iterator",
  86. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  87. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  88. function define(obj, key, value) {
  89. return Object.defineProperty(obj, key, {
  90. value: value,
  91. enumerable: !0,
  92. configurable: !0,
  93. writable: !0
  94. }), obj[key];
  95. }
  96. try {
  97. define({}, "");
  98. } catch (err) {
  99. define = function (obj, key, value) {
  100. return obj[key] = value;
  101. };
  102. }
  103. function wrap(innerFn, outerFn, self, tryLocsList) {
  104. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  105. generator = Object.create(protoGenerator.prototype),
  106. context = new Context(tryLocsList || []);
  107. return defineProperty(generator, "_invoke", {
  108. value: makeInvokeMethod(innerFn, self, context)
  109. }), generator;
  110. }
  111. function tryCatch(fn, obj, arg) {
  112. try {
  113. return {
  114. type: "normal",
  115. arg: fn.call(obj, arg)
  116. };
  117. } catch (err) {
  118. return {
  119. type: "throw",
  120. arg: err
  121. };
  122. }
  123. }
  124. exports.wrap = wrap;
  125. var ContinueSentinel = {};
  126. function Generator() {}
  127. function GeneratorFunction() {}
  128. function GeneratorFunctionPrototype() {}
  129. var IteratorPrototype = {};
  130. define(IteratorPrototype, iteratorSymbol, function () {
  131. return this;
  132. });
  133. var getProto = Object.getPrototypeOf,
  134. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  135. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  136. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  137. function defineIteratorMethods(prototype) {
  138. ["next", "throw", "return"].forEach(function (method) {
  139. define(prototype, method, function (arg) {
  140. return this._invoke(method, arg);
  141. });
  142. });
  143. }
  144. function AsyncIterator(generator, PromiseImpl) {
  145. function invoke(method, arg, resolve, reject) {
  146. var record = tryCatch(generator[method], generator, arg);
  147. if ("throw" !== record.type) {
  148. var result = record.arg,
  149. value = result.value;
  150. return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  151. invoke("next", value, resolve, reject);
  152. }, function (err) {
  153. invoke("throw", err, resolve, reject);
  154. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  155. result.value = unwrapped, resolve(result);
  156. }, function (error) {
  157. return invoke("throw", error, resolve, reject);
  158. });
  159. }
  160. reject(record.arg);
  161. }
  162. var previousPromise;
  163. defineProperty(this, "_invoke", {
  164. value: function (method, arg) {
  165. function callInvokeWithMethodAndArg() {
  166. return new PromiseImpl(function (resolve, reject) {
  167. invoke(method, arg, resolve, reject);
  168. });
  169. }
  170. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  171. }
  172. });
  173. }
  174. function makeInvokeMethod(innerFn, self, context) {
  175. var state = "suspendedStart";
  176. return function (method, arg) {
  177. if ("executing" === state) throw new Error("Generator is already running");
  178. if ("completed" === state) {
  179. if ("throw" === method) throw arg;
  180. return doneResult();
  181. }
  182. for (context.method = method, context.arg = arg;;) {
  183. var delegate = context.delegate;
  184. if (delegate) {
  185. var delegateResult = maybeInvokeDelegate(delegate, context);
  186. if (delegateResult) {
  187. if (delegateResult === ContinueSentinel) continue;
  188. return delegateResult;
  189. }
  190. }
  191. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  192. if ("suspendedStart" === state) throw state = "completed", context.arg;
  193. context.dispatchException(context.arg);
  194. } else "return" === context.method && context.abrupt("return", context.arg);
  195. state = "executing";
  196. var record = tryCatch(innerFn, self, context);
  197. if ("normal" === record.type) {
  198. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  199. return {
  200. value: record.arg,
  201. done: context.done
  202. };
  203. }
  204. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  205. }
  206. };
  207. }
  208. function maybeInvokeDelegate(delegate, context) {
  209. var methodName = context.method,
  210. method = delegate.iterator[methodName];
  211. 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;
  212. var record = tryCatch(method, delegate.iterator, context.arg);
  213. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  214. var info = record.arg;
  215. 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);
  216. }
  217. function pushTryEntry(locs) {
  218. var entry = {
  219. tryLoc: locs[0]
  220. };
  221. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  222. }
  223. function resetTryEntry(entry) {
  224. var record = entry.completion || {};
  225. record.type = "normal", delete record.arg, entry.completion = record;
  226. }
  227. function Context(tryLocsList) {
  228. this.tryEntries = [{
  229. tryLoc: "root"
  230. }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
  231. }
  232. function values(iterable) {
  233. if (iterable) {
  234. var iteratorMethod = iterable[iteratorSymbol];
  235. if (iteratorMethod) return iteratorMethod.call(iterable);
  236. if ("function" == typeof iterable.next) return iterable;
  237. if (!isNaN(iterable.length)) {
  238. var i = -1,
  239. next = function next() {
  240. for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  241. return next.value = undefined, next.done = !0, next;
  242. };
  243. return next.next = next;
  244. }
  245. }
  246. return {
  247. next: doneResult
  248. };
  249. }
  250. function doneResult() {
  251. return {
  252. value: undefined,
  253. done: !0
  254. };
  255. }
  256. return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
  257. value: GeneratorFunctionPrototype,
  258. configurable: !0
  259. }), defineProperty(GeneratorFunctionPrototype, "constructor", {
  260. value: GeneratorFunction,
  261. configurable: !0
  262. }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  263. var ctor = "function" == typeof genFun && genFun.constructor;
  264. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  265. }, exports.mark = function (genFun) {
  266. return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
  267. }, exports.awrap = function (arg) {
  268. return {
  269. __await: arg
  270. };
  271. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  272. return this;
  273. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  274. void 0 === PromiseImpl && (PromiseImpl = Promise);
  275. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  276. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  277. return result.done ? result.value : iter.next();
  278. });
  279. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  280. return this;
  281. }), define(Gp, "toString", function () {
  282. return "[object Generator]";
  283. }), exports.keys = function (val) {
  284. var object = Object(val),
  285. keys = [];
  286. for (var key in object) keys.push(key);
  287. return keys.reverse(), function next() {
  288. for (; keys.length;) {
  289. var key = keys.pop();
  290. if (key in object) return next.value = key, next.done = !1, next;
  291. }
  292. return next.done = !0, next;
  293. };
  294. }, exports.values = values, Context.prototype = {
  295. constructor: Context,
  296. reset: function (skipTempReset) {
  297. 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);
  298. },
  299. stop: function () {
  300. this.done = !0;
  301. var rootRecord = this.tryEntries[0].completion;
  302. if ("throw" === rootRecord.type) throw rootRecord.arg;
  303. return this.rval;
  304. },
  305. dispatchException: function (exception) {
  306. if (this.done) throw exception;
  307. var context = this;
  308. function handle(loc, caught) {
  309. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  310. }
  311. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  312. var entry = this.tryEntries[i],
  313. record = entry.completion;
  314. if ("root" === entry.tryLoc) return handle("end");
  315. if (entry.tryLoc <= this.prev) {
  316. var hasCatch = hasOwn.call(entry, "catchLoc"),
  317. hasFinally = hasOwn.call(entry, "finallyLoc");
  318. if (hasCatch && hasFinally) {
  319. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  320. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  321. } else if (hasCatch) {
  322. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  323. } else {
  324. if (!hasFinally) throw new Error("try statement without catch or finally");
  325. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  326. }
  327. }
  328. }
  329. },
  330. abrupt: function (type, arg) {
  331. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  332. var entry = this.tryEntries[i];
  333. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  334. var finallyEntry = entry;
  335. break;
  336. }
  337. }
  338. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  339. var record = finallyEntry ? finallyEntry.completion : {};
  340. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  341. },
  342. complete: function (record, afterLoc) {
  343. if ("throw" === record.type) throw record.arg;
  344. 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;
  345. },
  346. finish: function (finallyLoc) {
  347. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  348. var entry = this.tryEntries[i];
  349. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  350. }
  351. },
  352. catch: function (tryLoc) {
  353. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  354. var entry = this.tryEntries[i];
  355. if (entry.tryLoc === tryLoc) {
  356. var record = entry.completion;
  357. if ("throw" === record.type) {
  358. var thrown = record.arg;
  359. resetTryEntry(entry);
  360. }
  361. return thrown;
  362. }
  363. }
  364. throw new Error("illegal catch attempt");
  365. },
  366. delegateYield: function (iterable, resultName, nextLoc) {
  367. return this.delegate = {
  368. iterator: values(iterable),
  369. resultName: resultName,
  370. nextLoc: nextLoc
  371. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  372. }
  373. }, exports;
  374. }
  375. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  376. try {
  377. var info = gen[key](arg);
  378. var value = info.value;
  379. } catch (error) {
  380. reject(error);
  381. return;
  382. }
  383. if (info.done) {
  384. resolve(value);
  385. } else {
  386. Promise.resolve(value).then(_next, _throw);
  387. }
  388. }
  389. function _asyncToGenerator(fn) {
  390. return function () {
  391. var self = this,
  392. args = arguments;
  393. return new Promise(function (resolve, reject) {
  394. var gen = fn.apply(self, args);
  395. function _next(value) {
  396. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  397. }
  398. function _throw(err) {
  399. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  400. }
  401. _next(undefined);
  402. });
  403. };
  404. }
  405. function _defineProperties(target, props) {
  406. for (var i = 0; i < props.length; i++) {
  407. var descriptor = props[i];
  408. descriptor.enumerable = descriptor.enumerable || false;
  409. descriptor.configurable = true;
  410. if ("value" in descriptor) descriptor.writable = true;
  411. Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  412. }
  413. }
  414. function _createClass(Constructor, protoProps, staticProps) {
  415. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  416. if (staticProps) _defineProperties(Constructor, staticProps);
  417. Object.defineProperty(Constructor, "prototype", {
  418. writable: false
  419. });
  420. return Constructor;
  421. }
  422. function _extends() {
  423. _extends = Object.assign ? Object.assign.bind() : function (target) {
  424. for (var i = 1; i < arguments.length; i++) {
  425. var source = arguments[i];
  426. for (var key in source) {
  427. if (Object.prototype.hasOwnProperty.call(source, key)) {
  428. target[key] = source[key];
  429. }
  430. }
  431. }
  432. return target;
  433. };
  434. return _extends.apply(this, arguments);
  435. }
  436. function _inheritsLoose(subClass, superClass) {
  437. subClass.prototype = Object.create(superClass.prototype);
  438. subClass.prototype.constructor = subClass;
  439. _setPrototypeOf(subClass, superClass);
  440. }
  441. function _setPrototypeOf(o, p) {
  442. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  443. o.__proto__ = p;
  444. return o;
  445. };
  446. return _setPrototypeOf(o, p);
  447. }
  448. function _objectWithoutPropertiesLoose(source, excluded) {
  449. if (source == null) return {};
  450. var target = {};
  451. var sourceKeys = Object.keys(source);
  452. var key, i;
  453. for (i = 0; i < sourceKeys.length; i++) {
  454. key = sourceKeys[i];
  455. if (excluded.indexOf(key) >= 0) continue;
  456. target[key] = source[key];
  457. }
  458. return target;
  459. }
  460. function _assertThisInitialized(self) {
  461. if (self === void 0) {
  462. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  463. }
  464. return self;
  465. }
  466. function _unsupportedIterableToArray(o, minLen) {
  467. if (!o) return;
  468. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  469. var n = Object.prototype.toString.call(o).slice(8, -1);
  470. if (n === "Object" && o.constructor) n = o.constructor.name;
  471. if (n === "Map" || n === "Set") return Array.from(o);
  472. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  473. }
  474. function _arrayLikeToArray(arr, len) {
  475. if (len == null || len > arr.length) len = arr.length;
  476. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  477. return arr2;
  478. }
  479. function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  480. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  481. if (it) return (it = it.call(o)).next.bind(it);
  482. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  483. if (it) o = it;
  484. var i = 0;
  485. return function () {
  486. if (i >= o.length) return {
  487. done: true
  488. };
  489. return {
  490. done: false,
  491. value: o[i++]
  492. };
  493. };
  494. }
  495. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  496. }
  497. function _toPrimitive(input, hint) {
  498. if (typeof input !== "object" || input === null) return input;
  499. var prim = input[Symbol.toPrimitive];
  500. if (prim !== undefined) {
  501. var res = prim.call(input, hint || "default");
  502. if (typeof res !== "object") return res;
  503. throw new TypeError("@@toPrimitive must return a primitive value.");
  504. }
  505. return (hint === "string" ? String : Number)(input);
  506. }
  507. function _toPropertyKey(arg) {
  508. var key = _toPrimitive(arg, "string");
  509. return typeof key === "symbol" ? key : String(key);
  510. }
  511. // These units are iterated through, so be careful when adding or changing the
  512. // order.
  513. var UnitType;
  514. (function (UnitType) {
  515. UnitType[UnitType["kUnknown"] = 0] = "kUnknown";
  516. UnitType[UnitType["kNumber"] = 1] = "kNumber";
  517. UnitType[UnitType["kPercentage"] = 2] = "kPercentage";
  518. // Length units
  519. UnitType[UnitType["kEms"] = 3] = "kEms";
  520. // kExs,
  521. UnitType[UnitType["kPixels"] = 4] = "kPixels";
  522. // kCentimeters,
  523. // kMillimeters,
  524. // kInches,
  525. // kPoints,
  526. // kPicas,
  527. // kQuarterMillimeters,
  528. // https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
  529. //
  530. // See also IsViewportPercentageLength.
  531. // kViewportWidth,
  532. // kViewportHeight,
  533. // kViewportInlineSize,
  534. // kViewportBlockSize,
  535. // kViewportMin,
  536. // kViewportMax,
  537. // kSmallViewportWidth,
  538. // kSmallViewportHeight,
  539. // kSmallViewportInlineSize,
  540. // kSmallViewportBlockSize,
  541. // kSmallViewportMin,
  542. // kSmallViewportMax,
  543. // kLargeViewportWidth,
  544. // kLargeViewportHeight,
  545. // kLargeViewportInlineSize,
  546. // kLargeViewportBlockSize,
  547. // kLargeViewportMin,
  548. // kLargeViewportMax,
  549. // kDynamicViewportWidth,
  550. // kDynamicViewportHeight,
  551. // kDynamicViewportInlineSize,
  552. // kDynamicViewportBlockSize,
  553. // kDynamicViewportMin,
  554. // kDynamicViewportMax,
  555. // https://drafts.csswg.org/css-contain-3/#container-lengths
  556. //
  557. // See also IsContainerPercentageLength.
  558. // kContainerWidth,
  559. // kContainerHeight,
  560. // kContainerInlineSize,
  561. // kContainerBlockSize,
  562. // kContainerMin,
  563. // kContainerMax,
  564. UnitType[UnitType["kRems"] = 5] = "kRems";
  565. // kChs,
  566. // kUserUnits, // The SVG term for unitless lengths
  567. // Angle units
  568. UnitType[UnitType["kDegrees"] = 6] = "kDegrees";
  569. UnitType[UnitType["kRadians"] = 7] = "kRadians";
  570. UnitType[UnitType["kGradians"] = 8] = "kGradians";
  571. UnitType[UnitType["kTurns"] = 9] = "kTurns";
  572. // Time units
  573. UnitType[UnitType["kMilliseconds"] = 10] = "kMilliseconds";
  574. UnitType[UnitType["kSeconds"] = 11] = "kSeconds";
  575. // kHertz,
  576. // kKilohertz,
  577. // Resolution
  578. // kDotsPerPixel,
  579. // kDotsPerInch,
  580. // kDotsPerCentimeter,
  581. // Other units
  582. // kFraction,
  583. UnitType[UnitType["kInteger"] = 12] = "kInteger";
  584. // This value is used to handle quirky margins in reflow roots (body, td,
  585. // and th) like WinIE. The basic idea is that a stylesheet can use the value
  586. // __qem (for quirky em) instead of em. When the quirky value is used, if
  587. // you're in quirks mode, the margin will collapse away inside a table cell.
  588. // This quirk is specified in the HTML spec but our impl is different.
  589. // TODO: Remove this. crbug.com/443952
  590. // kQuirkyEms,
  591. })(UnitType || (UnitType = {}));
  592. var UnitCategory;
  593. (function (UnitCategory) {
  594. UnitCategory[UnitCategory["kUNumber"] = 0] = "kUNumber";
  595. UnitCategory[UnitCategory["kUPercent"] = 1] = "kUPercent";
  596. UnitCategory[UnitCategory["kULength"] = 2] = "kULength";
  597. UnitCategory[UnitCategory["kUAngle"] = 3] = "kUAngle";
  598. UnitCategory[UnitCategory["kUTime"] = 4] = "kUTime";
  599. // kUFrequency,
  600. // kUResolution,
  601. UnitCategory[UnitCategory["kUOther"] = 5] = "kUOther";
  602. })(UnitCategory || (UnitCategory = {}));
  603. var ValueRange;
  604. (function (ValueRange) {
  605. ValueRange[ValueRange["kAll"] = 0] = "kAll";
  606. ValueRange[ValueRange["kNonNegative"] = 1] = "kNonNegative";
  607. ValueRange[ValueRange["kInteger"] = 2] = "kInteger";
  608. ValueRange[ValueRange["kNonNegativeInteger"] = 3] = "kNonNegativeInteger";
  609. ValueRange[ValueRange["kPositiveInteger"] = 4] = "kPositiveInteger";
  610. })(ValueRange || (ValueRange = {}));
  611. var Nested;
  612. (function (Nested) {
  613. Nested[Nested["kYes"] = 0] = "kYes";
  614. Nested[Nested["kNo"] = 1] = "kNo";
  615. })(Nested || (Nested = {}));
  616. var ParenLess;
  617. (function (ParenLess) {
  618. ParenLess[ParenLess["kYes"] = 0] = "kYes";
  619. ParenLess[ParenLess["kNo"] = 1] = "kNo";
  620. })(ParenLess || (ParenLess = {}));
  621. // This file specifies the unit strings used in CSSPrimitiveValues.
  622. var data = [{
  623. name: 'em',
  624. unit_type: UnitType.kEms
  625. },
  626. // {
  627. // name: 'ex',
  628. // unit_type: UnitType.kExs,
  629. // },
  630. {
  631. name: 'px',
  632. unit_type: UnitType.kPixels
  633. },
  634. // {
  635. // name: "cm",
  636. // unit_type: UnitType.kCentimeters,
  637. // },
  638. // {
  639. // name: "mm",
  640. // unit_type: UnitType.kMillimeters,
  641. // },
  642. // {
  643. // name: "q",
  644. // unit_type: UnitType.kQuarterMillimeters,
  645. // },
  646. // {
  647. // name: "in",
  648. // unit_type: UnitType.kInches,
  649. // },
  650. // {
  651. // name: "pt",
  652. // unit_type: UnitType.kPoints,
  653. // },
  654. // {
  655. // name: "pc",
  656. // unit_type: UnitType.kPicas,
  657. // },
  658. {
  659. name: 'deg',
  660. unit_type: UnitType.kDegrees
  661. }, {
  662. name: 'rad',
  663. unit_type: UnitType.kRadians
  664. }, {
  665. name: 'grad',
  666. unit_type: UnitType.kGradians
  667. }, {
  668. name: 'ms',
  669. unit_type: UnitType.kMilliseconds
  670. }, {
  671. name: 's',
  672. unit_type: UnitType.kSeconds
  673. },
  674. // {
  675. // name: "hz",
  676. // unit_type: UnitType.kHertz,
  677. // },
  678. // {
  679. // name: "khz",
  680. // unit_type: UnitType.kKilohertz,
  681. // },
  682. // {
  683. // name: "dpi",
  684. // unit_type: "kDotsPerInch",
  685. // },
  686. // {
  687. // name: "dpcm",
  688. // unit_type: "kDotsPerCentimeter",
  689. // },
  690. // {
  691. // name: "dppx",
  692. // unit_type: "kDotsPerPixel",
  693. // },
  694. // {
  695. // name: "x",
  696. // unit_type: "kDotsPerPixel",
  697. // },
  698. // {
  699. // name: "vw",
  700. // unit_type: "kViewportWidth",
  701. // },
  702. // {
  703. // name: "vh",
  704. // unit_type: "kViewportHeight",
  705. // },
  706. // {
  707. // name: "vi",
  708. // unit_type: "kViewportInlineSize",
  709. // },
  710. // {
  711. // name: "vb",
  712. // unit_type: "kViewportBlockSize",
  713. // },
  714. // {
  715. // name: "vmin",
  716. // unit_type: UnitType.kViewportMin,
  717. // },
  718. // {
  719. // name: "vmax",
  720. // unit_type: UnitType.kViewportMax,
  721. // },
  722. // {
  723. // name: "svw",
  724. // unit_type: "kSmallViewportWidth",
  725. // },
  726. // {
  727. // name: "svh",
  728. // unit_type: "kSmallViewportHeight",
  729. // },
  730. // {
  731. // name: "svi",
  732. // unit_type: "kSmallViewportInlineSize",
  733. // },
  734. // {
  735. // name: "svb",
  736. // unit_type: "kSmallViewportBlockSize",
  737. // },
  738. // {
  739. // name: "svmin",
  740. // unit_type: "kSmallViewportMin",
  741. // },
  742. // {
  743. // name: "svmax",
  744. // unit_type: "kSmallViewportMax",
  745. // },
  746. // {
  747. // name: "lvw",
  748. // unit_type: "kLargeViewportWidth",
  749. // },
  750. // {
  751. // name: "lvh",
  752. // unit_type: "kLargeViewportHeight",
  753. // },
  754. // {
  755. // name: "lvi",
  756. // unit_type: "kLargeViewportInlineSize",
  757. // },
  758. // {
  759. // name: "lvb",
  760. // unit_type: "kLargeViewportBlockSize",
  761. // },
  762. // {
  763. // name: "lvmin",
  764. // unit_type: UnitType.kLargeViewportMin,
  765. // },
  766. // {
  767. // name: "lvmax",
  768. // unit_type: UnitType.kLargeViewportMax,
  769. // },
  770. // {
  771. // name: "dvw",
  772. // unit_type: UnitType.kDynamicViewportWidth,
  773. // },
  774. // {
  775. // name: "dvh",
  776. // unit_type: UnitType.kDynamicViewportHeight,
  777. // },
  778. // {
  779. // name: "dvi",
  780. // unit_type: UnitType.kDynamicViewportInlineSize,
  781. // },
  782. // {
  783. // name: "dvb",
  784. // unit_type: UnitType.kDynamicViewportBlockSize,
  785. // },
  786. // {
  787. // name: "dvmin",
  788. // unit_type: UnitType.kDynamicViewportMin,
  789. // },
  790. // {
  791. // name: "dvmax",
  792. // unit_type: UnitType.kDynamicViewportMax,
  793. // },
  794. // {
  795. // name: "cqw",
  796. // unit_type: UnitType.kContainerWidth,
  797. // },
  798. // {
  799. // name: "cqh",
  800. // unit_type: UnitType.kContainerHeight,
  801. // },
  802. // {
  803. // name: "cqi",
  804. // unit_type: UnitType.kContainerInlineSize,
  805. // },
  806. // {
  807. // name: "cqb",
  808. // unit_type: UnitType.kContainerBlockSize,
  809. // },
  810. // {
  811. // name: "cqmin",
  812. // unit_type: UnitType.kContainerMin,
  813. // },
  814. // {
  815. // name: "cqmax",
  816. // unit_type: UnitType.kContainerMax,
  817. // },
  818. {
  819. name: 'rem',
  820. unit_type: UnitType.kRems
  821. },
  822. // {
  823. // name: 'fr',
  824. // unit_type: UnitType.kFraction,
  825. // },
  826. {
  827. name: 'turn',
  828. unit_type: UnitType.kTurns
  829. }
  830. // {
  831. // name: 'ch',
  832. // unit_type: UnitType.kChs,
  833. // },
  834. // {
  835. // name: '__qem',
  836. // unit_type: UnitType.kQuirkyEms,
  837. // },
  838. ];
  839. var CSSStyleValueType;
  840. (function (CSSStyleValueType) {
  841. CSSStyleValueType[CSSStyleValueType["kUnknownType"] = 0] = "kUnknownType";
  842. CSSStyleValueType[CSSStyleValueType["kUnparsedType"] = 1] = "kUnparsedType";
  843. CSSStyleValueType[CSSStyleValueType["kKeywordType"] = 2] = "kKeywordType";
  844. // Start of CSSNumericValue subclasses
  845. CSSStyleValueType[CSSStyleValueType["kUnitType"] = 3] = "kUnitType";
  846. CSSStyleValueType[CSSStyleValueType["kSumType"] = 4] = "kSumType";
  847. CSSStyleValueType[CSSStyleValueType["kProductType"] = 5] = "kProductType";
  848. CSSStyleValueType[CSSStyleValueType["kNegateType"] = 6] = "kNegateType";
  849. CSSStyleValueType[CSSStyleValueType["kInvertType"] = 7] = "kInvertType";
  850. CSSStyleValueType[CSSStyleValueType["kMinType"] = 8] = "kMinType";
  851. CSSStyleValueType[CSSStyleValueType["kMaxType"] = 9] = "kMaxType";
  852. CSSStyleValueType[CSSStyleValueType["kClampType"] = 10] = "kClampType";
  853. // End of CSSNumericValue subclasses
  854. CSSStyleValueType[CSSStyleValueType["kTransformType"] = 11] = "kTransformType";
  855. CSSStyleValueType[CSSStyleValueType["kPositionType"] = 12] = "kPositionType";
  856. CSSStyleValueType[CSSStyleValueType["kURLImageType"] = 13] = "kURLImageType";
  857. CSSStyleValueType[CSSStyleValueType["kColorType"] = 14] = "kColorType";
  858. CSSStyleValueType[CSSStyleValueType["kUnsupportedColorType"] = 15] = "kUnsupportedColorType";
  859. })(CSSStyleValueType || (CSSStyleValueType = {}));
  860. // function parseCSSStyleValue(propertyName: string, value: string): CSSStyleValue[] {
  861. // // const propertyId = cssPropertyID(propertyName);
  862. // // if (propertyId === CSSPropertyID.kInvalid) {
  863. // // return [];
  864. // // }
  865. // // const customPropertyName = propertyId === CSSPropertyID.kVariable ? propertyName : null;
  866. // // return fromString(propertyId, customPropertyName, value);
  867. // return [];
  868. // }
  869. var stringToUnitType = function stringToUnitType(name) {
  870. return data.find(function (item) {
  871. return item.name === name;
  872. }).unit_type;
  873. };
  874. var unitFromName = function unitFromName(name) {
  875. if (!name) {
  876. return UnitType.kUnknown;
  877. }
  878. if (name === 'number') {
  879. return UnitType.kNumber;
  880. }
  881. if (name === 'percent' || name === '%') {
  882. return UnitType.kPercentage;
  883. }
  884. return stringToUnitType(name);
  885. };
  886. var unitTypeToUnitCategory = function unitTypeToUnitCategory(type) {
  887. switch (type) {
  888. case UnitType.kNumber:
  889. case UnitType.kInteger:
  890. return UnitCategory.kUNumber;
  891. case UnitType.kPercentage:
  892. return UnitCategory.kUPercent;
  893. case UnitType.kPixels:
  894. // case UnitType.kCentimeters:
  895. // case UnitType.kMillimeters:
  896. // case UnitType.kQuarterMillimeters:
  897. // case UnitType.kInches:
  898. // case UnitType.kPoints:
  899. // case UnitType.kPicas:
  900. // case UnitType.kUserUnits:
  901. return UnitCategory.kULength;
  902. case UnitType.kMilliseconds:
  903. case UnitType.kSeconds:
  904. return UnitCategory.kUTime;
  905. case UnitType.kDegrees:
  906. case UnitType.kRadians:
  907. case UnitType.kGradians:
  908. case UnitType.kTurns:
  909. return UnitCategory.kUAngle;
  910. // case UnitType.kHertz:
  911. // case UnitType.kKilohertz:
  912. // return UnitCategory.kUFrequency;
  913. // case UnitType.kDotsPerPixel:
  914. // case UnitType.kDotsPerInch:
  915. // case UnitType.kDotsPerCentimeter:
  916. // return UnitCategory.kUResolution;
  917. default:
  918. return UnitCategory.kUOther;
  919. }
  920. };
  921. var canonicalUnitTypeForCategory = function canonicalUnitTypeForCategory(category) {
  922. // The canonical unit type is chosen according to the way
  923. // CSSPropertyParser.ValidUnit() chooses the default unit in each category
  924. // (based on unitflags).
  925. switch (category) {
  926. case UnitCategory.kUNumber:
  927. return UnitType.kNumber;
  928. case UnitCategory.kULength:
  929. return UnitType.kPixels;
  930. case UnitCategory.kUPercent:
  931. return UnitType.kPercentage;
  932. // return UnitType.kUnknown; // Cannot convert between numbers and percent.
  933. case UnitCategory.kUTime:
  934. return UnitType.kSeconds;
  935. case UnitCategory.kUAngle:
  936. return UnitType.kDegrees;
  937. // case UnitCategory.kUFrequency:
  938. // return UnitType.kHertz;
  939. // case UnitCategory.kUResolution:
  940. // return UnitType.kDotsPerPixel;
  941. default:
  942. return UnitType.kUnknown;
  943. }
  944. };
  945. /**
  946. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/css_primitive_value.cc#353
  947. */
  948. var conversionToCanonicalUnitsScaleFactor = function conversionToCanonicalUnitsScaleFactor(unit_type) {
  949. var factor = 1.0;
  950. // FIXME: the switch can be replaced by an array of scale factors.
  951. switch (unit_type) {
  952. // These are "canonical" units in their respective categories.
  953. case UnitType.kPixels:
  954. // case UnitType.kUserUnits:
  955. case UnitType.kDegrees:
  956. case UnitType.kSeconds:
  957. // case UnitType.kHertz:
  958. break;
  959. case UnitType.kMilliseconds:
  960. factor = 0.001;
  961. break;
  962. // case UnitType.kCentimeters:
  963. // // factor = kCssPixelsPerCentimeter;
  964. // break;
  965. // case UnitType.kDotsPerCentimeter:
  966. // // factor = 1 / kCssPixelsPerCentimeter;
  967. // break;
  968. // case UnitType.kMillimeters:
  969. // // factor = kCssPixelsPerMillimeter;
  970. // break;
  971. // case UnitType.kQuarterMillimeters:
  972. // // factor = kCssPixelsPerQuarterMillimeter;
  973. // break;
  974. // case UnitType.kInches:
  975. // // factor = kCssPixelsPerInch;
  976. // break;
  977. // case UnitType.kDotsPerInch:
  978. // // factor = 1 / kCssPixelsPerInch;
  979. // break;
  980. // case UnitType.kPoints:
  981. // // factor = kCssPixelsPerPoint;
  982. // break;
  983. // case UnitType.kPicas:
  984. // // factor = kCssPixelsPerPica;
  985. // break;
  986. case UnitType.kRadians:
  987. factor = 180 / Math.PI;
  988. break;
  989. case UnitType.kGradians:
  990. factor = 0.9;
  991. break;
  992. case UnitType.kTurns:
  993. factor = 360;
  994. break;
  995. }
  996. return factor;
  997. };
  998. var unitTypeToString = function unitTypeToString(type) {
  999. switch (type) {
  1000. case UnitType.kNumber:
  1001. case UnitType.kInteger:
  1002. // case UnitType.kUserUnits:
  1003. return '';
  1004. case UnitType.kPercentage:
  1005. return '%';
  1006. case UnitType.kEms:
  1007. // case UnitType.kQuirkyEms:
  1008. return 'em';
  1009. // case UnitType.kExs:
  1010. // return 'ex';
  1011. case UnitType.kRems:
  1012. return 'rem';
  1013. // case UnitType.kChs:
  1014. // return 'ch';
  1015. case UnitType.kPixels:
  1016. return 'px';
  1017. // case UnitType.kCentimeters:
  1018. // return 'cm';
  1019. // case UnitType.kDotsPerPixel:
  1020. // return 'dppx';
  1021. // case UnitType.kDotsPerInch:
  1022. // return 'dpi';
  1023. // case UnitType.kDotsPerCentimeter:
  1024. // return 'dpcm';
  1025. // case UnitType.kMillimeters:
  1026. // return 'mm';
  1027. // case UnitType.kQuarterMillimeters:
  1028. // return 'q';
  1029. // case UnitType.kInches:
  1030. // return 'in';
  1031. // case UnitType.kPoints:
  1032. // return 'pt';
  1033. // case UnitType.kPicas:
  1034. // return 'pc';
  1035. case UnitType.kDegrees:
  1036. return 'deg';
  1037. case UnitType.kRadians:
  1038. return 'rad';
  1039. case UnitType.kGradians:
  1040. return 'grad';
  1041. case UnitType.kMilliseconds:
  1042. return 'ms';
  1043. case UnitType.kSeconds:
  1044. return 's';
  1045. // case UnitType.kHertz:
  1046. // return 'hz';
  1047. // case UnitType.kKilohertz:
  1048. // return 'khz';
  1049. case UnitType.kTurns:
  1050. return 'turn';
  1051. }
  1052. return '';
  1053. };
  1054. /**
  1055. * CSSStyleValue is the base class for all CSS values accessible from Typed OM.
  1056. * Values that are not yet supported as specific types are also returned as base CSSStyleValues.
  1057. *
  1058. * Spec @see https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects
  1059. * Docs @see https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue
  1060. */
  1061. var CSSStyleValue = /*#__PURE__*/function () {
  1062. function CSSStyleValue() {}
  1063. // static parse(propertyName: string, value: string): CSSStyleValue {
  1064. // return parseCSSStyleValue(propertyName, value)[0];
  1065. // }
  1066. // static parseAll(propertyName: string, value: string): CSSStyleValue[] {
  1067. // return parseCSSStyleValue(propertyName, value);
  1068. // }
  1069. CSSStyleValue.isAngle = function isAngle(unit) {
  1070. return unit === UnitType.kDegrees || unit === UnitType.kRadians || unit === UnitType.kGradians || unit === UnitType.kTurns;
  1071. }
  1072. // static isViewportPercentageLength(type: UnitType) {
  1073. // return type >= UnitType.kViewportWidth && type <= UnitType.kDynamicViewportMax;
  1074. // }
  1075. // static isContainerPercentageLength(type: UnitType) {
  1076. // return type >= UnitType.kContainerWidth && type <= UnitType.kContainerMax;
  1077. // }
  1078. ;
  1079. CSSStyleValue.isLength = function isLength(type) {
  1080. // return (type >= UnitType.kEms && type <= UnitType.kUserUnits) || type == UnitType.kQuirkyEms;
  1081. return type >= UnitType.kEms && type < UnitType.kDegrees;
  1082. };
  1083. CSSStyleValue.isRelativeUnit = function isRelativeUnit(type) {
  1084. return type === UnitType.kPercentage || type === UnitType.kEms ||
  1085. // type === UnitType.kExs ||
  1086. type === UnitType.kRems
  1087. // type === UnitType.kChs ||
  1088. // this.isViewportPercentageLength(type) ||
  1089. // this.isContainerPercentageLength(type)
  1090. ;
  1091. };
  1092. CSSStyleValue.isTime = function isTime(unit) {
  1093. return unit === UnitType.kSeconds || unit === UnitType.kMilliseconds;
  1094. }
  1095. // protected abstract toCSSValue(): CSSValue;
  1096. ;
  1097. var _proto = CSSStyleValue.prototype;
  1098. _proto.toString = function toString() {
  1099. return this.buildCSSText(Nested.kNo, ParenLess.kNo, '');
  1100. };
  1101. _proto.isNumericValue = function isNumericValue() {
  1102. return this.getType() >= CSSStyleValueType.kUnitType && this.getType() <= CSSStyleValueType.kClampType;
  1103. };
  1104. return CSSStyleValue;
  1105. }();
  1106. /**
  1107. * CSSColorValue is the base class used for the various CSS color interfaces.
  1108. *
  1109. * @see https://drafts.css-houdini.org/css-typed-om-1/#colorvalue-objects
  1110. */
  1111. var CSSColorValue = /*#__PURE__*/function (_CSSStyleValue) {
  1112. _inheritsLoose(CSSColorValue, _CSSStyleValue);
  1113. function CSSColorValue(colorSpace) {
  1114. var _this;
  1115. _this = _CSSStyleValue.call(this) || this;
  1116. _this.colorSpace = void 0;
  1117. _this.colorSpace = colorSpace;
  1118. return _this;
  1119. }
  1120. var _proto = CSSColorValue.prototype;
  1121. _proto.getType = function getType() {
  1122. return CSSStyleValueType.kColorType;
  1123. }
  1124. // buildCSSText(n: Nested, p: ParenLess, result: string): string {
  1125. // let text = '';
  1126. // if (this.colorSpace === 'rgb') {
  1127. // text = `rgba(${this.channels.join(',')},${this.alpha})`;
  1128. // }
  1129. // return (result += text);
  1130. // }
  1131. /**
  1132. * @see https://drafts.css-houdini.org/css-typed-om-1/#dom-csscolorvalue-to
  1133. */;
  1134. _proto.to = function to(colorSpace) {
  1135. return this;
  1136. };
  1137. return CSSColorValue;
  1138. }(CSSStyleValue);
  1139. var GradientType;
  1140. (function (GradientType) {
  1141. GradientType[GradientType["Constant"] = 0] = "Constant";
  1142. GradientType[GradientType["LinearGradient"] = 1] = "LinearGradient";
  1143. GradientType[GradientType["RadialGradient"] = 2] = "RadialGradient";
  1144. })(GradientType || (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 = 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 === 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 UnitType.kUnknown:
  1365. // FIXME
  1366. break;
  1367. case UnitType.kInteger:
  1368. text = Number(this.value).toFixed(0);
  1369. break;
  1370. case UnitType.kNumber:
  1371. case UnitType.kPercentage:
  1372. case UnitType.kEms:
  1373. // case UnitType.kQuirkyEms:
  1374. // case UnitType.kExs:
  1375. case UnitType.kRems:
  1376. // case UnitType.kChs:
  1377. case 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 UnitType.kDegrees:
  1389. case UnitType.kRadians:
  1390. case UnitType.kGradians:
  1391. case UnitType.kMilliseconds:
  1392. case UnitType.kSeconds:
  1393. // case UnitType.kHertz:
  1394. // case UnitType.kKilohertz:
  1395. case 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 = 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 vec3.clone(x);
  1753. }
  1754. if (isNumber(x)) {
  1755. return vec3.fromValues(x, y, z);
  1756. }
  1757. return 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 = mat4.getScaling(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 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 = mat4.create();
  1912. var perspectiveMatrix = mat4.create();
  1913. var tmpVec4 = vec4.create();
  1914. var row = [vec3.create(), vec3.create(), vec3.create()];
  1915. var pdum3 = 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. 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(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 = mat4.invert(perspectiveMatrix, perspectiveMatrix);
  1959. if (!ret) return false;
  1960. mat4.transpose(perspectiveMatrix, perspectiveMatrix);
  1961. //multiply by transposed inverse perspective matrix, into perspective vec4
  1962. 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] = vec3.length(row[0]);
  1976. vec3.normalize(row[0], row[0]);
  1977. // Compute XY shear factor and make 2nd row orthogonal to 1st.
  1978. skew[0] = 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] = vec3.length(row[1]);
  1982. vec3.normalize(row[1], row[1]);
  1983. skew[0] /= scale[1];
  1984. // Compute XZ and YZ shears, orthogonalize 3rd row
  1985. skew[1] = vec3.dot(row[0], row[2]);
  1986. combine(row[2], row[2], row[0], 1.0, -skew[1]);
  1987. skew[2] = 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] = vec3.length(row[2]);
  1991. 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. vec3.cross(pdum3, row[1], row[2]);
  1998. if (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 = 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(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. mat4.set.apply(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 === UnitType.kPercentage) {
  2452. x = cx.value / 100 * width;
  2453. }
  2454. if (cy.unit === UnitType.kPercentage) {
  2455. y = cy.value / 100 * height;
  2456. }
  2457. // default to farthest-side
  2458. var r = Math.max(distanceSquareRoot([0, 0], [x, y]), distanceSquareRoot([0, height], [x, y]), distanceSquareRoot([width, height], [x, y]), 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(distanceSquareRoot([0, 0], [x, y]), distanceSquareRoot([0, height], [x, y]), distanceSquareRoot([width, height], [x, y]), distanceSquareRoot([width, 0], [x, y]));
  2470. }
  2471. }
  2472. }
  2473. return {
  2474. x: x,
  2475. y: y,
  2476. r: r
  2477. };
  2478. }
  2479. var Shape;
  2480. (function (Shape) {
  2481. Shape["GROUP"] = "g";
  2482. Shape["CIRCLE"] = "circle";
  2483. Shape["ELLIPSE"] = "ellipse";
  2484. Shape["IMAGE"] = "image";
  2485. Shape["RECT"] = "rect";
  2486. Shape["LINE"] = "line";
  2487. Shape["POLYLINE"] = "polyline";
  2488. Shape["POLYGON"] = "polygon";
  2489. Shape["TEXT"] = "text";
  2490. Shape["PATH"] = "path";
  2491. Shape["HTML"] = "html";
  2492. Shape["MESH"] = "mesh";
  2493. })(Shape || (Shape = {}));
  2494. function getOrCalculatePathTotalLength(path) {
  2495. if (path.parsedStyle.path.totalLength === 0) {
  2496. path.parsedStyle.path.totalLength = getTotalLength(path.parsedStyle.path.absolutePath);
  2497. }
  2498. return path.parsedStyle.path.totalLength;
  2499. }
  2500. function hasArcOrBezier(path) {
  2501. var hasArc = false;
  2502. var count = path.length;
  2503. for (var i = 0; i < count; i++) {
  2504. var params = path[i];
  2505. var cmd = params[0];
  2506. if (cmd === 'C' || cmd === 'A' || cmd === 'Q') {
  2507. hasArc = true;
  2508. break;
  2509. }
  2510. }
  2511. return hasArc;
  2512. }
  2513. function extractPolygons(pathArray) {
  2514. var polygons = [];
  2515. var polylines = [];
  2516. var points = []; // 防止第一个命令不是 'M'
  2517. for (var i = 0; i < pathArray.length; i++) {
  2518. var params = pathArray[i];
  2519. var cmd = params[0];
  2520. if (cmd === 'M') {
  2521. // 遇到 'M' 判定是否是新数组,新数组中没有点
  2522. if (points.length) {
  2523. // 如果存在点,则说明没有遇到 'Z',开始了一个新的多边形
  2524. polylines.push(points);
  2525. points = []; // 创建新的点
  2526. }
  2527. points.push([params[1], params[2]]);
  2528. } else if (cmd === 'Z') {
  2529. if (points.length) {
  2530. // 存在点
  2531. polygons.push(points);
  2532. points = []; // 开始新的点集合
  2533. }
  2534. // 如果不存在点,同时 'Z',则说明是错误,不处理
  2535. } else {
  2536. points.push([params[1], params[2]]);
  2537. }
  2538. }
  2539. // 说明 points 未放入 polygons 或者 polyline
  2540. // 仅当只有一个 M,没有 Z 时会发生这种情况
  2541. if (points.length > 0) {
  2542. polylines.push(points);
  2543. }
  2544. return {
  2545. polygons: polygons,
  2546. polylines: polylines
  2547. };
  2548. }
  2549. function isSamePoint(point1, point2) {
  2550. return point1[0] === point2[0] && point1[1] === point2[1];
  2551. }
  2552. function getPathBBox(segments, lineWidth) {
  2553. var xArr = [];
  2554. var yArr = [];
  2555. var segmentsWithAngle = [];
  2556. for (var i = 0; i < segments.length; i++) {
  2557. var segment = segments[i];
  2558. var currentPoint = segment.currentPoint,
  2559. params = segment.params,
  2560. prePoint = segment.prePoint;
  2561. var box = void 0;
  2562. switch (segment.command) {
  2563. case 'Q':
  2564. box = Quad.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4]);
  2565. break;
  2566. case 'C':
  2567. box = Cubic.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4], params[5], params[6]);
  2568. break;
  2569. case 'A':
  2570. var arcParams = segment.arcParams;
  2571. box = Arc.box(arcParams.cx, arcParams.cy, arcParams.rx, arcParams.ry, arcParams.xRotation, arcParams.startAngle, arcParams.endAngle);
  2572. break;
  2573. default:
  2574. xArr.push(currentPoint[0]);
  2575. yArr.push(currentPoint[1]);
  2576. break;
  2577. }
  2578. if (box) {
  2579. segment.box = box;
  2580. xArr.push(box.x, box.x + box.width);
  2581. yArr.push(box.y, box.y + box.height);
  2582. }
  2583. if (lineWidth && (segment.command === 'L' || segment.command === 'M') && segment.prePoint && segment.nextPoint) {
  2584. segmentsWithAngle.push(segment);
  2585. }
  2586. }
  2587. // bbox calculation should ignore NaN for path attribute
  2588. // ref: https://github.com/antvis/g/issues/210
  2589. // ref: https://github.com/antvis/G2/issues/3109
  2590. xArr = xArr.filter(function (item) {
  2591. return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
  2592. });
  2593. yArr = yArr.filter(function (item) {
  2594. return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
  2595. });
  2596. var minX = min(xArr);
  2597. var minY = min(yArr);
  2598. var maxX = max(xArr);
  2599. var maxY = max(yArr);
  2600. if (segmentsWithAngle.length === 0) {
  2601. return {
  2602. x: minX,
  2603. y: minY,
  2604. width: maxX - minX,
  2605. height: maxY - minY
  2606. };
  2607. }
  2608. for (var _i = 0; _i < segmentsWithAngle.length; _i++) {
  2609. var _segment = segmentsWithAngle[_i];
  2610. var _currentPoint = _segment.currentPoint;
  2611. var extra = void 0;
  2612. if (_currentPoint[0] === minX) {
  2613. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2614. minX = minX - extra.xExtra;
  2615. } else if (_currentPoint[0] === maxX) {
  2616. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2617. maxX = maxX + extra.xExtra;
  2618. }
  2619. if (_currentPoint[1] === minY) {
  2620. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2621. minY = minY - extra.yExtra;
  2622. } else if (_currentPoint[1] === maxY) {
  2623. extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
  2624. maxY = maxY + extra.yExtra;
  2625. }
  2626. }
  2627. return {
  2628. x: minX,
  2629. y: minY,
  2630. width: maxX - minX,
  2631. height: maxY - minY
  2632. };
  2633. }
  2634. function getExtraFromSegmentWithAngle(segment, lineWidth) {
  2635. var prePoint = segment.prePoint,
  2636. currentPoint = segment.currentPoint,
  2637. nextPoint = segment.nextPoint;
  2638. var currentAndPre = Math.pow(currentPoint[0] - prePoint[0], 2) + Math.pow(currentPoint[1] - prePoint[1], 2);
  2639. var currentAndNext = Math.pow(currentPoint[0] - nextPoint[0], 2) + Math.pow(currentPoint[1] - nextPoint[1], 2);
  2640. var preAndNext = Math.pow(prePoint[0] - nextPoint[0], 2) + Math.pow(prePoint[1] - nextPoint[1], 2);
  2641. // 以 currentPoint 为顶点的夹角
  2642. var currentAngle = Math.acos((currentAndPre + currentAndNext - preAndNext) / (2 * Math.sqrt(currentAndPre) * Math.sqrt(currentAndNext)));
  2643. // 夹角为空、 0 或 PI 时,不需要计算夹角处的额外宽度
  2644. // 注意: 由于计算精度问题,夹角为 0 的情况计算出来的角度可能是一个很小的值,还需要判断其与 0 是否近似相等
  2645. if (!currentAngle || Math.sin(currentAngle) === 0 || isNumberEqual(currentAngle, 0)) {
  2646. return {
  2647. xExtra: 0,
  2648. yExtra: 0
  2649. };
  2650. }
  2651. var xAngle = Math.abs(Math.atan2(nextPoint[1] - currentPoint[1], nextPoint[0] - currentPoint[0]));
  2652. var yAngle = Math.abs(Math.atan2(nextPoint[0] - currentPoint[0], nextPoint[1] - currentPoint[1]));
  2653. // 将夹角转为锐角
  2654. xAngle = xAngle > Math.PI / 2 ? Math.PI - xAngle : xAngle;
  2655. yAngle = yAngle > Math.PI / 2 ? Math.PI - yAngle : yAngle;
  2656. // 这里不考虑在水平和垂直方向的投影,直接使用最大差值
  2657. // 由于上层统一加减了二分之一线宽,这里需要进行弥补
  2658. var extra = {
  2659. // 水平方向投影
  2660. xExtra: Math.cos(currentAngle / 2 - xAngle) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0,
  2661. // 垂直方向投影
  2662. yExtra: Math.cos(yAngle - currentAngle / 2) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0
  2663. };
  2664. return extra;
  2665. }
  2666. // 点对称
  2667. function toSymmetry(point, center) {
  2668. return [center[0] + (center[0] - point[0]), center[1] + (center[1] - point[1])];
  2669. }
  2670. var angleBetween = function angleBetween(v0, v1) {
  2671. var p = v0.x * v1.x + v0.y * v1.y;
  2672. var n = Math.sqrt((Math.pow(v0.x, 2) + Math.pow(v0.y, 2)) * (Math.pow(v1.x, 2) + Math.pow(v1.y, 2)));
  2673. var sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1 : 1;
  2674. var angle = sign * Math.acos(p / n);
  2675. return angle;
  2676. };
  2677. /**
  2678. * @see https://github.com/rveciana/svg-path-properties/blob/b6bd9a322966f6ef7a311872d80c56e3718de861/src/arc.ts#L121
  2679. */
  2680. var pointOnEllipticalArc = function pointOnEllipticalArc(p0, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p1, t) {
  2681. // In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
  2682. rx = Math.abs(rx);
  2683. ry = Math.abs(ry);
  2684. xAxisRotation = mod(xAxisRotation, 360);
  2685. var xAxisRotationRadians = deg2rad(xAxisRotation);
  2686. // If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
  2687. if (p0.x === p1.x && p0.y === p1.y) {
  2688. return {
  2689. x: p0.x,
  2690. y: p0.y,
  2691. ellipticalArcAngle: 0
  2692. }; // Check if angle is correct
  2693. }
  2694. // If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
  2695. if (rx === 0 || ry === 0) {
  2696. //return this.pointOnLine(p0, p1, t);
  2697. return {
  2698. x: 0,
  2699. y: 0,
  2700. ellipticalArcAngle: 0
  2701. }; // Check if angle is correct
  2702. }
  2703. // Following "Conversion from endpoint to center parameterization"
  2704. // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
  2705. // Step #1: Compute transformedPoint
  2706. var dx = (p0.x - p1.x) / 2;
  2707. var dy = (p0.y - p1.y) / 2;
  2708. var transformedPoint = {
  2709. x: Math.cos(xAxisRotationRadians) * dx + Math.sin(xAxisRotationRadians) * dy,
  2710. y: -Math.sin(xAxisRotationRadians) * dx + Math.cos(xAxisRotationRadians) * dy
  2711. };
  2712. // Ensure radii are large enough
  2713. var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
  2714. if (radiiCheck > 1) {
  2715. rx = Math.sqrt(radiiCheck) * rx;
  2716. ry = Math.sqrt(radiiCheck) * ry;
  2717. }
  2718. // Step #2: Compute transformedCenter
  2719. 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);
  2720. var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
  2721. var cRadicand = cSquareNumerator / cSquareRootDenom;
  2722. // Make sure this never drops below zero because of precision
  2723. cRadicand = cRadicand < 0 ? 0 : cRadicand;
  2724. var cCoef = (largeArcFlag !== sweepFlag ? 1 : -1) * Math.sqrt(cRadicand);
  2725. var transformedCenter = {
  2726. x: cCoef * (rx * transformedPoint.y / ry),
  2727. y: cCoef * (-(ry * transformedPoint.x) / rx)
  2728. };
  2729. // Step #3: Compute center
  2730. var center = {
  2731. x: Math.cos(xAxisRotationRadians) * transformedCenter.x - Math.sin(xAxisRotationRadians) * transformedCenter.y + (p0.x + p1.x) / 2,
  2732. y: Math.sin(xAxisRotationRadians) * transformedCenter.x + Math.cos(xAxisRotationRadians) * transformedCenter.y + (p0.y + p1.y) / 2
  2733. };
  2734. // Step #4: Compute start/sweep angles
  2735. // Start angle of the elliptical arc prior to the stretch and rotate operations.
  2736. // Difference between the start and end angles
  2737. var startVector = {
  2738. x: (transformedPoint.x - transformedCenter.x) / rx,
  2739. y: (transformedPoint.y - transformedCenter.y) / ry
  2740. };
  2741. var startAngle = angleBetween({
  2742. x: 1,
  2743. y: 0
  2744. }, startVector);
  2745. var endVector = {
  2746. x: (-transformedPoint.x - transformedCenter.x) / rx,
  2747. y: (-transformedPoint.y - transformedCenter.y) / ry
  2748. };
  2749. var sweepAngle = angleBetween(startVector, endVector);
  2750. if (!sweepFlag && sweepAngle > 0) {
  2751. sweepAngle -= 2 * Math.PI;
  2752. } else if (sweepFlag && sweepAngle < 0) {
  2753. sweepAngle += 2 * Math.PI;
  2754. }
  2755. // We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
  2756. sweepAngle %= 2 * Math.PI;
  2757. // From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
  2758. var angle = startAngle + sweepAngle * t;
  2759. var ellipseComponentX = rx * Math.cos(angle);
  2760. var ellipseComponentY = ry * Math.sin(angle);
  2761. var point = {
  2762. x: Math.cos(xAxisRotationRadians) * ellipseComponentX - Math.sin(xAxisRotationRadians) * ellipseComponentY + center.x,
  2763. y: Math.sin(xAxisRotationRadians) * ellipseComponentX + Math.cos(xAxisRotationRadians) * ellipseComponentY + center.y,
  2764. ellipticalArcStartAngle: startAngle,
  2765. ellipticalArcEndAngle: startAngle + sweepAngle,
  2766. ellipticalArcAngle: angle,
  2767. ellipticalArcCenter: center,
  2768. resultantRx: rx,
  2769. resultantRy: ry
  2770. };
  2771. return point;
  2772. };
  2773. function path2Segments(path) {
  2774. var segments = [];
  2775. var currentPoint = null; // 当前图形
  2776. var nextParams = null; // 下一节点的 path 参数
  2777. var startMovePoint = null; // 开始 M 的点,可能会有多个
  2778. var lastStartMovePointIndex = 0; // 最近一个开始点 M 的索引
  2779. var count = path.length;
  2780. for (var i = 0; i < count; i++) {
  2781. var params = path[i];
  2782. nextParams = path[i + 1];
  2783. var command = params[0];
  2784. // 数学定义上的参数,便于后面的计算
  2785. var segment = {
  2786. command: command,
  2787. prePoint: currentPoint,
  2788. params: params,
  2789. startTangent: null,
  2790. endTangent: null,
  2791. currentPoint: null,
  2792. nextPoint: null,
  2793. arcParams: null,
  2794. box: null,
  2795. cubicParams: null
  2796. };
  2797. switch (command) {
  2798. case 'M':
  2799. startMovePoint = [params[1], params[2]];
  2800. lastStartMovePointIndex = i;
  2801. break;
  2802. case 'A':
  2803. var arcParams = getArcParams(currentPoint, params);
  2804. segment.arcParams = arcParams;
  2805. break;
  2806. }
  2807. if (command === 'Z') {
  2808. // 有了 Z 后,当前节点从开始 M 的点开始
  2809. currentPoint = startMovePoint;
  2810. // 如果当前点的命令为 Z,相当于当前点为最近一个 M 点,则下一个点直接指向最近一个 M 点的下一个点
  2811. nextParams = path[lastStartMovePointIndex + 1];
  2812. } else {
  2813. var len = params.length;
  2814. currentPoint = [params[len - 2], params[len - 1]];
  2815. }
  2816. if (nextParams && nextParams[0] === 'Z') {
  2817. // 如果下一个点的命令为 Z,则下一个点直接指向最近一个 M 点
  2818. nextParams = path[lastStartMovePointIndex];
  2819. if (segments[lastStartMovePointIndex]) {
  2820. // 如果下一个点的命令为 Z,则最近一个 M 点的前一个点为当前点
  2821. segments[lastStartMovePointIndex].prePoint = currentPoint;
  2822. }
  2823. }
  2824. segment.currentPoint = currentPoint;
  2825. // 如果当前点与最近一个 M 点相同,则最近一个 M 点的前一个点为当前点的前一个点
  2826. if (segments[lastStartMovePointIndex] && isSamePoint(currentPoint, segments[lastStartMovePointIndex].currentPoint)) {
  2827. segments[lastStartMovePointIndex].prePoint = segment.prePoint;
  2828. }
  2829. var nextPoint = nextParams ? [nextParams[nextParams.length - 2], nextParams[nextParams.length - 1]] : null;
  2830. segment.nextPoint = nextPoint;
  2831. // Add startTangent and endTangent
  2832. var prePoint = segment.prePoint;
  2833. if (['L', 'H', 'V'].includes(command)) {
  2834. segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
  2835. segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
  2836. } else if (command === 'Q') {
  2837. // 二次贝塞尔曲线只有一个控制点
  2838. var cp = [params[1], params[2]];
  2839. // 二次贝塞尔曲线的终点为 currentPoint
  2840. segment.startTangent = [prePoint[0] - cp[0], prePoint[1] - cp[1]];
  2841. segment.endTangent = [currentPoint[0] - cp[0], currentPoint[1] - cp[1]];
  2842. } else if (command === 'T') {
  2843. var preSegment = segments[i - 1];
  2844. var _cp = toSymmetry(preSegment.currentPoint, prePoint);
  2845. if (preSegment.command === 'Q') {
  2846. segment.command = 'Q';
  2847. segment.startTangent = [prePoint[0] - _cp[0], prePoint[1] - _cp[1]];
  2848. segment.endTangent = [currentPoint[0] - _cp[0], currentPoint[1] - _cp[1]];
  2849. } else {
  2850. // @ts-ignore
  2851. segment.command = 'TL';
  2852. segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
  2853. segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
  2854. }
  2855. } else if (command === 'C') {
  2856. // 三次贝塞尔曲线有两个控制点
  2857. var cp1 = [params[1], params[2]];
  2858. var cp2 = [params[3], params[4]];
  2859. segment.startTangent = [prePoint[0] - cp1[0], prePoint[1] - cp1[1]];
  2860. segment.endTangent = [currentPoint[0] - cp2[0], currentPoint[1] - cp2[1]];
  2861. // horizontal line, eg. ['C', 100, 100, 100, 100, 200, 200]
  2862. if (segment.startTangent[0] === 0 && segment.startTangent[1] === 0) {
  2863. segment.startTangent = [cp1[0] - cp2[0], cp1[1] - cp2[1]];
  2864. }
  2865. if (segment.endTangent[0] === 0 && segment.endTangent[1] === 0) {
  2866. segment.endTangent = [cp2[0] - cp1[0], cp2[1] - cp1[1]];
  2867. }
  2868. } else if (command === 'S') {
  2869. var _preSegment = segments[i - 1];
  2870. var _cp2 = toSymmetry(_preSegment.currentPoint, prePoint);
  2871. var _cp3 = [params[1], params[2]];
  2872. if (_preSegment.command === 'C') {
  2873. segment.command = 'C'; // 将 S 命令变换为 C 命令
  2874. segment.startTangent = [prePoint[0] - _cp2[0], prePoint[1] - _cp2[1]];
  2875. segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
  2876. } else {
  2877. // @ts-ignore
  2878. segment.command = 'SQ'; // 将 S 命令变换为 SQ 命令
  2879. segment.startTangent = [prePoint[0] - _cp3[0], prePoint[1] - _cp3[1]];
  2880. segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
  2881. }
  2882. } else if (command === 'A') {
  2883. var _getTangentAtRatio = getTangentAtRatio(segment, 0),
  2884. dx1 = _getTangentAtRatio.x,
  2885. dy1 = _getTangentAtRatio.y;
  2886. var _getTangentAtRatio2 = getTangentAtRatio(segment, 1, false),
  2887. dx2 = _getTangentAtRatio2.x,
  2888. dy2 = _getTangentAtRatio2.y;
  2889. segment.startTangent = [dx1, dy1];
  2890. segment.endTangent = [dx2, dy2];
  2891. }
  2892. segments.push(segment);
  2893. }
  2894. return segments;
  2895. }
  2896. /**
  2897. * Use length instead of ratio
  2898. */
  2899. function getTangentAtRatio(segment, ratio, sign) {
  2900. if (sign === void 0) {
  2901. sign = true;
  2902. }
  2903. var _segment$arcParams = segment.arcParams,
  2904. _segment$arcParams$rx = _segment$arcParams.rx,
  2905. rx = _segment$arcParams$rx === void 0 ? 0 : _segment$arcParams$rx,
  2906. _segment$arcParams$ry = _segment$arcParams.ry,
  2907. ry = _segment$arcParams$ry === void 0 ? 0 : _segment$arcParams$ry,
  2908. xRotation = _segment$arcParams.xRotation,
  2909. arcFlag = _segment$arcParams.arcFlag,
  2910. sweepFlag = _segment$arcParams.sweepFlag;
  2911. var p1 = pointOnEllipticalArc({
  2912. x: segment.prePoint[0],
  2913. y: segment.prePoint[1]
  2914. }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
  2915. x: segment.currentPoint[0],
  2916. y: segment.currentPoint[1]
  2917. }, ratio);
  2918. var p2 = pointOnEllipticalArc({
  2919. x: segment.prePoint[0],
  2920. y: segment.prePoint[1]
  2921. }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
  2922. x: segment.currentPoint[0],
  2923. y: segment.currentPoint[1]
  2924. }, sign ? ratio + 0.005 : ratio - 0.005);
  2925. var xDist = p2.x - p1.x;
  2926. var yDist = p2.y - p1.y;
  2927. var dist = Math.sqrt(xDist * xDist + yDist * yDist);
  2928. return {
  2929. x: -xDist / dist,
  2930. y: -yDist / dist
  2931. };
  2932. }
  2933. // 向量长度
  2934. function vMag(v) {
  2935. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  2936. }
  2937. // u.v/|u||v|,计算夹角的余弦值
  2938. function vRatio(u, v) {
  2939. // 当存在一个向量的长度为 0 时,夹角也为 0,即夹角的余弦值为 1
  2940. return vMag(u) * vMag(v) ? (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)) : 1;
  2941. }
  2942. // 向量角度
  2943. function vAngle(u, v) {
  2944. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
  2945. }
  2946. function getArcParams(startPoint, params) {
  2947. var rx = params[1];
  2948. var ry = params[2];
  2949. var xRotation = mod(deg2rad(params[3]), Math.PI * 2);
  2950. var arcFlag = params[4];
  2951. var sweepFlag = params[5];
  2952. // 弧形起点坐标
  2953. var x1 = startPoint[0];
  2954. var y1 = startPoint[1];
  2955. // 弧形终点坐标
  2956. var x2 = params[6];
  2957. var y2 = params[7];
  2958. var xp = Math.cos(xRotation) * (x1 - x2) / 2.0 + Math.sin(xRotation) * (y1 - y2) / 2.0;
  2959. var yp = -1 * Math.sin(xRotation) * (x1 - x2) / 2.0 + Math.cos(xRotation) * (y1 - y2) / 2.0;
  2960. var lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
  2961. if (lambda > 1) {
  2962. rx *= Math.sqrt(lambda);
  2963. ry *= Math.sqrt(lambda);
  2964. }
  2965. var diff = rx * rx * (yp * yp) + ry * ry * (xp * xp);
  2966. var f = diff ? Math.sqrt((rx * rx * (ry * ry) - diff) / diff) : 1;
  2967. if (arcFlag === sweepFlag) {
  2968. f *= -1;
  2969. }
  2970. if (isNaN(f)) {
  2971. f = 0;
  2972. }
  2973. // 旋转前的起点坐标,且当长半轴和短半轴的长度为 0 时,坐标按 (0, 0) 处理
  2974. var cxp = ry ? f * rx * yp / ry : 0;
  2975. var cyp = rx ? f * -ry * xp / rx : 0;
  2976. // 椭圆圆心坐标
  2977. var cx = (x1 + x2) / 2.0 + Math.cos(xRotation) * cxp - Math.sin(xRotation) * cyp;
  2978. var cy = (y1 + y2) / 2.0 + Math.sin(xRotation) * cxp + Math.cos(xRotation) * cyp;
  2979. // 起始点的单位向量
  2980. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  2981. // 终止点的单位向量
  2982. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  2983. // 计算起始点和圆心的连线,与 x 轴正方向的夹角
  2984. var theta = vAngle([1, 0], u);
  2985. // 计算圆弧起始点和终止点与椭圆圆心连线的夹角
  2986. var dTheta = vAngle(u, v);
  2987. if (vRatio(u, v) <= -1) {
  2988. dTheta = Math.PI;
  2989. }
  2990. if (vRatio(u, v) >= 1) {
  2991. dTheta = 0;
  2992. }
  2993. if (sweepFlag === 0 && dTheta > 0) {
  2994. dTheta = dTheta - 2 * Math.PI;
  2995. }
  2996. if (sweepFlag === 1 && dTheta < 0) {
  2997. dTheta = dTheta + 2 * Math.PI;
  2998. }
  2999. return {
  3000. cx: cx,
  3001. cy: cy,
  3002. // 弧形的起点和终点相同时,长轴和短轴的长度按 0 处理
  3003. rx: isSamePoint(startPoint, [x2, y2]) ? 0 : rx,
  3004. ry: isSamePoint(startPoint, [x2, y2]) ? 0 : ry,
  3005. startAngle: theta,
  3006. endAngle: theta + dTheta,
  3007. xRotation: xRotation,
  3008. arcFlag: arcFlag,
  3009. sweepFlag: sweepFlag
  3010. };
  3011. }
  3012. function commandsToPathString(commands, object, transform) {
  3013. var _object$parsedStyle = object.parsedStyle,
  3014. _object$parsedStyle$d = _object$parsedStyle.defX,
  3015. defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
  3016. _object$parsedStyle$d2 = _object$parsedStyle.defY,
  3017. defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
  3018. return commands.reduce(function (prev, cur) {
  3019. var path = '';
  3020. if (cur[0] === 'M' || cur[0] === 'L') {
  3021. var p = vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
  3022. if (transform) {
  3023. vec3.transformMat4(p, p, transform);
  3024. }
  3025. path = "" + cur[0] + p[0] + "," + p[1];
  3026. } else if (cur[0] === 'Z') {
  3027. path = cur[0];
  3028. } else if (cur[0] === 'C') {
  3029. var p1 = vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
  3030. var p2 = vec3.fromValues(cur[3] - defX, cur[4] - defY, 0);
  3031. var p3 = vec3.fromValues(cur[5] - defX, cur[6] - defY, 0);
  3032. if (transform) {
  3033. vec3.transformMat4(p1, p1, transform);
  3034. vec3.transformMat4(p2, p2, transform);
  3035. vec3.transformMat4(p3, p3, transform);
  3036. }
  3037. path = "" + cur[0] + p1[0] + "," + p1[1] + "," + p2[0] + "," + p2[1] + "," + p3[0] + "," + p3[1];
  3038. } else if (cur[0] === 'A') {
  3039. var c = vec3.fromValues(cur[6] - defX, cur[7] - defY, 0);
  3040. if (transform) {
  3041. vec3.transformMat4(c, c, transform);
  3042. }
  3043. path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "," + cur[5] + "," + c[0] + "," + c[1];
  3044. } else if (cur[0] === 'Q') {
  3045. var _p = vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
  3046. var _p2 = vec3.fromValues(cur[3] - defX, cur[4] - defY, 0);
  3047. if (transform) {
  3048. vec3.transformMat4(_p, _p, transform);
  3049. vec3.transformMat4(_p2, _p2, transform);
  3050. }
  3051. path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "}";
  3052. }
  3053. return prev += path;
  3054. }, '');
  3055. }
  3056. function lineToCommands(x1, y1, x2, y2) {
  3057. return [['M', x1, y1], ['L', x2, y2]];
  3058. }
  3059. function ellipseToCommands(rx, ry, cx, cy) {
  3060. var factor = (-1 + Math.sqrt(2)) / 3 * 4;
  3061. var dx = rx * factor;
  3062. var dy = ry * factor;
  3063. var left = cx - rx;
  3064. var right = cx + rx;
  3065. var top = cy - ry;
  3066. var bottom = cy + ry;
  3067. 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']];
  3068. }
  3069. function polygonToCommands(points, closed) {
  3070. var result = points.map(function (point, i) {
  3071. return [i === 0 ? 'M' : 'L', point[0], point[1]];
  3072. });
  3073. if (closed) {
  3074. result.push(['Z']);
  3075. }
  3076. return result;
  3077. }
  3078. function rectToCommands(width, height, x, y, radius) {
  3079. // @see https://gist.github.com/danielpquinn/dd966af424030d47e476
  3080. if (radius) {
  3081. var tlr = radius[0],
  3082. trr = radius[1],
  3083. brr = radius[2],
  3084. blr = radius[3];
  3085. var signX = width > 0 ? 1 : -1;
  3086. var signY = height > 0 ? 1 : -1;
  3087. // sweep-flag @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths#arcs
  3088. var sweepFlag = signX + signY !== 0 ? 1 : 0;
  3089. 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) {
  3090. return command;
  3091. });
  3092. }
  3093. return [['M', x, y], ['L', x + width, y], ['L', x + width, y + height], ['L', x, y + height], ['Z']];
  3094. }
  3095. /**
  3096. * convert object to path, should account for:
  3097. * * transform & origin
  3098. * * anchor
  3099. * * lineWidth
  3100. */
  3101. function convertToPath(object, transform) {
  3102. if (transform === void 0) {
  3103. transform = object.getLocalTransform();
  3104. }
  3105. var commands = [];
  3106. switch (object.nodeName) {
  3107. case Shape.LINE:
  3108. var _object$parsedStyle2 = object.parsedStyle,
  3109. x1 = _object$parsedStyle2.x1,
  3110. y1 = _object$parsedStyle2.y1,
  3111. x2 = _object$parsedStyle2.x2,
  3112. y2 = _object$parsedStyle2.y2;
  3113. commands = lineToCommands(x1, y1, x2, y2);
  3114. break;
  3115. case Shape.CIRCLE:
  3116. {
  3117. var _object$parsedStyle3 = object.parsedStyle,
  3118. r = _object$parsedStyle3.r,
  3119. cx = _object$parsedStyle3.cx,
  3120. cy = _object$parsedStyle3.cy;
  3121. commands = ellipseToCommands(r, r, cx, cy);
  3122. break;
  3123. }
  3124. case Shape.ELLIPSE:
  3125. {
  3126. var _object$parsedStyle4 = object.parsedStyle,
  3127. rx = _object$parsedStyle4.rx,
  3128. ry = _object$parsedStyle4.ry,
  3129. _cx = _object$parsedStyle4.cx,
  3130. _cy = _object$parsedStyle4.cy;
  3131. commands = ellipseToCommands(rx, ry, _cx, _cy);
  3132. break;
  3133. }
  3134. case Shape.POLYLINE:
  3135. case Shape.POLYGON:
  3136. var points = object.parsedStyle.points;
  3137. commands = polygonToCommands(points.points, object.nodeName === Shape.POLYGON);
  3138. break;
  3139. case Shape.RECT:
  3140. var _object$parsedStyle5 = object.parsedStyle,
  3141. width = _object$parsedStyle5.width,
  3142. height = _object$parsedStyle5.height,
  3143. x = _object$parsedStyle5.x,
  3144. y = _object$parsedStyle5.y,
  3145. radius = _object$parsedStyle5.radius;
  3146. var hasRadius = radius && radius.some(function (r) {
  3147. return r !== 0;
  3148. });
  3149. commands = rectToCommands(width, height, x, y, hasRadius && radius.map(function (r) {
  3150. return clamp(r, 0, Math.min(Math.abs(width) / 2, Math.abs(height) / 2));
  3151. }));
  3152. break;
  3153. case Shape.PATH:
  3154. var absolutePath = object.parsedStyle.path.absolutePath;
  3155. commands = [].concat(absolutePath);
  3156. break;
  3157. }
  3158. if (commands.length) {
  3159. return commandsToPathString(commands, object, transform);
  3160. }
  3161. }
  3162. function translatePathToString(absolutePath, defX, defY, startOffsetX, startOffsetY, endOffsetX, endOffsetY) {
  3163. if (startOffsetX === void 0) {
  3164. startOffsetX = 0;
  3165. }
  3166. if (startOffsetY === void 0) {
  3167. startOffsetY = 0;
  3168. }
  3169. if (endOffsetX === void 0) {
  3170. endOffsetX = 0;
  3171. }
  3172. if (endOffsetY === void 0) {
  3173. endOffsetY = 0;
  3174. }
  3175. var newValue = absolutePath.map(function (params, i) {
  3176. var command = params[0];
  3177. var nextSegment = absolutePath[i + 1];
  3178. var useStartOffset = i === 0 && (startOffsetX !== 0 || startOffsetY !== 0);
  3179. var useEndOffset = (i === absolutePath.length - 1 || nextSegment && (nextSegment[0] === 'M' || nextSegment[0] === 'Z')) && endOffsetX !== 0 && endOffsetY !== 0;
  3180. switch (command) {
  3181. case 'M':
  3182. // Use start marker offset
  3183. if (useStartOffset) {
  3184. return "M " + (params[1] - defX + startOffsetX) + "," + (params[2] - defY + startOffsetY) + " L " + (params[1] - defX) + "," + (params[2] - defY);
  3185. } else {
  3186. return "M " + (params[1] - defX) + "," + (params[2] - defY);
  3187. }
  3188. case 'L':
  3189. return "L " + (params[1] - defX + (useEndOffset ? endOffsetX : 0)) + "," + (params[2] - defY + (useEndOffset ? endOffsetY : 0));
  3190. case 'Q':
  3191. return "Q " + (params[1] - defX) + " " + (params[2] - defY) + "," + (params[3] - defX) + " " + (params[4] - defY) + (useEndOffset ? " L " + (params[3] - defX + endOffsetX) + "," + (params[4] - defY + endOffsetY) : '');
  3192. case 'C':
  3193. 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) : '');
  3194. case 'A':
  3195. 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) : '');
  3196. case 'Z':
  3197. return 'Z';
  3198. }
  3199. }).join(' ');
  3200. if (~newValue.indexOf('NaN')) {
  3201. return '';
  3202. }
  3203. return newValue;
  3204. }
  3205. function isFillOrStrokeAffected(pointerEvents, fill, stroke) {
  3206. // account for pointerEvents
  3207. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
  3208. var hasFill = false;
  3209. var hasStroke = false;
  3210. var isFillOtherThanNone = !!fill && !fill.isNone;
  3211. var isStrokeOtherThanNone = !!stroke && !stroke.isNone;
  3212. if (pointerEvents === 'visiblepainted' || pointerEvents === 'painted' || pointerEvents === 'auto') {
  3213. hasFill = isFillOtherThanNone;
  3214. hasStroke = isStrokeOtherThanNone;
  3215. } else if (pointerEvents === 'visiblefill' || pointerEvents === 'fill') {
  3216. hasFill = true;
  3217. } else if (pointerEvents === 'visiblestroke' || pointerEvents === 'stroke') {
  3218. hasStroke = true;
  3219. } else if (pointerEvents === 'visible' || pointerEvents === 'all') {
  3220. // The values of the fill and stroke do not affect event processing.
  3221. hasFill = true;
  3222. hasStroke = true;
  3223. }
  3224. return [hasFill, hasStroke];
  3225. }
  3226. var AsyncParallelHook = /*#__PURE__*/function () {
  3227. function AsyncParallelHook() {
  3228. this.callbacks = [];
  3229. }
  3230. var _proto = AsyncParallelHook.prototype;
  3231. _proto.getCallbacksNum = function getCallbacksNum() {
  3232. return this.callbacks.length;
  3233. };
  3234. _proto.tapPromise = function tapPromise(options, fn) {
  3235. this.callbacks.push(fn);
  3236. };
  3237. _proto.promise = function promise() {
  3238. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3239. args[_key] = arguments[_key];
  3240. }
  3241. return Promise.all(this.callbacks.map(function (callback) {
  3242. return callback.apply(void 0, args);
  3243. }));
  3244. };
  3245. return AsyncParallelHook;
  3246. }();
  3247. var AsyncSeriesWaterfallHook = /*#__PURE__*/function () {
  3248. function AsyncSeriesWaterfallHook() {
  3249. this.callbacks = [];
  3250. }
  3251. var _proto = AsyncSeriesWaterfallHook.prototype;
  3252. _proto.tapPromise = function tapPromise(options, fn) {
  3253. this.callbacks.push(fn);
  3254. };
  3255. _proto.promise = /*#__PURE__*/function () {
  3256. var _promise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
  3257. var _this$callbacks,
  3258. result,
  3259. i,
  3260. callback,
  3261. _args = arguments;
  3262. return _regeneratorRuntime().wrap(function _callee$(_context) {
  3263. while (1) switch (_context.prev = _context.next) {
  3264. case 0:
  3265. if (!this.callbacks.length) {
  3266. _context.next = 14;
  3267. break;
  3268. }
  3269. _context.next = 3;
  3270. return (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, _args);
  3271. case 3:
  3272. result = _context.sent;
  3273. i = 0;
  3274. case 5:
  3275. if (!(i < this.callbacks.length - 1)) {
  3276. _context.next = 13;
  3277. break;
  3278. }
  3279. callback = this.callbacks[i]; // @ts-ignore
  3280. _context.next = 9;
  3281. return callback(result);
  3282. case 9:
  3283. result = _context.sent;
  3284. case 10:
  3285. i++;
  3286. _context.next = 5;
  3287. break;
  3288. case 13:
  3289. return _context.abrupt("return", result);
  3290. case 14:
  3291. return _context.abrupt("return", null);
  3292. case 15:
  3293. case "end":
  3294. return _context.stop();
  3295. }
  3296. }, _callee, this);
  3297. }));
  3298. function promise() {
  3299. return _promise.apply(this, arguments);
  3300. }
  3301. return promise;
  3302. }();
  3303. return AsyncSeriesWaterfallHook;
  3304. }();
  3305. var SyncHook = /*#__PURE__*/function () {
  3306. function SyncHook() {
  3307. this.callbacks = [];
  3308. }
  3309. var _proto = SyncHook.prototype;
  3310. _proto.tap = function tap(options, fn) {
  3311. this.callbacks.push(fn);
  3312. };
  3313. _proto.call = function call() {
  3314. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3315. args[_key] = arguments[_key];
  3316. }
  3317. this.callbacks.forEach(function (callback) {
  3318. callback.apply(void 0, args);
  3319. });
  3320. };
  3321. return SyncHook;
  3322. }();
  3323. var SyncWaterfallHook = /*#__PURE__*/function () {
  3324. function SyncWaterfallHook() {
  3325. this.callbacks = [];
  3326. }
  3327. var _proto = SyncWaterfallHook.prototype;
  3328. _proto.tap = function tap(options, fn) {
  3329. this.callbacks.push(fn);
  3330. };
  3331. _proto.call = function call() {
  3332. if (this.callbacks.length) {
  3333. var _this$callbacks;
  3334. var result = (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, arguments);
  3335. for (var i = 0; i < this.callbacks.length - 1; i++) {
  3336. var callback = this.callbacks[i];
  3337. // @ts-ignore
  3338. result = callback(result);
  3339. }
  3340. return result;
  3341. }
  3342. return null;
  3343. };
  3344. return SyncWaterfallHook;
  3345. }();
  3346. var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui'];
  3347. var stringRegExp = /([\"\'])[^\'\"]+\1/;
  3348. function toFontString(attributes) {
  3349. var fontSize = attributes.fontSize,
  3350. fontFamily = attributes.fontFamily,
  3351. fontStyle = attributes.fontStyle,
  3352. fontVariant = attributes.fontVariant,
  3353. fontWeight = attributes.fontWeight;
  3354. // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
  3355. // const fontSizeString: string = isNumber(fontSize) ? `${fontSize}px` : fontSize.toString();
  3356. var fontSizeString = isNumber(fontSize) && fontSize + "px" || '16px';
  3357. // Clean-up fontFamily property by quoting each font name
  3358. // this will support font names with spaces
  3359. var fontFamilies = fontFamily.split(',');
  3360. for (var i = fontFamilies.length - 1; i >= 0; i--) {
  3361. // Trim any extra white-space
  3362. var _fontFamily = fontFamilies[i].trim();
  3363. // Check if font already contains strings
  3364. if (!stringRegExp.test(_fontFamily) && genericFontFamilies.indexOf(_fontFamily) < 0) {
  3365. _fontFamily = "\"" + _fontFamily + "\"";
  3366. }
  3367. fontFamilies[i] = _fontFamily;
  3368. }
  3369. return fontStyle + " " + fontVariant + " " + fontWeight + " " + fontSizeString + " " + fontFamilies.join(',');
  3370. }
  3371. /**
  3372. * Thanks for following contributor of codes
  3373. * https://gist.github.com/1866474
  3374. * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  3375. * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  3376. * https://github.com/Financial-Times/polyfill-library/blob/master/polyfills/requestAnimationFrame/polyfill.js
  3377. **/
  3378. var uId = 1;
  3379. var uniqueId = function uniqueId() {
  3380. return uId++;
  3381. };
  3382. // We use `self` instead of `window` for `WebWorker` support.
  3383. var root = typeof self === 'object' && self.self == self ? self :
  3384. // @ts-ignore
  3385. typeof global === 'object' && global.global == global ?
  3386. // @ts-ignore
  3387. global : {};
  3388. var nowOffset = Date.now();
  3389. // use performance api if exist, otherwise use Date.now.
  3390. // Date.now polyfill required.
  3391. var pnow = function pnow() {
  3392. if (root.performance && typeof root.performance.now === 'function') {
  3393. return root.performance.now();
  3394. }
  3395. // fallback
  3396. return Date.now() - nowOffset;
  3397. };
  3398. var reservedCBs = {};
  3399. var lastTime = Date.now();
  3400. var polyfillRaf = function polyfillRaf(callback) {
  3401. if (typeof callback !== 'function') {
  3402. throw new TypeError(callback + ' is not a function');
  3403. }
  3404. var currentTime = Date.now();
  3405. var gap = currentTime - lastTime;
  3406. var delay = gap > 16 ? 0 : 16 - gap;
  3407. var id = uniqueId();
  3408. reservedCBs[id] = callback;
  3409. // keys(reservedCBs).length > 1 의미는 이미 setTimeout 이 걸려있는 경우.
  3410. // 함께 callback 이 실행될 수 있게 reservedCBs 에만 추가해주고 return
  3411. if (Object.keys(reservedCBs).length > 1) return id;
  3412. setTimeout(function () {
  3413. lastTime = currentTime;
  3414. var copied = reservedCBs;
  3415. reservedCBs = {};
  3416. Object.keys(copied).forEach(function (key) {
  3417. return copied[key](pnow());
  3418. });
  3419. }, delay);
  3420. return id;
  3421. };
  3422. var polyfillCaf = function polyfillCaf(id) {
  3423. delete reservedCBs[id];
  3424. };
  3425. var vendorPrefixes = ['', 'webkit', 'moz', 'ms', 'o'];
  3426. var getRequestAnimationFrame = function getRequestAnimationFrame(vp) {
  3427. if (typeof vp !== 'string') return polyfillRaf;
  3428. if (vp === '') return root['requestAnimationFrame'];
  3429. return root[vp + 'RequestAnimationFrame'];
  3430. };
  3431. var getCancelAnimationFrame = function getCancelAnimationFrame(vp) {
  3432. if (typeof vp !== 'string') return polyfillCaf;
  3433. if (vp === '') return root['cancelAnimationFrame'];
  3434. return root[vp + 'CancelAnimationFrame'] || root[vp + 'CancelRequestAnimationFrame'];
  3435. };
  3436. var find = function find(arr, predicate) {
  3437. var i = 0;
  3438. while (arr[i] !== void 0) {
  3439. if (predicate(arr[i])) return arr[i];
  3440. i = i + 1;
  3441. }
  3442. };
  3443. var vp = find(vendorPrefixes, function (vp) {
  3444. return !!getRequestAnimationFrame(vp);
  3445. });
  3446. var raf = getRequestAnimationFrame(vp);
  3447. var caf = getCancelAnimationFrame(vp);
  3448. root.requestAnimationFrame = raf;
  3449. root.cancelAnimationFrame = caf;
  3450. var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i;
  3451. var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i;
  3452. var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i;
  3453. var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/gi;
  3454. function spaceColorStops(colorStops) {
  3455. var _colorStops$length;
  3456. var length = colorStops.length;
  3457. colorStops[length - 1].length = (_colorStops$length = colorStops[length - 1].length) !== null && _colorStops$length !== void 0 ? _colorStops$length : {
  3458. type: '%',
  3459. value: '100'
  3460. };
  3461. if (length > 1) {
  3462. var _colorStops$0$length;
  3463. colorStops[0].length = (_colorStops$0$length = colorStops[0].length) !== null && _colorStops$0$length !== void 0 ? _colorStops$0$length : {
  3464. type: '%',
  3465. value: '0'
  3466. };
  3467. }
  3468. var previousIndex = 0;
  3469. var previousOffset = Number(colorStops[0].length.value);
  3470. for (var i = 1; i < length; i++) {
  3471. var _colorStops$i$length;
  3472. // support '%' & 'px'
  3473. var offset = (_colorStops$i$length = colorStops[i].length) === null || _colorStops$i$length === void 0 ? void 0 : _colorStops$i$length.value;
  3474. if (!isNil(offset) && !isNil(previousOffset)) {
  3475. for (var j = 1; j < i - previousIndex; j++) colorStops[previousIndex + j].length = {
  3476. type: '%',
  3477. value: "" + (previousOffset + (Number(offset) - previousOffset) * j / (i - previousIndex))
  3478. };
  3479. previousIndex = i;
  3480. previousOffset = Number(offset);
  3481. }
  3482. }
  3483. }
  3484. // The position of the gradient line's starting point.
  3485. // different from CSS side(to top) @see https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#values
  3486. var SideOrCornerToDegMap = {
  3487. left: 270 - 90,
  3488. top: 0 - 90,
  3489. bottom: 180 - 90,
  3490. right: 90 - 90,
  3491. 'left top': 315 - 90,
  3492. 'top left': 315 - 90,
  3493. 'left bottom': 225 - 90,
  3494. 'bottom left': 225 - 90,
  3495. 'right top': 45 - 90,
  3496. 'top right': 45 - 90,
  3497. 'right bottom': 135 - 90,
  3498. 'bottom right': 135 - 90
  3499. };
  3500. var angleToDeg = memoize(function (orientation) {
  3501. var angle;
  3502. if (orientation.type === 'angular') {
  3503. angle = Number(orientation.value);
  3504. } else {
  3505. angle = SideOrCornerToDegMap[orientation.value] || 0;
  3506. }
  3507. return getOrCreateUnitValue(angle, 'deg');
  3508. });
  3509. var positonToCSSUnitValue = memoize(function (position) {
  3510. var cx = 50;
  3511. var cy = 50;
  3512. var unitX = '%';
  3513. var unitY = '%';
  3514. if ((position === null || position === void 0 ? void 0 : position.type) === 'position') {
  3515. var _position$value = position.value,
  3516. x = _position$value.x,
  3517. y = _position$value.y;
  3518. if ((x === null || x === void 0 ? void 0 : x.type) === 'position-keyword') {
  3519. if (x.value === 'left') {
  3520. cx = 0;
  3521. } else if (x.value === 'center') {
  3522. cx = 50;
  3523. } else if (x.value === 'right') {
  3524. cx = 100;
  3525. } else if (x.value === 'top') {
  3526. cy = 0;
  3527. } else if (x.value === 'bottom') {
  3528. cy = 100;
  3529. }
  3530. }
  3531. if ((y === null || y === void 0 ? void 0 : y.type) === 'position-keyword') {
  3532. if (y.value === 'left') {
  3533. cx = 0;
  3534. } else if (y.value === 'center') {
  3535. cy = 50;
  3536. } else if (y.value === 'right') {
  3537. cx = 100;
  3538. } else if (y.value === 'top') {
  3539. cy = 0;
  3540. } else if (y.value === 'bottom') {
  3541. cy = 100;
  3542. }
  3543. }
  3544. 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') {
  3545. unitX = x === null || x === void 0 ? void 0 : x.type;
  3546. cx = Number(x.value);
  3547. }
  3548. 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') {
  3549. unitY = y === null || y === void 0 ? void 0 : y.type;
  3550. cy = Number(y.value);
  3551. }
  3552. }
  3553. return {
  3554. cx: getOrCreateUnitValue(cx, unitX),
  3555. cy: getOrCreateUnitValue(cy, unitY)
  3556. };
  3557. });
  3558. var parseGradient$1 = memoize(function (colorStr) {
  3559. if (colorStr.indexOf('linear') > -1 || colorStr.indexOf('radial') > -1) {
  3560. var ast = parseGradient(colorStr);
  3561. return ast.map(function (_ref) {
  3562. var type = _ref.type,
  3563. orientation = _ref.orientation,
  3564. colorStops = _ref.colorStops;
  3565. spaceColorStops(colorStops);
  3566. var steps = colorStops.map(function (colorStop) {
  3567. // TODO: only support % for now, should calc percentage of axis length when using px/em
  3568. return {
  3569. offset: getOrCreateUnitValue(Number(colorStop.length.value), '%'),
  3570. color: colorStopToString(colorStop)
  3571. };
  3572. });
  3573. if (type === 'linear-gradient') {
  3574. return new CSSGradientValue(GradientType.LinearGradient, {
  3575. angle: orientation ? angleToDeg(orientation) : Odeg,
  3576. steps: steps
  3577. });
  3578. } else if (type === 'radial-gradient') {
  3579. if (!orientation) {
  3580. orientation = [{
  3581. type: 'shape',
  3582. value: 'circle'
  3583. }];
  3584. }
  3585. if (orientation[0].type === 'shape' && orientation[0].value === 'circle') {
  3586. var _positonToCSSUnitValu = positonToCSSUnitValue(orientation[0].at),
  3587. cx = _positonToCSSUnitValu.cx,
  3588. cy = _positonToCSSUnitValu.cy;
  3589. var size;
  3590. if (orientation[0].style) {
  3591. var _orientation$0$style = orientation[0].style,
  3592. _type = _orientation$0$style.type,
  3593. value = _orientation$0$style.value;
  3594. if (_type === 'extent-keyword') {
  3595. size = getOrCreateKeyword(value);
  3596. } else {
  3597. size = getOrCreateUnitValue(value, _type);
  3598. }
  3599. }
  3600. return new CSSGradientValue(GradientType.RadialGradient, {
  3601. cx: cx,
  3602. cy: cy,
  3603. size: size,
  3604. steps: steps
  3605. });
  3606. }
  3607. // TODO: support ellipse shape
  3608. // TODO: repeating-linear-gradient & repeating-radial-gradient
  3609. // } else if (type === 'repeating-linear-gradient') {
  3610. // } else if (type === 'repeating-radial-gradient') {
  3611. }
  3612. });
  3613. }
  3614. // legacy format, should be deprecated later
  3615. var type = colorStr[0];
  3616. if (colorStr[1] === '(' || colorStr[2] === '(') {
  3617. if (type === 'l') {
  3618. var arr = regexLG.exec(colorStr);
  3619. if (arr) {
  3620. var _arr$2$match;
  3621. var steps = ((_arr$2$match = arr[2].match(regexColorStop)) === null || _arr$2$match === void 0 ? void 0 : _arr$2$match.map(function (stop) {
  3622. return stop.split(':');
  3623. })) || [];
  3624. return [new CSSGradientValue(GradientType.LinearGradient, {
  3625. angle: getOrCreateUnitValue(parseFloat(arr[1]), 'deg'),
  3626. steps: steps.map(function (_ref2) {
  3627. var offset = _ref2[0],
  3628. color = _ref2[1];
  3629. return {
  3630. offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
  3631. color: color
  3632. };
  3633. })
  3634. })];
  3635. }
  3636. } else if (type === 'r') {
  3637. var parsedRadialGradient = parseRadialGradient(colorStr);
  3638. if (parsedRadialGradient) {
  3639. if (isString(parsedRadialGradient)) {
  3640. colorStr = parsedRadialGradient;
  3641. } else {
  3642. return [new CSSGradientValue(GradientType.RadialGradient, parsedRadialGradient)];
  3643. }
  3644. }
  3645. } else if (type === 'p') {
  3646. return parsePattern(colorStr);
  3647. }
  3648. }
  3649. });
  3650. function parseRadialGradient(gradientStr) {
  3651. var arr = regexRG.exec(gradientStr);
  3652. if (arr) {
  3653. var _arr$4$match;
  3654. var steps = ((_arr$4$match = arr[4].match(regexColorStop)) === null || _arr$4$match === void 0 ? void 0 : _arr$4$match.map(function (stop) {
  3655. return stop.split(':');
  3656. })) || [];
  3657. return {
  3658. cx: getOrCreateUnitValue(50, '%'),
  3659. cy: getOrCreateUnitValue(50, '%'),
  3660. steps: steps.map(function (_ref3) {
  3661. var offset = _ref3[0],
  3662. color = _ref3[1];
  3663. return {
  3664. offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
  3665. color: color
  3666. };
  3667. })
  3668. };
  3669. }
  3670. return null;
  3671. }
  3672. function parsePattern(patternStr) {
  3673. var arr = regexPR.exec(patternStr);
  3674. if (arr) {
  3675. var repetition = arr[1];
  3676. var src = arr[2];
  3677. switch (repetition) {
  3678. case 'a':
  3679. repetition = 'repeat';
  3680. break;
  3681. case 'x':
  3682. repetition = 'repeat-x';
  3683. break;
  3684. case 'y':
  3685. repetition = 'repeat-y';
  3686. break;
  3687. case 'n':
  3688. repetition = 'no-repeat';
  3689. break;
  3690. default:
  3691. repetition = 'no-repeat';
  3692. }
  3693. return {
  3694. image: src,
  3695. // @ts-ignore
  3696. repetition: repetition
  3697. };
  3698. }
  3699. return null;
  3700. }
  3701. function isCSSGradientValue(object) {
  3702. return !!object.type && !!object.value;
  3703. }
  3704. function isPattern(object) {
  3705. return object && !!object.image;
  3706. }
  3707. function isCSSRGB(object) {
  3708. return object && !isNil(object.r) && !isNil(object.g) && !isNil(object.b);
  3709. }
  3710. /**
  3711. * @see https://github.com/WebKit/WebKit/blob/main/Source/WebCore/css/parser/CSSParser.cpp#L97
  3712. */
  3713. var parseColor = memoize(function (colorStr) {
  3714. if (isPattern(colorStr)) {
  3715. return _extends({
  3716. repetition: 'repeat'
  3717. }, colorStr);
  3718. }
  3719. if (isNil(colorStr)) {
  3720. colorStr = '';
  3721. }
  3722. if (colorStr === 'transparent') {
  3723. // transparent black
  3724. return transparentColor;
  3725. } else if (colorStr === 'currentColor') {
  3726. // @see https://github.com/adobe-webplatform/Snap.svg/issues/526
  3727. colorStr = 'black';
  3728. }
  3729. // support CSS gradient syntax
  3730. var g = parseGradient$1(colorStr);
  3731. if (g) {
  3732. return g;
  3733. }
  3734. // constants
  3735. var color$1 = color(colorStr);
  3736. var rgba = [0, 0, 0, 0];
  3737. if (color$1 !== null) {
  3738. rgba[0] = color$1.r || 0;
  3739. rgba[1] = color$1.g || 0;
  3740. rgba[2] = color$1.b || 0;
  3741. rgba[3] = color$1.opacity;
  3742. }
  3743. // return new CSSRGB(...rgba);
  3744. return getOrCreateRGBA.apply(void 0, rgba);
  3745. });
  3746. function mergeColors(left, right) {
  3747. // only support constant value, exclude gradient & pattern
  3748. if (!isCSSRGB(left) || !isCSSRGB(right)) {
  3749. return;
  3750. }
  3751. 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) {
  3752. var rgba = color.slice();
  3753. if (rgba[3]) {
  3754. for (var i = 0; i < 3; i++) rgba[i] = Math.round(clamp(rgba[i], 0, 255));
  3755. }
  3756. rgba[3] = clamp(rgba[3], 0, 1);
  3757. return "rgba(" + rgba.join(',') + ")";
  3758. }];
  3759. }
  3760. function parseDimension(unitRegExp, string) {
  3761. if (isNil(string)) {
  3762. return getOrCreateUnitValue(0, 'px');
  3763. }
  3764. string = ("" + string).trim().toLowerCase();
  3765. if (isFinite(Number(string))) {
  3766. if ('px'.search(unitRegExp) >= 0) {
  3767. return getOrCreateUnitValue(Number(string), 'px');
  3768. } else if ('deg'.search(unitRegExp) >= 0) {
  3769. return getOrCreateUnitValue(Number(string), 'deg');
  3770. }
  3771. }
  3772. var matchedUnits = [];
  3773. string = string.replace(unitRegExp, function (match) {
  3774. matchedUnits.push(match);
  3775. return 'U' + match;
  3776. });
  3777. var taggedUnitRegExp = 'U(' + unitRegExp.source + ')';
  3778. return matchedUnits.map(function (unit) {
  3779. return getOrCreateUnitValue(Number(string.replace(new RegExp('U' + unit, 'g'), '').replace(new RegExp(taggedUnitRegExp, 'g'), '*0')), unit);
  3780. })[0];
  3781. }
  3782. /**
  3783. * <length>
  3784. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length
  3785. * length with only absolute unit, eg. 1px
  3786. */
  3787. var parseLength = memoize(function (css) {
  3788. return parseDimension(new RegExp('px', 'g'), css);
  3789. });
  3790. /**
  3791. * <percentage>
  3792. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage
  3793. */
  3794. var parserPercentage = memoize(function (css) {
  3795. return parseDimension(new RegExp('%', 'g'), css);
  3796. });
  3797. /**
  3798. * length with absolute or relative unit,
  3799. * eg. 1px, 0.7em, 50%, calc(100% - 200px);
  3800. *
  3801. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length-percentage
  3802. */
  3803. // export const parseLengthOrPercentage = memoize((css: string): CSSUnitValue => {
  3804. // if (isNumber(css) || isFinite(Number(css))) {
  3805. // return getOrCreateUnitValue(Number(css), 'px');
  3806. // }
  3807. // return parseDimension(new RegExp('px|%|em|rem', 'g'), css) as CSSUnitValue;
  3808. // });
  3809. var parseLengthOrPercentage = function parseLengthOrPercentage(css) {
  3810. if (isNumber(css) || isFinite(Number(css))) {
  3811. // Number(css) is NaN
  3812. return getOrCreateUnitValue(Number(css) || 0, 'px');
  3813. // return Number(css);
  3814. }
  3815. return parseDimension(new RegExp('px|%|em|rem', 'g'), css);
  3816. };
  3817. var parseAngle = memoize(function (css) {
  3818. return parseDimension(new RegExp('deg|rad|grad|turn', 'g'), css);
  3819. });
  3820. /**
  3821. * merge CSSUnitValue
  3822. *
  3823. * @example
  3824. * 10px + 20px = 30px
  3825. * 10deg + 10rad
  3826. * 10% + 20% = 30%
  3827. */
  3828. function mergeDimensions(left, right, target, nonNegative, index) {
  3829. if (index === void 0) {
  3830. index = 0;
  3831. }
  3832. var unit = '';
  3833. var leftValue = left.value || 0;
  3834. var rightValue = right.value || 0;
  3835. var canonicalUnit = toCanonicalUnit(left.unit);
  3836. var leftCanonicalUnitValue = left.convertTo(canonicalUnit);
  3837. var rightCanonicalUnitValue = right.convertTo(canonicalUnit);
  3838. if (leftCanonicalUnitValue && rightCanonicalUnitValue) {
  3839. leftValue = leftCanonicalUnitValue.value;
  3840. rightValue = rightCanonicalUnitValue.value;
  3841. unit = unitTypeToString(left.unit);
  3842. } else {
  3843. // format '%' to 'px'
  3844. if (CSSUnitValue.isLength(left.unit) || CSSUnitValue.isLength(right.unit)) {
  3845. leftValue = convertPercentUnit(left, index, target);
  3846. rightValue = convertPercentUnit(right, index, target);
  3847. unit = 'px';
  3848. }
  3849. }
  3850. // // format 'rad' 'turn' to 'deg'
  3851. // if (CSSUnitValue.isAngle(left.unit) || CSSUnitValue.isAngle(right.unit)) {
  3852. // leftValue = convertAngleUnit(left);
  3853. // rightValue = convertAngleUnit(right);
  3854. // unit = 'deg';
  3855. // }
  3856. return [leftValue, rightValue, function (value) {
  3857. if (nonNegative) {
  3858. value = Math.max(value, 0);
  3859. }
  3860. return value + unit;
  3861. }];
  3862. }
  3863. function convertAngleUnit(value) {
  3864. var deg = 0;
  3865. if (value.unit === UnitType.kDegrees) {
  3866. deg = value.value;
  3867. } else if (value.unit === UnitType.kRadians) {
  3868. deg = rad2deg(Number(value.value));
  3869. } else if (value.unit === UnitType.kTurns) {
  3870. deg = turn2deg(Number(value.value));
  3871. }
  3872. return deg;
  3873. }
  3874. function parseDimensionArrayFormat(string, size) {
  3875. var parsed;
  3876. if (Array.isArray(string)) {
  3877. // [1, '2px', 3]
  3878. parsed = string.map(function (segment) {
  3879. return Number(segment);
  3880. });
  3881. } else if (isString(string)) {
  3882. parsed = string.split(' ').map(function (segment) {
  3883. return Number(segment);
  3884. });
  3885. } else if (isNumber(string)) {
  3886. parsed = [string];
  3887. }
  3888. if (size === 2) {
  3889. if (parsed.length === 1) {
  3890. return [parsed[0], parsed[0]];
  3891. } else {
  3892. return [parsed[0], parsed[1]];
  3893. }
  3894. } else {
  3895. if (parsed.length === 1) {
  3896. return [parsed[0], parsed[0], parsed[0], parsed[0]];
  3897. } else if (parsed.length === 2) {
  3898. return [parsed[0], parsed[1], parsed[0], parsed[1]];
  3899. } else if (parsed.length === 3) {
  3900. return [parsed[0], parsed[1], parsed[2], parsed[1]];
  3901. } else {
  3902. return [parsed[0], parsed[1], parsed[2], parsed[3]];
  3903. }
  3904. }
  3905. }
  3906. function parseDimensionArray(string) {
  3907. if (isString(string)) {
  3908. // "1px 2px 3px"
  3909. return string.split(' ').map(function (segment) {
  3910. return parseLengthOrPercentage(segment);
  3911. });
  3912. } else {
  3913. // [1, '2px', 3]
  3914. return string.map(function (segment) {
  3915. return parseLengthOrPercentage(segment.toString());
  3916. });
  3917. }
  3918. }
  3919. // export function mergeDimensionList(
  3920. // left: CSSUnitValue[],
  3921. // right: CSSUnitValue[],
  3922. // target: IElement | null,
  3923. // ): [number[], number[], (list: number[]) => string] | undefined {
  3924. // if (left.length !== right.length) {
  3925. // return;
  3926. // }
  3927. // const unit = left[0].unit;
  3928. // return [
  3929. // left.map((l) => l.value),
  3930. // right.map((l) => l.value),
  3931. // (values: number[]) => {
  3932. // return values.map((n) => new CSSUnitValue(n, unit)).join(' ');
  3933. // },
  3934. // ];
  3935. // }
  3936. function convertPercentUnit(valueWithUnit, vec3Index, target) {
  3937. if (valueWithUnit.value === 0) {
  3938. return 0;
  3939. }
  3940. if (valueWithUnit.unit === UnitType.kPixels) {
  3941. return Number(valueWithUnit.value);
  3942. } else if (valueWithUnit.unit === UnitType.kPercentage && target) {
  3943. var bounds = target.nodeName === Shape.GROUP ? target.getLocalBounds() :
  3944. // : target.getGeometryBounds();
  3945. target.geometry.contentBounds;
  3946. return valueWithUnit.value / 100 * bounds.halfExtents[vec3Index] * 2;
  3947. }
  3948. return 0;
  3949. }
  3950. var parseParam = function parseParam(css) {
  3951. return parseDimension(/deg|rad|grad|turn|px|%/g, css);
  3952. };
  3953. var supportedFilters = ['blur', 'brightness', 'drop-shadow', 'contrast', 'grayscale', 'sepia', 'saturate', 'hue-rotate', 'invert'];
  3954. function parseFilter(filterStr) {
  3955. if (filterStr === void 0) {
  3956. filterStr = '';
  3957. }
  3958. filterStr = filterStr.toLowerCase().trim();
  3959. if (filterStr === 'none') {
  3960. return [];
  3961. }
  3962. var filterRegExp = /\s*([\w-]+)\(([^)]*)\)/g;
  3963. var result = [];
  3964. var match;
  3965. var prevLastIndex = 0;
  3966. while (match = filterRegExp.exec(filterStr)) {
  3967. if (match.index !== prevLastIndex) {
  3968. return [];
  3969. }
  3970. prevLastIndex = match.index + match[0].length;
  3971. if (supportedFilters.indexOf(match[1]) > -1) {
  3972. result.push({
  3973. name: match[1],
  3974. params: match[2].split(' ').map(function (p) {
  3975. return parseParam(p) || parseColor(p);
  3976. })
  3977. });
  3978. }
  3979. if (filterRegExp.lastIndex === filterStr.length) {
  3980. return result;
  3981. }
  3982. }
  3983. return [];
  3984. }
  3985. function numberToString(x) {
  3986. // scale(0.00000001) -> scale(0)
  3987. // return x.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
  3988. return x.toString();
  3989. }
  3990. /**
  3991. * parse string or number to CSSUnitValue(numeric)
  3992. *
  3993. * eg.
  3994. * * 0 -> CSSUnitValue(0)
  3995. * * '2' -> CSSUnitValue(2)
  3996. */
  3997. var parseNumber = memoize(function (string) {
  3998. if (typeof string === 'number') {
  3999. return getOrCreateUnitValue(string);
  4000. }
  4001. if (/^\s*[-+]?(\d*\.)?\d+\s*$/.test(string)) {
  4002. return getOrCreateUnitValue(Number(string));
  4003. } else {
  4004. return getOrCreateUnitValue(0);
  4005. }
  4006. });
  4007. /**
  4008. * separate string to array
  4009. * eg.
  4010. * * [0.5, 0.5] -> [CSSUnitValue, CSSUnitValue]
  4011. */
  4012. var parseNumberList = memoize(function (string) {
  4013. if (isString(string)) {
  4014. return string.split(' ').map(parseNumber);
  4015. } else {
  4016. return string.map(parseNumber);
  4017. }
  4018. });
  4019. function mergeNumbers(left, right) {
  4020. return [left, right, numberToString];
  4021. }
  4022. function clampedMergeNumbers(min, max) {
  4023. return function (left, right) {
  4024. return [left, right, function (x) {
  4025. return numberToString(clamp(x, min, max));
  4026. }];
  4027. };
  4028. }
  4029. function mergeNumberLists(left, right) {
  4030. if (left.length !== right.length) {
  4031. return;
  4032. }
  4033. return [left, right, function (numberList) {
  4034. return numberList;
  4035. }];
  4036. }
  4037. var internalParsePath = function internalParsePath(path) {
  4038. // empty path
  4039. if (path === '' || Array.isArray(path) && path.length === 0) {
  4040. return {
  4041. absolutePath: [],
  4042. hasArc: false,
  4043. segments: [],
  4044. polygons: [],
  4045. polylines: [],
  4046. curve: null,
  4047. totalLength: 0,
  4048. rect: {
  4049. x: 0,
  4050. y: 0,
  4051. width: 0,
  4052. height: 0
  4053. }
  4054. };
  4055. }
  4056. var absolutePath;
  4057. try {
  4058. absolutePath = normalizePath(path);
  4059. } catch (e) {
  4060. absolutePath = normalizePath('');
  4061. console.error("[g]: Invalid SVG Path definition: " + path);
  4062. }
  4063. var hasArc = hasArcOrBezier(absolutePath);
  4064. var _extractPolygons = extractPolygons(absolutePath),
  4065. polygons = _extractPolygons.polygons,
  4066. polylines = _extractPolygons.polylines;
  4067. // for later use
  4068. var segments = path2Segments(absolutePath);
  4069. // Only calculate bbox here since we don't need length now.
  4070. var _getPathBBox = getPathBBox(segments, 0),
  4071. x = _getPathBBox.x,
  4072. y = _getPathBBox.y,
  4073. width = _getPathBBox.width,
  4074. height = _getPathBBox.height;
  4075. return {
  4076. absolutePath: absolutePath,
  4077. hasArc: hasArc,
  4078. segments: segments,
  4079. polygons: polygons,
  4080. polylines: polylines,
  4081. // curve,
  4082. // Delay the calculation of length.
  4083. totalLength: 0,
  4084. rect: {
  4085. x: Number.isFinite(x) ? x : 0,
  4086. y: Number.isFinite(y) ? y : 0,
  4087. width: Number.isFinite(width) ? width : 0,
  4088. height: Number.isFinite(height) ? height : 0
  4089. }
  4090. };
  4091. };
  4092. var memoizedParsePath = memoize(internalParsePath);
  4093. function parsePath(path, object) {
  4094. var result = isString(path) ? memoizedParsePath(path) : internalParsePath(path);
  4095. if (object) {
  4096. object.parsedStyle.defX = result.rect.x;
  4097. object.parsedStyle.defY = result.rect.y;
  4098. }
  4099. return result;
  4100. }
  4101. function mergePaths(left, right, object) {
  4102. var curve1 = left.curve;
  4103. var curve2 = right.curve;
  4104. if (!curve1 || curve1.length === 0) {
  4105. // convert to curves to do morphing & picking later
  4106. // @see http://thednp.github.io/kute.js/svgCubicMorph.html
  4107. curve1 = path2Curve(left.absolutePath, false);
  4108. left.curve = curve1;
  4109. }
  4110. if (!curve2 || curve2.length === 0) {
  4111. curve2 = path2Curve(right.absolutePath, false);
  4112. right.curve = curve2;
  4113. }
  4114. var curves = [curve1, curve2];
  4115. if (curve1.length !== curve2.length) {
  4116. curves = equalizeSegments(curve1, curve2);
  4117. }
  4118. var curve0 = getDrawDirection(curves[0]) !== getDrawDirection(curves[1]) ? reverseCurve(curves[0]) : clonePath(curves[0]);
  4119. return [curve0, getRotatedCurve(curves[1], curve0), function (pathArray) {
  4120. // need converting to path string?
  4121. return pathArray;
  4122. }];
  4123. }
  4124. /**
  4125. * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/points
  4126. *
  4127. * @example
  4128. * points="100,10 250,150 200,110"
  4129. */
  4130. function parsePoints(pointsOrStr, object) {
  4131. var points;
  4132. if (isString(pointsOrStr)) {
  4133. points = pointsOrStr.split(' ').map(function (pointStr) {
  4134. var _pointStr$split = pointStr.split(','),
  4135. x = _pointStr$split[0],
  4136. y = _pointStr$split[1];
  4137. return [Number(x), Number(y)];
  4138. });
  4139. } else {
  4140. points = pointsOrStr;
  4141. }
  4142. var segments = [];
  4143. var tempLength = 0;
  4144. var segmentT;
  4145. var segmentL;
  4146. var totalLength = Polyline$1.length(points);
  4147. points.forEach(function (p, i) {
  4148. if (points[i + 1]) {
  4149. segmentT = [0, 0];
  4150. segmentT[0] = tempLength / totalLength;
  4151. segmentL = Line$1.length(p[0], p[1], points[i + 1][0], points[i + 1][1]);
  4152. tempLength += segmentL;
  4153. segmentT[1] = tempLength / totalLength;
  4154. segments.push(segmentT);
  4155. }
  4156. });
  4157. var minX = Math.min.apply(Math, points.map(function (point) {
  4158. return point[0];
  4159. }));
  4160. var minY = Math.min.apply(Math, points.map(function (point) {
  4161. return point[1];
  4162. }));
  4163. if (object) {
  4164. object.parsedStyle.defX = minX;
  4165. object.parsedStyle.defY = minY;
  4166. }
  4167. return {
  4168. points: points,
  4169. totalLength: totalLength,
  4170. segments: segments
  4171. };
  4172. }
  4173. function mergePoints(left, right) {
  4174. return [left.points, right.points, function (points) {
  4175. return points;
  4176. }];
  4177. }
  4178. var _ = null;
  4179. function cast(pattern) {
  4180. return function (contents) {
  4181. var i = 0;
  4182. return pattern.map(function (x) {
  4183. return x === _ ? contents[i++] : x;
  4184. });
  4185. };
  4186. }
  4187. function id(x) {
  4188. return x;
  4189. }
  4190. // type: [argTypes, convertTo3D, convertTo2D]
  4191. // In the argument types string, lowercase characters represent optional arguments
  4192. var transformFunctions = {
  4193. // @ts-ignore
  4194. matrix: ['NNNNNN', [_, _, 0, 0, _, _, 0, 0, 0, 0, 1, 0, _, _, 0, 1], id],
  4195. matrix3d: ['NNNNNNNNNNNNNNNN', id],
  4196. rotate: ['A'],
  4197. rotatex: ['A'],
  4198. rotatey: ['A'],
  4199. rotatez: ['A'],
  4200. rotate3d: ['NNNA'],
  4201. perspective: ['L'],
  4202. scale: ['Nn', cast([_, _, new CSSUnitValue(1)]), id],
  4203. scalex: ['N', cast([_, new CSSUnitValue(1), new CSSUnitValue(1)]), cast([_, new CSSUnitValue(1)])],
  4204. scaley: ['N', cast([new CSSUnitValue(1), _, new CSSUnitValue(1)]), cast([new CSSUnitValue(1), _])],
  4205. scalez: ['N', cast([new CSSUnitValue(1), new CSSUnitValue(1), _])],
  4206. scale3d: ['NNN', id],
  4207. skew: ['Aa', null, id],
  4208. skewx: ['A', null, cast([_, Odeg])],
  4209. skewy: ['A', null, cast([Odeg, _])],
  4210. translate: ['Tt', cast([_, _, Opx]), id],
  4211. translatex: ['T', cast([_, Opx, Opx]), cast([_, Opx])],
  4212. translatey: ['T', cast([Opx, _, Opx]), cast([Opx, _])],
  4213. translatez: ['L', cast([Opx, Opx, _])],
  4214. translate3d: ['TTL', id]
  4215. };
  4216. /**
  4217. * none
  4218. * scale(1) scale(1, 2)
  4219. * scaleX(1)
  4220. */
  4221. function parseTransform(string) {
  4222. string = (string || 'none').toLowerCase().trim();
  4223. if (string === 'none') {
  4224. return [];
  4225. }
  4226. var transformRegExp = /\s*(\w+)\(([^)]*)\)/g;
  4227. var result = [];
  4228. var match;
  4229. var prevLastIndex = 0;
  4230. while (match = transformRegExp.exec(string)) {
  4231. if (match.index !== prevLastIndex) {
  4232. return [];
  4233. }
  4234. prevLastIndex = match.index + match[0].length;
  4235. var functionName = match[1]; // scale
  4236. var functionData = transformFunctions[functionName]; // scale(1, 2)
  4237. if (!functionData) {
  4238. // invalid, eg. scale()
  4239. return [];
  4240. }
  4241. var args = match[2].split(','); // 1,2
  4242. var argTypes = functionData[0]; // Nn
  4243. if (argTypes.length < args.length) {
  4244. // scale(N, n)
  4245. return [];
  4246. }
  4247. var parsedArgs = [];
  4248. for (var i = 0; i < argTypes.length; i++) {
  4249. var arg = args[i];
  4250. var type = argTypes[i];
  4251. var parsedArg = void 0;
  4252. if (!arg) {
  4253. // @ts-ignore
  4254. parsedArg = {
  4255. a: Odeg,
  4256. n: parsedArgs[0],
  4257. t: Opx
  4258. }[type];
  4259. } else {
  4260. // @ts-ignore
  4261. parsedArg = {
  4262. A: function A(s) {
  4263. return s.trim() === '0' ? Odeg : parseAngle(s);
  4264. },
  4265. N: parseNumber,
  4266. T: parseLengthOrPercentage,
  4267. L: parseLength
  4268. }[type.toUpperCase()](arg);
  4269. }
  4270. if (parsedArg === undefined) {
  4271. return [];
  4272. }
  4273. parsedArgs.push(parsedArg);
  4274. }
  4275. result.push({
  4276. t: functionName,
  4277. d: parsedArgs
  4278. }); // { t: scale, d: [1, 2] }
  4279. if (transformRegExp.lastIndex === string.length) {
  4280. return result;
  4281. }
  4282. }
  4283. return [];
  4284. }
  4285. function convertItemToMatrix(item) {
  4286. var x;
  4287. var y;
  4288. var z;
  4289. var angle;
  4290. switch (item.t) {
  4291. case 'rotatex':
  4292. angle = deg2rad(convertAngleUnit(item.d[0]));
  4293. 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];
  4294. case 'rotatey':
  4295. angle = deg2rad(convertAngleUnit(item.d[0]));
  4296. 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];
  4297. case 'rotate':
  4298. case 'rotatez':
  4299. angle = deg2rad(convertAngleUnit(item.d[0]));
  4300. 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];
  4301. case 'rotate3d':
  4302. x = item.d[0].value;
  4303. y = item.d[1].value;
  4304. z = item.d[2].value;
  4305. angle = deg2rad(convertAngleUnit(item.d[3]));
  4306. var sqrLength = x * x + y * y + z * z;
  4307. if (sqrLength === 0) {
  4308. x = 1;
  4309. y = 0;
  4310. z = 0;
  4311. } else if (sqrLength !== 1) {
  4312. var length = Math.sqrt(sqrLength);
  4313. x /= length;
  4314. y /= length;
  4315. z /= length;
  4316. }
  4317. var s = Math.sin(angle / 2);
  4318. var sc = s * Math.cos(angle / 2);
  4319. var sq = s * s;
  4320. 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];
  4321. case 'scale':
  4322. return [item.d[0].value, 0, 0, 0, 0, item.d[1].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4323. case 'scalex':
  4324. return [item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4325. case 'scaley':
  4326. return [1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4327. case 'scalez':
  4328. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1];
  4329. case 'scale3d':
  4330. 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];
  4331. case 'skew':
  4332. var xAngle = deg2rad(convertAngleUnit(item.d[0]));
  4333. var yAngle = deg2rad(convertAngleUnit(item.d[1]));
  4334. return [1, Math.tan(yAngle), 0, 0, Math.tan(xAngle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4335. case 'skewx':
  4336. angle = deg2rad(convertAngleUnit(item.d[0]));
  4337. return [1, 0, 0, 0, Math.tan(angle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4338. case 'skewy':
  4339. angle = deg2rad(convertAngleUnit(item.d[0]));
  4340. return [1, Math.tan(angle), 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4341. case 'translate':
  4342. // TODO: pass target
  4343. x = convertPercentUnit(item.d[0], 0, null) || 0;
  4344. y = convertPercentUnit(item.d[1], 0, null) || 0;
  4345. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1];
  4346. case 'translatex':
  4347. x = convertPercentUnit(item.d[0], 0, null) || 0;
  4348. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1];
  4349. case 'translatey':
  4350. y = convertPercentUnit(item.d[0], 0, null) || 0;
  4351. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, y, 0, 1];
  4352. case 'translatez':
  4353. z = convertPercentUnit(item.d[0], 0, null) || 0;
  4354. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, z, 1];
  4355. case 'translate3d':
  4356. x = convertPercentUnit(item.d[0], 0, null) || 0;
  4357. y = convertPercentUnit(item.d[1], 0, null) || 0;
  4358. z = convertPercentUnit(item.d[2], 0, null) || 0;
  4359. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
  4360. case 'perspective':
  4361. var t = convertPercentUnit(item.d[0], 0, null) || 0;
  4362. var p = t ? -1 / t : 0;
  4363. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, p, 0, 0, 0, 1];
  4364. case 'matrix':
  4365. 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];
  4366. case 'matrix3d':
  4367. return item.d.map(function (d) {
  4368. return d.value;
  4369. });
  4370. }
  4371. }
  4372. function multiplyMatrices(a, b) {
  4373. 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]];
  4374. }
  4375. function convertToMatrix(transformList) {
  4376. if (transformList.length === 0) {
  4377. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  4378. }
  4379. return transformList.map(convertItemToMatrix).reduce(multiplyMatrices);
  4380. }
  4381. function makeMatrixDecomposition(transformList) {
  4382. var translate = [0, 0, 0];
  4383. var scale = [1, 1, 1];
  4384. var skew = [0, 0, 0];
  4385. var perspective = [0, 0, 0, 1];
  4386. var quaternion = [0, 0, 0, 1];
  4387. // @ts-ignore
  4388. decomposeMat4(convertToMatrix(transformList), translate, scale, skew, perspective, quaternion);
  4389. return [[translate, scale, skew, quaternion, perspective]];
  4390. }
  4391. var composeMatrix = function () {
  4392. function multiply(a, b) {
  4393. var result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
  4394. for (var i = 0; i < 4; i++) {
  4395. for (var j = 0; j < 4; j++) {
  4396. for (var k = 0; k < 4; k++) {
  4397. result[i][j] += b[i][k] * a[k][j];
  4398. }
  4399. }
  4400. }
  4401. return result;
  4402. }
  4403. function is2D(m) {
  4404. 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;
  4405. }
  4406. function composeMatrix(translate, scale, skew, quat, perspective) {
  4407. var matrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
  4408. for (var i = 0; i < 4; i++) {
  4409. matrix[i][3] = perspective[i];
  4410. }
  4411. for (var _i = 0; _i < 3; _i++) {
  4412. for (var j = 0; j < 3; j++) {
  4413. matrix[3][_i] += translate[j] * matrix[j][_i];
  4414. }
  4415. }
  4416. var x = quat[0],
  4417. y = quat[1],
  4418. z = quat[2],
  4419. w = quat[3];
  4420. var rotMatrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
  4421. rotMatrix[0][0] = 1 - 2 * (y * y + z * z);
  4422. rotMatrix[0][1] = 2 * (x * y - z * w);
  4423. rotMatrix[0][2] = 2 * (x * z + y * w);
  4424. rotMatrix[1][0] = 2 * (x * y + z * w);
  4425. rotMatrix[1][1] = 1 - 2 * (x * x + z * z);
  4426. rotMatrix[1][2] = 2 * (y * z - x * w);
  4427. rotMatrix[2][0] = 2 * (x * z - y * w);
  4428. rotMatrix[2][1] = 2 * (y * z + x * w);
  4429. rotMatrix[2][2] = 1 - 2 * (x * x + y * y);
  4430. matrix = multiply(matrix, rotMatrix);
  4431. var temp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
  4432. if (skew[2]) {
  4433. temp[2][1] = skew[2];
  4434. matrix = multiply(matrix, temp);
  4435. }
  4436. if (skew[1]) {
  4437. temp[2][1] = 0;
  4438. temp[2][0] = skew[0];
  4439. matrix = multiply(matrix, temp);
  4440. }
  4441. if (skew[0]) {
  4442. temp[2][0] = 0;
  4443. temp[1][0] = skew[0];
  4444. matrix = multiply(matrix, temp);
  4445. }
  4446. for (var _i2 = 0; _i2 < 3; _i2++) {
  4447. for (var _j = 0; _j < 3; _j++) {
  4448. matrix[_i2][_j] *= scale[_i2];
  4449. }
  4450. }
  4451. if (is2D(matrix)) {
  4452. return [matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1], matrix[3][0], matrix[3][1]];
  4453. }
  4454. return matrix[0].concat(matrix[1], matrix[2], matrix[3]);
  4455. }
  4456. return composeMatrix;
  4457. }();
  4458. function numberToLongString(x) {
  4459. return x.toFixed(6).replace('.000000', '');
  4460. }
  4461. function mergeMatrices(left, right) {
  4462. var leftArgs;
  4463. var rightArgs;
  4464. // @ts-ignore
  4465. if (left.decompositionPair !== right) {
  4466. // @ts-ignore
  4467. left.decompositionPair = right;
  4468. // @ts-ignore
  4469. leftArgs = makeMatrixDecomposition(left);
  4470. }
  4471. // @ts-ignore
  4472. if (right.decompositionPair !== left) {
  4473. // @ts-ignore
  4474. right.decompositionPair = left;
  4475. // @ts-ignore
  4476. rightArgs = makeMatrixDecomposition(right);
  4477. }
  4478. if (leftArgs[0] === null || rightArgs[0] === null) return [
  4479. // @ts-ignore
  4480. [false],
  4481. // @ts-ignore
  4482. [true],
  4483. // @ts-ignore
  4484. function (x) {
  4485. return x ? right[0].d : left[0].d;
  4486. }];
  4487. leftArgs[0].push(0);
  4488. rightArgs[0].push(1);
  4489. return [leftArgs, rightArgs,
  4490. // @ts-ignore
  4491. function (list) {
  4492. // @ts-ignore
  4493. var q = quat(leftArgs[0][3], rightArgs[0][3], list[5]);
  4494. var mat = composeMatrix(list[0], list[1], list[2], q, list[4]);
  4495. var stringifiedArgs = mat.map(numberToLongString).join(',');
  4496. return stringifiedArgs;
  4497. }];
  4498. }
  4499. function dot(v1, v2) {
  4500. var result = 0;
  4501. for (var i = 0; i < v1.length; i++) {
  4502. result += v1[i] * v2[i];
  4503. }
  4504. return result;
  4505. }
  4506. function quat(fromQ, toQ, f) {
  4507. var product = dot(fromQ, toQ);
  4508. product = clamp(product, -1.0, 1.0);
  4509. var quat = [];
  4510. if (product === 1.0) {
  4511. quat = fromQ;
  4512. } else {
  4513. var theta = Math.acos(product);
  4514. var w = Math.sin(f * theta) * 1 / Math.sqrt(1 - product * product);
  4515. for (var i = 0; i < 4; i++) {
  4516. quat.push(fromQ[i] * (Math.cos(f * theta) - product * w) + toQ[i] * w);
  4517. }
  4518. }
  4519. return quat;
  4520. }
  4521. // scalex/y/z -> scale
  4522. function typeTo2D(type) {
  4523. return type.replace(/[xy]/, '');
  4524. }
  4525. // scalex/y/z -> scale3d
  4526. function typeTo3D(type) {
  4527. return type.replace(/(x|y|z|3d)?$/, '3d');
  4528. }
  4529. var isMatrixOrPerspective = function isMatrixOrPerspective(lt, rt) {
  4530. return lt === 'perspective' && rt === 'perspective' || (lt === 'matrix' || lt === 'matrix3d') && (rt === 'matrix' || rt === 'matrix3d');
  4531. };
  4532. function mergeTransforms(left, right, target) {
  4533. var flipResults = false;
  4534. // padding empty transform, eg. merge 'scale(10)' with 'none' -> scale(1)
  4535. if (!left.length || !right.length) {
  4536. if (!left.length) {
  4537. flipResults = true;
  4538. left = right;
  4539. right = [];
  4540. }
  4541. var _loop = function _loop() {
  4542. var _left$i = left[i],
  4543. type = _left$i.t,
  4544. args = _left$i.d;
  4545. // none -> scale(1)/translateX(0)
  4546. var defaultValue = type.substring(0, 5) === 'scale' ? 1 : 0;
  4547. right.push({
  4548. t: type,
  4549. d: args.map(function (arg) {
  4550. if (typeof arg === 'number') {
  4551. return getOrCreateUnitValue(defaultValue);
  4552. }
  4553. return getOrCreateUnitValue(defaultValue, arg.unit);
  4554. // {
  4555. // unit: arg.unit,
  4556. // value: defaultValue,
  4557. // };
  4558. })
  4559. });
  4560. };
  4561. for (var i = 0; i < left.length; i++) {
  4562. _loop();
  4563. }
  4564. }
  4565. var leftResult = [];
  4566. var rightResult = [];
  4567. var types = [];
  4568. // merge matrix() with matrix3d()
  4569. if (left.length !== right.length) {
  4570. var merged = mergeMatrices(left, right);
  4571. // @ts-ignore
  4572. leftResult = [merged[0]];
  4573. // @ts-ignore
  4574. rightResult = [merged[1]];
  4575. types = [['matrix', [merged[2]]]];
  4576. } else {
  4577. for (var _i3 = 0; _i3 < left.length; _i3++) {
  4578. var leftType = left[_i3].t;
  4579. var rightType = right[_i3].t;
  4580. var leftArgs = left[_i3].d;
  4581. var rightArgs = right[_i3].d;
  4582. var leftFunctionData = transformFunctions[leftType];
  4583. var rightFunctionData = transformFunctions[rightType];
  4584. var type = void 0;
  4585. if (isMatrixOrPerspective(leftType, rightType)) {
  4586. var _merged = mergeMatrices([left[_i3]], [right[_i3]]);
  4587. // @ts-ignore
  4588. leftResult.push(_merged[0]);
  4589. // @ts-ignore
  4590. rightResult.push(_merged[1]);
  4591. types.push(['matrix', [_merged[2]]]);
  4592. continue;
  4593. } else if (leftType === rightType) {
  4594. type = leftType;
  4595. } else if (leftFunctionData[2] && rightFunctionData[2] && typeTo2D(leftType) === typeTo2D(rightType)) {
  4596. type = typeTo2D(leftType);
  4597. // @ts-ignore
  4598. leftArgs = leftFunctionData[2](leftArgs);
  4599. // @ts-ignore
  4600. rightArgs = rightFunctionData[2](rightArgs);
  4601. } else if (leftFunctionData[1] && rightFunctionData[1] && typeTo3D(leftType) === typeTo3D(rightType)) {
  4602. type = typeTo3D(leftType);
  4603. // @ts-ignore
  4604. leftArgs = leftFunctionData[1](leftArgs);
  4605. // @ts-ignore
  4606. rightArgs = rightFunctionData[1](rightArgs);
  4607. } else {
  4608. var _merged2 = mergeMatrices(left, right);
  4609. // @ts-ignore
  4610. leftResult = [_merged2[0]];
  4611. // @ts-ignore
  4612. rightResult = [_merged2[1]];
  4613. types = [['matrix', [_merged2[2]]]];
  4614. break;
  4615. }
  4616. var leftArgsCopy = [];
  4617. var rightArgsCopy = [];
  4618. var stringConversions = [];
  4619. for (var j = 0; j < leftArgs.length; j++) {
  4620. // const merge = leftArgs[j].unit === UnitType.kNumber ? mergeDimensions : mergeDimensions;
  4621. var _merged3 = mergeDimensions(leftArgs[j], rightArgs[j], target, false, j);
  4622. leftArgsCopy[j] = _merged3[0];
  4623. rightArgsCopy[j] = _merged3[1];
  4624. stringConversions.push(_merged3[2]);
  4625. }
  4626. leftResult.push(leftArgsCopy);
  4627. rightResult.push(rightArgsCopy);
  4628. types.push([type, stringConversions]);
  4629. }
  4630. }
  4631. if (flipResults) {
  4632. var tmp = leftResult;
  4633. leftResult = rightResult;
  4634. rightResult = tmp;
  4635. }
  4636. return [leftResult, rightResult, function (list) {
  4637. return list.map(function (args, i) {
  4638. var stringifiedArgs = args.map(function (arg, j) {
  4639. return types[i][1][j](arg);
  4640. }).join(',');
  4641. if (types[i][0] === 'matrix' && stringifiedArgs.split(',').length === 16) {
  4642. types[i][0] = 'matrix3d';
  4643. }
  4644. if (types[i][0] === 'matrix3d' && stringifiedArgs.split(',').length === 6) {
  4645. types[i][0] = 'matrix';
  4646. }
  4647. return types[i][0] + '(' + stringifiedArgs + ')';
  4648. }).join(' ');
  4649. }];
  4650. }
  4651. /**
  4652. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
  4653. * eg. 'center' 'top left' '50px 50px'
  4654. */
  4655. var parseTransformOrigin = memoize(function (value) {
  4656. if (isString(value)) {
  4657. if (value === 'text-anchor') {
  4658. return [getOrCreateUnitValue(0, 'px'), getOrCreateUnitValue(0, 'px')];
  4659. }
  4660. var values = value.split(' ');
  4661. if (values.length === 1) {
  4662. if (values[0] === 'top' || values[0] === 'bottom') {
  4663. // 'top' -> 'center top'
  4664. values[1] = values[0];
  4665. values[0] = 'center';
  4666. } else {
  4667. // '50px' -> '50px center'
  4668. values[1] = 'center';
  4669. }
  4670. }
  4671. if (values.length !== 2) {
  4672. return null;
  4673. }
  4674. // eg. center bottom
  4675. return [parseLengthOrPercentage(convertKeyword2Percent(values[0])), parseLengthOrPercentage(convertKeyword2Percent(values[1]))];
  4676. } else {
  4677. return [getOrCreateUnitValue(value[0] || 0, 'px'), getOrCreateUnitValue(value[1] || 0, 'px')];
  4678. }
  4679. });
  4680. function convertKeyword2Percent(keyword) {
  4681. if (keyword === 'center') {
  4682. return '50%';
  4683. } else if (keyword === 'left' || keyword === 'top') {
  4684. return '0';
  4685. } else if (keyword === 'right' || keyword === 'bottom') {
  4686. return '100%';
  4687. }
  4688. return keyword;
  4689. }
  4690. var CSSPropertyAngle = /*#__PURE__*/function () {
  4691. function CSSPropertyAngle() {
  4692. this.parser = parseAngle;
  4693. this.parserWithCSSDisabled = null;
  4694. this.mixer = mergeNumbers;
  4695. }
  4696. var _proto = CSSPropertyAngle.prototype;
  4697. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  4698. return convertAngleUnit(parsed);
  4699. };
  4700. return CSSPropertyAngle;
  4701. }();
  4702. /**
  4703. * clipPath / textPath / offsetPath
  4704. */
  4705. var CSSPropertyClipPath = /*#__PURE__*/function () {
  4706. function CSSPropertyClipPath() {}
  4707. var _proto = CSSPropertyClipPath.prototype;
  4708. _proto.calculator = function calculator(name, oldPath, newPath, object) {
  4709. // unset
  4710. if (newPath instanceof CSSKeywordValue) {
  4711. newPath = null;
  4712. }
  4713. runtime.sceneGraphService.updateDisplayObjectDependency(name, oldPath, newPath, object);
  4714. if (name === 'clipPath') {
  4715. // should affect children
  4716. object.forEach(function (leaf) {
  4717. if (leaf.childNodes.length === 0) {
  4718. runtime.sceneGraphService.dirtifyToRoot(leaf);
  4719. }
  4720. });
  4721. }
  4722. return newPath;
  4723. };
  4724. return CSSPropertyClipPath;
  4725. }();
  4726. var CSSPropertyColor = /*#__PURE__*/function () {
  4727. function CSSPropertyColor() {
  4728. this.parser = parseColor;
  4729. this.parserWithCSSDisabled = parseColor;
  4730. this.mixer = mergeColors;
  4731. }
  4732. var _proto = CSSPropertyColor.prototype;
  4733. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  4734. if (parsed instanceof CSSKeywordValue) {
  4735. // 'unset' 'none'
  4736. return parsed.value === 'none' ? noneColor : transparentColor;
  4737. }
  4738. return parsed;
  4739. };
  4740. return CSSPropertyColor;
  4741. }();
  4742. var CSSPropertyFilter = /*#__PURE__*/function () {
  4743. function CSSPropertyFilter() {
  4744. this.parser = parseFilter;
  4745. }
  4746. var _proto = CSSPropertyFilter.prototype;
  4747. _proto.calculator = function calculator(name, oldParsed, parsed) {
  4748. // unset or none
  4749. if (parsed instanceof CSSKeywordValue) {
  4750. return [];
  4751. }
  4752. return parsed;
  4753. };
  4754. return CSSPropertyFilter;
  4755. }();
  4756. function getFontSize(object) {
  4757. var fontSize = object.parsedStyle.fontSize;
  4758. return isNil(fontSize) ? null : fontSize;
  4759. }
  4760. /**
  4761. * <length> & <percentage>
  4762. */
  4763. var CSSPropertyLengthOrPercentage = /*#__PURE__*/function () {
  4764. function CSSPropertyLengthOrPercentage() {
  4765. this.parser = parseLengthOrPercentage;
  4766. this.parserWithCSSDisabled = null;
  4767. this.mixer = mergeNumbers;
  4768. }
  4769. var _proto = CSSPropertyLengthOrPercentage.prototype;
  4770. /**
  4771. * according to parent's bounds
  4772. *
  4773. * @example
  4774. * CSS.percent(50) -> CSS.px(0.5 * parent.width)
  4775. */
  4776. _proto.calculator = function calculator(name, oldParsed, computed, object, registry) {
  4777. if (isNumber(computed)) {
  4778. return computed;
  4779. }
  4780. if (CSSUnitValue.isRelativeUnit(computed.unit)) {
  4781. if (computed.unit === UnitType.kPercentage) {
  4782. // TODO: merge dimensions
  4783. return 0;
  4784. } else if (computed.unit === UnitType.kEms) {
  4785. if (object.parentNode) {
  4786. var fontSize = getFontSize(object.parentNode);
  4787. if (fontSize) {
  4788. fontSize *= computed.value;
  4789. return fontSize;
  4790. } else {
  4791. registry.addUnresolveProperty(object, name);
  4792. }
  4793. } else {
  4794. registry.addUnresolveProperty(object, name);
  4795. }
  4796. return 0;
  4797. } else if (computed.unit === UnitType.kRems) {
  4798. var _object$ownerDocument;
  4799. if (object === null || object === void 0 ? void 0 : (_object$ownerDocument = object.ownerDocument) === null || _object$ownerDocument === void 0 ? void 0 : _object$ownerDocument.documentElement) {
  4800. var _fontSize = getFontSize(object.ownerDocument.documentElement);
  4801. if (_fontSize) {
  4802. _fontSize *= computed.value;
  4803. return _fontSize;
  4804. } else {
  4805. registry.addUnresolveProperty(object, name);
  4806. }
  4807. } else {
  4808. registry.addUnresolveProperty(object, name);
  4809. }
  4810. return 0;
  4811. }
  4812. } else {
  4813. // remove listener if exists
  4814. // registry.unregisterParentGeometryBoundsChangedHandler(object, name);
  4815. // return absolute value
  4816. return computed.value;
  4817. }
  4818. };
  4819. return CSSPropertyLengthOrPercentage;
  4820. }();
  4821. /**
  4822. * format to Tuple2<CSSUnitValue>
  4823. *
  4824. * @example
  4825. * rect.style.lineDash = 10;
  4826. * rect.style.lineDash = [10, 10];
  4827. * rect.style.lineDash = '10 10';
  4828. */
  4829. var CSSPropertyLengthOrPercentage12 = /*#__PURE__*/function () {
  4830. function CSSPropertyLengthOrPercentage12() {
  4831. this.mixer = mergeNumberLists;
  4832. }
  4833. var _proto = CSSPropertyLengthOrPercentage12.prototype;
  4834. _proto.parser = function parser(radius) {
  4835. var parsed = parseDimensionArray(isNumber(radius) ? [radius] : radius);
  4836. var formatted;
  4837. if (parsed.length === 1) {
  4838. formatted = [parsed[0], parsed[0]];
  4839. } else {
  4840. formatted = [parsed[0], parsed[1]];
  4841. }
  4842. return formatted;
  4843. };
  4844. _proto.calculator = function calculator(name, oldParsed, computed) {
  4845. return computed.map(function (c) {
  4846. return c.value;
  4847. });
  4848. };
  4849. return CSSPropertyLengthOrPercentage12;
  4850. }();
  4851. /**
  4852. * used in rounded rect
  4853. *
  4854. * @example
  4855. * rect.style.radius = 10;
  4856. * rect.style.radius = '10 10';
  4857. * rect.style.radius = '10 10 10 10';
  4858. */
  4859. var CSSPropertyLengthOrPercentage14 = /*#__PURE__*/function () {
  4860. function CSSPropertyLengthOrPercentage14() {
  4861. this.mixer = mergeNumberLists;
  4862. }
  4863. var _proto = CSSPropertyLengthOrPercentage14.prototype;
  4864. _proto.parser = function parser(radius) {
  4865. var parsed = parseDimensionArray(isNumber(radius) ? [radius] : radius);
  4866. var formatted;
  4867. // format to Tuple<CSSUnitValue>
  4868. if (parsed.length === 1) {
  4869. formatted = [parsed[0], parsed[0], parsed[0], parsed[0]];
  4870. } else if (parsed.length === 2) {
  4871. formatted = [parsed[0], parsed[1], parsed[0], parsed[1]];
  4872. } else if (parsed.length === 3) {
  4873. formatted = [parsed[0], parsed[1], parsed[2], parsed[1]];
  4874. } else {
  4875. formatted = [parsed[0], parsed[1], parsed[2], parsed[3]];
  4876. }
  4877. return formatted;
  4878. };
  4879. _proto.calculator = function calculator(name, oldParsed, computed) {
  4880. return computed.map(function (c) {
  4881. return c.value;
  4882. });
  4883. };
  4884. return CSSPropertyLengthOrPercentage14;
  4885. }();
  4886. /**
  4887. * local position
  4888. */
  4889. var CSSPropertyLocalPosition = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
  4890. _inheritsLoose(CSSPropertyLocalPosition, _CSSPropertyLengthOrP);
  4891. function CSSPropertyLocalPosition() {
  4892. return _CSSPropertyLengthOrP.apply(this, arguments) || this;
  4893. }
  4894. var _proto = CSSPropertyLocalPosition.prototype;
  4895. /**
  4896. * update local position
  4897. */
  4898. _proto.postProcessor = function postProcessor(object, attributes) {
  4899. var x;
  4900. var y;
  4901. var z;
  4902. switch (object.nodeName) {
  4903. case Shape.CIRCLE:
  4904. case Shape.ELLIPSE:
  4905. var _object$parsedStyle = object.parsedStyle,
  4906. cx = _object$parsedStyle.cx,
  4907. cy = _object$parsedStyle.cy,
  4908. cz = _object$parsedStyle.cz;
  4909. if (!isNil(cx)) {
  4910. x = cx;
  4911. }
  4912. if (!isNil(cy)) {
  4913. y = cy;
  4914. }
  4915. if (!isNil(cz)) {
  4916. z = cz;
  4917. }
  4918. break;
  4919. case Shape.LINE:
  4920. var _object$parsedStyle2 = object.parsedStyle,
  4921. x1 = _object$parsedStyle2.x1,
  4922. x2 = _object$parsedStyle2.x2,
  4923. y1 = _object$parsedStyle2.y1,
  4924. y2 = _object$parsedStyle2.y2;
  4925. var minX = Math.min(x1, x2);
  4926. var minY = Math.min(y1, y2);
  4927. x = minX;
  4928. y = minY;
  4929. z = 0;
  4930. break;
  4931. case Shape.RECT:
  4932. case Shape.IMAGE:
  4933. case Shape.GROUP:
  4934. case Shape.HTML:
  4935. case Shape.TEXT:
  4936. case Shape.MESH:
  4937. if (!isNil(object.parsedStyle.x)) {
  4938. x = object.parsedStyle.x;
  4939. }
  4940. if (!isNil(object.parsedStyle.y)) {
  4941. y = object.parsedStyle.y;
  4942. }
  4943. if (!isNil(object.parsedStyle.z)) {
  4944. z = object.parsedStyle.z;
  4945. }
  4946. break;
  4947. }
  4948. if (object.nodeName !== Shape.PATH && object.nodeName !== Shape.POLYLINE && object.nodeName !== Shape.POLYGON) {
  4949. object.parsedStyle.defX = x || 0;
  4950. object.parsedStyle.defY = y || 0;
  4951. }
  4952. var needResetLocalPosition = !isNil(x) || !isNil(y) || !isNil(z);
  4953. // only if `transform` won't be processed later
  4954. if (needResetLocalPosition && attributes.indexOf('transform') === -1) {
  4955. // account for current transform if needed
  4956. var transform = object.parsedStyle.transform;
  4957. if (transform && transform.length) {
  4958. parsedTransformToMat4(transform, object);
  4959. } else {
  4960. var _object$getLocalPosit = object.getLocalPosition(),
  4961. ox = _object$getLocalPosit[0],
  4962. oy = _object$getLocalPosit[1],
  4963. oz = _object$getLocalPosit[2];
  4964. object.setLocalPosition(isNil(x) ? ox : x, isNil(y) ? oy : y, isNil(z) ? oz : z);
  4965. }
  4966. }
  4967. };
  4968. return CSSPropertyLocalPosition;
  4969. }(CSSPropertyLengthOrPercentage);
  4970. var CSSPropertyMarker = /*#__PURE__*/function () {
  4971. function CSSPropertyMarker() {}
  4972. var _proto = CSSPropertyMarker.prototype;
  4973. _proto.calculator = function calculator(name, oldMarker, newMarker, object) {
  4974. var _newMarker;
  4975. // unset
  4976. if (newMarker instanceof CSSKeywordValue) {
  4977. newMarker = null;
  4978. }
  4979. var cloned = (_newMarker = newMarker) === null || _newMarker === void 0 ? void 0 : _newMarker.cloneNode(true);
  4980. if (cloned) {
  4981. // FIXME: SVG should not inherit parent's style, add a flag here
  4982. cloned.style.isMarker = true;
  4983. }
  4984. return cloned;
  4985. };
  4986. return CSSPropertyMarker;
  4987. }();
  4988. var CSSPropertyNumber = /*#__PURE__*/function () {
  4989. function CSSPropertyNumber() {
  4990. this.mixer = mergeNumbers;
  4991. this.parser = parseNumber;
  4992. this.parserWithCSSDisabled = null;
  4993. }
  4994. var _proto = CSSPropertyNumber.prototype;
  4995. _proto.calculator = function calculator(name, oldParsed, computed) {
  4996. return computed.value;
  4997. };
  4998. return CSSPropertyNumber;
  4999. }();
  5000. var CSSPropertyOffsetDistance = /*#__PURE__*/function () {
  5001. function CSSPropertyOffsetDistance() {
  5002. this.parser = parseNumber;
  5003. this.parserWithCSSDisabled = null;
  5004. this.mixer = clampedMergeNumbers(0, 1);
  5005. }
  5006. var _proto = CSSPropertyOffsetDistance.prototype;
  5007. _proto.calculator = function calculator(name, oldParsed, computed) {
  5008. return computed.value;
  5009. };
  5010. _proto.postProcessor = function postProcessor(object) {
  5011. var _object$parsedStyle = object.parsedStyle,
  5012. offsetPath = _object$parsedStyle.offsetPath,
  5013. offsetDistance = _object$parsedStyle.offsetDistance;
  5014. if (!offsetPath) {
  5015. return;
  5016. }
  5017. var nodeName = offsetPath.nodeName;
  5018. if (nodeName === Shape.LINE || nodeName === Shape.PATH || nodeName === Shape.POLYLINE) {
  5019. // set position in world space
  5020. var point = offsetPath.getPoint(offsetDistance);
  5021. if (point) {
  5022. object.parsedStyle.defX = point.x;
  5023. object.parsedStyle.defY = point.y;
  5024. object.setLocalPosition(point.x, point.y);
  5025. }
  5026. }
  5027. };
  5028. return CSSPropertyOffsetDistance;
  5029. }();
  5030. /**
  5031. * opacity
  5032. */
  5033. var CSSPropertyOpacity = /*#__PURE__*/function () {
  5034. function CSSPropertyOpacity() {
  5035. this.parser = parseNumber;
  5036. this.parserWithCSSDisabled = null;
  5037. this.mixer = clampedMergeNumbers(0, 1);
  5038. }
  5039. var _proto = CSSPropertyOpacity.prototype;
  5040. _proto.calculator = function calculator(name, oldParsed, computed) {
  5041. return computed.value;
  5042. };
  5043. return CSSPropertyOpacity;
  5044. }();
  5045. /**
  5046. * Axis-Aligned Bounding Box
  5047. * 为了便于后续 Frustum Culling,通过查找表定义 p-vertex 和 n-vertex
  5048. * @see https://github.com/antvis/GWebGPUEngine/issues/3
  5049. */
  5050. var AABB = /*#__PURE__*/function () {
  5051. function AABB() {
  5052. this.center = [0, 0, 0];
  5053. this.halfExtents = [0, 0, 0];
  5054. this.min = [0, 0, 0];
  5055. this.max = [0, 0, 0];
  5056. }
  5057. AABB.isEmpty = function isEmpty(aabb) {
  5058. return !aabb || aabb.halfExtents[0] === 0 && aabb.halfExtents[1] === 0 && aabb.halfExtents[2] === 0;
  5059. };
  5060. var _proto = AABB.prototype;
  5061. // center: vec3 = vec3.create();
  5062. // halfExtents: vec3 = vec3.create();
  5063. // min: vec3 = vec3.create();
  5064. // max: vec3 = vec3.create();
  5065. _proto.update = function update(center, halfExtents) {
  5066. copyVec3(this.center, center);
  5067. copyVec3(this.halfExtents, halfExtents);
  5068. subVec3(this.min, this.center, this.halfExtents);
  5069. addVec3(this.max, this.center, this.halfExtents);
  5070. // vec3.copy(this.center, center);
  5071. // vec3.copy(this.halfExtents, halfExtents);
  5072. // vec3.sub(this.min, this.center, this.halfExtents);
  5073. // vec3.add(this.max, this.center, this.halfExtents);
  5074. };
  5075. _proto.setMinMax = function setMinMax(min, max) {
  5076. // vec3.add(this.center, max, min);
  5077. // vec3.scale(this.center, this.center, 0.5);
  5078. // vec3.sub(this.halfExtents, max, min);
  5079. // vec3.scale(this.halfExtents, this.halfExtents, 0.5);
  5080. // vec3.copy(this.min, min);
  5081. // vec3.copy(this.max, max);
  5082. addVec3(this.center, max, min);
  5083. scaleVec3(this.center, this.center, 0.5);
  5084. subVec3(this.halfExtents, max, min);
  5085. scaleVec3(this.halfExtents, this.halfExtents, 0.5);
  5086. copyVec3(this.min, min);
  5087. copyVec3(this.max, max);
  5088. };
  5089. _proto.getMin = function getMin() {
  5090. return this.min;
  5091. };
  5092. _proto.getMax = function getMax() {
  5093. return this.max;
  5094. };
  5095. _proto.add = function add(aabb) {
  5096. if (AABB.isEmpty(aabb)) {
  5097. return;
  5098. }
  5099. if (AABB.isEmpty(this)) {
  5100. this.setMinMax(aabb.getMin(), aabb.getMax());
  5101. return;
  5102. }
  5103. var tc = this.center;
  5104. var tcx = tc[0];
  5105. var tcy = tc[1];
  5106. var tcz = tc[2];
  5107. var th = this.halfExtents;
  5108. var thx = th[0];
  5109. var thy = th[1];
  5110. var thz = th[2];
  5111. var tminx = tcx - thx;
  5112. var tmaxx = tcx + thx;
  5113. var tminy = tcy - thy;
  5114. var tmaxy = tcy + thy;
  5115. var tminz = tcz - thz;
  5116. var tmaxz = tcz + thz;
  5117. var oc = aabb.center;
  5118. var ocx = oc[0];
  5119. var ocy = oc[1];
  5120. var ocz = oc[2];
  5121. var oh = aabb.halfExtents;
  5122. var ohx = oh[0];
  5123. var ohy = oh[1];
  5124. var ohz = oh[2];
  5125. var ominx = ocx - ohx;
  5126. var omaxx = ocx + ohx;
  5127. var ominy = ocy - ohy;
  5128. var omaxy = ocy + ohy;
  5129. var ominz = ocz - ohz;
  5130. var omaxz = ocz + ohz;
  5131. if (ominx < tminx) {
  5132. tminx = ominx;
  5133. }
  5134. if (omaxx > tmaxx) {
  5135. tmaxx = omaxx;
  5136. }
  5137. if (ominy < tminy) {
  5138. tminy = ominy;
  5139. }
  5140. if (omaxy > tmaxy) {
  5141. tmaxy = omaxy;
  5142. }
  5143. if (ominz < tminz) {
  5144. tminz = ominz;
  5145. }
  5146. if (omaxz > tmaxz) {
  5147. tmaxz = omaxz;
  5148. }
  5149. tc[0] = (tminx + tmaxx) * 0.5;
  5150. tc[1] = (tminy + tmaxy) * 0.5;
  5151. tc[2] = (tminz + tmaxz) * 0.5;
  5152. th[0] = (tmaxx - tminx) * 0.5;
  5153. th[1] = (tmaxy - tminy) * 0.5;
  5154. th[2] = (tmaxz - tminz) * 0.5;
  5155. this.min[0] = tminx;
  5156. this.min[1] = tminy;
  5157. this.min[2] = tminz;
  5158. this.max[0] = tmaxx;
  5159. this.max[1] = tmaxy;
  5160. this.max[2] = tmaxz;
  5161. };
  5162. _proto.setFromTransformedAABB = function setFromTransformedAABB(aabb, m) {
  5163. var bc = this.center;
  5164. var br = this.halfExtents;
  5165. var ac = aabb.center;
  5166. var ar = aabb.halfExtents;
  5167. var mx0 = m[0];
  5168. var mx1 = m[4];
  5169. var mx2 = m[8];
  5170. var my0 = m[1];
  5171. var my1 = m[5];
  5172. var my2 = m[9];
  5173. var mz0 = m[2];
  5174. var mz1 = m[6];
  5175. var mz2 = m[10];
  5176. var mx0a = Math.abs(mx0);
  5177. var mx1a = Math.abs(mx1);
  5178. var mx2a = Math.abs(mx2);
  5179. var my0a = Math.abs(my0);
  5180. var my1a = Math.abs(my1);
  5181. var my2a = Math.abs(my2);
  5182. var mz0a = Math.abs(mz0);
  5183. var mz1a = Math.abs(mz1);
  5184. var mz2a = Math.abs(mz2);
  5185. bc[0] = m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2];
  5186. bc[1] = m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2];
  5187. bc[2] = m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2];
  5188. // vec3.set(
  5189. // bc,
  5190. // m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
  5191. // m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
  5192. // m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2],
  5193. // );
  5194. br[0] = mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2];
  5195. br[1] = my0a * ar[0] + my1a * ar[1] + my2a * ar[2];
  5196. br[2] = mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2];
  5197. // vec3.set(
  5198. // br,
  5199. // mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
  5200. // my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
  5201. // mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2],
  5202. // );
  5203. // this.min = vec3.sub(this.min, bc, br);
  5204. // this.max = vec3.add(this.max, bc, br);
  5205. subVec3(this.min, bc, br);
  5206. addVec3(this.max, bc, br);
  5207. };
  5208. _proto.intersects = function intersects(aabb) {
  5209. var aMax = this.getMax();
  5210. var aMin = this.getMin();
  5211. var bMax = aabb.getMax();
  5212. var bMin = aabb.getMin();
  5213. 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];
  5214. };
  5215. _proto.intersection = function intersection(aabb) {
  5216. if (!this.intersects(aabb)) {
  5217. return null;
  5218. }
  5219. var intersection = new AABB();
  5220. // const min = vec3.max(vec3.create(), this.getMin(), aabb.getMin());
  5221. // const max = vec3.min(vec3.create(), this.getMax(), aabb.getMax());
  5222. var min = maxVec3([0, 0, 0], this.getMin(), aabb.getMin());
  5223. var max = minVec3([0, 0, 0], this.getMax(), aabb.getMax());
  5224. intersection.setMinMax(min, max);
  5225. return intersection;
  5226. }
  5227. // containsPoint(point: vec3) {
  5228. // const min = this.getMin();
  5229. // const max = this.getMax();
  5230. // return !(
  5231. // point[0] < min[0] ||
  5232. // point[0] > max[0] ||
  5233. // point[1] < min[1] ||
  5234. // point[1] > max[1] ||
  5235. // point[2] < min[2] ||
  5236. // point[2] > max[2]
  5237. // );
  5238. // }
  5239. /**
  5240. * get n-vertex
  5241. * @param plane plane of CullingVolume
  5242. */;
  5243. _proto.getNegativeFarPoint = function getNegativeFarPoint(plane) {
  5244. if (plane.pnVertexFlag === 0x111) {
  5245. return copyVec3([0, 0, 0], this.min);
  5246. // return vec3.copy(vec3.create(), this.min);
  5247. } else if (plane.pnVertexFlag === 0x110) {
  5248. return [this.min[0], this.min[1], this.max[2]];
  5249. // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
  5250. } else if (plane.pnVertexFlag === 0x101) {
  5251. return [this.min[0], this.max[1], this.min[2]];
  5252. // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
  5253. } else if (plane.pnVertexFlag === 0x100) {
  5254. return [this.min[0], this.max[1], this.max[2]];
  5255. // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
  5256. } else if (plane.pnVertexFlag === 0x011) {
  5257. return [this.max[0], this.min[1], this.min[2]];
  5258. // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
  5259. } else if (plane.pnVertexFlag === 0x010) {
  5260. return [this.max[0], this.min[1], this.max[2]];
  5261. // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
  5262. } else if (plane.pnVertexFlag === 0x001) {
  5263. return [this.max[0], this.max[1], this.min[2]];
  5264. // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
  5265. } else {
  5266. return [this.max[0], this.max[1], this.max[2]];
  5267. // return vec3.fromValues(this.max[0], this.max[1], this.max[2]);
  5268. }
  5269. }
  5270. /**
  5271. * get p-vertex
  5272. * @param plane plane of CullingVolume
  5273. */;
  5274. _proto.getPositiveFarPoint = function getPositiveFarPoint(plane) {
  5275. if (plane.pnVertexFlag === 0x111) {
  5276. return copyVec3([0, 0, 0], this.max);
  5277. // return vec3.copy(vec3.create(), this.max);
  5278. } else if (plane.pnVertexFlag === 0x110) {
  5279. return [this.max[0], this.max[1], this.min[2]];
  5280. // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
  5281. } else if (plane.pnVertexFlag === 0x101) {
  5282. return [this.max[0], this.min[1], this.max[2]];
  5283. // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
  5284. } else if (plane.pnVertexFlag === 0x100) {
  5285. return [this.max[0], this.min[1], this.min[2]];
  5286. // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
  5287. } else if (plane.pnVertexFlag === 0x011) {
  5288. return [this.min[0], this.max[1], this.max[2]];
  5289. // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
  5290. } else if (plane.pnVertexFlag === 0x010) {
  5291. return [this.min[0], this.max[1], this.min[2]];
  5292. // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
  5293. } else if (plane.pnVertexFlag === 0x001) {
  5294. return [this.min[0], this.min[1], this.max[2]];
  5295. // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
  5296. } else {
  5297. return [this.min[0], this.min[1], this.min[2]];
  5298. // return vec3.fromValues(this.min[0], this.min[1], this.min[2]);
  5299. }
  5300. };
  5301. return AABB;
  5302. }();
  5303. var Plane = /*#__PURE__*/function () {
  5304. function Plane(distance, normal) {
  5305. this.distance = void 0;
  5306. this.normal = void 0;
  5307. /**
  5308. * lookup table for p-vertex & n-vertex when doing frustum culling
  5309. */
  5310. this.pnVertexFlag = void 0;
  5311. this.distance = distance || 0;
  5312. this.normal = normal || vec3.fromValues(0, 1, 0);
  5313. this.updatePNVertexFlag();
  5314. }
  5315. var _proto = Plane.prototype;
  5316. _proto.updatePNVertexFlag = function updatePNVertexFlag() {
  5317. this.pnVertexFlag = (Number(this.normal[0] >= 0) << 8) + (Number(this.normal[1] >= 0) << 4) + Number(this.normal[2] >= 0);
  5318. };
  5319. _proto.distanceToPoint = function distanceToPoint(point) {
  5320. return vec3.dot(point, this.normal) - this.distance;
  5321. };
  5322. _proto.normalize = function normalize() {
  5323. var invLen = 1 / vec3.len(this.normal);
  5324. vec3.scale(this.normal, this.normal, invLen);
  5325. this.distance *= invLen;
  5326. };
  5327. _proto.intersectsLine = function intersectsLine(start, end, point) {
  5328. var d0 = this.distanceToPoint(start);
  5329. var d1 = this.distanceToPoint(end);
  5330. var t = d0 / (d0 - d1);
  5331. var intersects = t >= 0 && t <= 1;
  5332. if (intersects && point) {
  5333. vec3.lerp(point, start, end, t);
  5334. }
  5335. return intersects;
  5336. };
  5337. return Plane;
  5338. }();
  5339. var Mask;
  5340. (function (Mask) {
  5341. Mask[Mask["OUTSIDE"] = 4294967295] = "OUTSIDE";
  5342. Mask[Mask["INSIDE"] = 0] = "INSIDE";
  5343. Mask[Mask["INDETERMINATE"] = 2147483647] = "INDETERMINATE";
  5344. })(Mask || (Mask = {}));
  5345. var Frustum = /*#__PURE__*/function () {
  5346. function Frustum(planes) {
  5347. this.planes = [];
  5348. if (planes) {
  5349. this.planes = planes;
  5350. } else {
  5351. for (var i = 0; i < 6; i++) {
  5352. this.planes.push(new Plane());
  5353. }
  5354. }
  5355. }
  5356. /**
  5357. * extract 6 planes from projectionMatrix
  5358. * @see http://www8.cs.umu.se/kurser/5DV051/HT12/lab/plane_extraction.pdf
  5359. */
  5360. var _proto = Frustum.prototype;
  5361. _proto.extractFromVPMatrix = function extractFromVPMatrix(projectionMatrix) {
  5362. // @ts-ignore
  5363. var m0 = projectionMatrix[0],
  5364. m1 = projectionMatrix[1],
  5365. m2 = projectionMatrix[2],
  5366. m3 = projectionMatrix[3],
  5367. m4 = projectionMatrix[4],
  5368. m5 = projectionMatrix[5],
  5369. m6 = projectionMatrix[6],
  5370. m7 = projectionMatrix[7],
  5371. m8 = projectionMatrix[8],
  5372. m9 = projectionMatrix[9],
  5373. m10 = projectionMatrix[10],
  5374. m11 = projectionMatrix[11],
  5375. m12 = projectionMatrix[12],
  5376. m13 = projectionMatrix[13],
  5377. m14 = projectionMatrix[14],
  5378. m15 = projectionMatrix[15];
  5379. // right
  5380. vec3.set(this.planes[0].normal, m3 - m0, m7 - m4, m11 - m8);
  5381. this.planes[0].distance = m15 - m12;
  5382. // left
  5383. vec3.set(this.planes[1].normal, m3 + m0, m7 + m4, m11 + m8);
  5384. this.planes[1].distance = m15 + m12;
  5385. // bottom
  5386. vec3.set(this.planes[2].normal, m3 + m1, m7 + m5, m11 + m9);
  5387. this.planes[2].distance = m15 + m13;
  5388. // top
  5389. vec3.set(this.planes[3].normal, m3 - m1, m7 - m5, m11 - m9);
  5390. this.planes[3].distance = m15 - m13;
  5391. // far
  5392. vec3.set(this.planes[4].normal, m3 - m2, m7 - m6, m11 - m10);
  5393. this.planes[4].distance = m15 - m14;
  5394. // near
  5395. vec3.set(this.planes[5].normal, m3 + m2, m7 + m6, m11 + m10);
  5396. this.planes[5].distance = m15 + m14;
  5397. this.planes.forEach(function (plane) {
  5398. plane.normalize();
  5399. plane.updatePNVertexFlag();
  5400. });
  5401. };
  5402. return Frustum;
  5403. }();
  5404. var Point = /*#__PURE__*/function () {
  5405. function Point(x, y) {
  5406. if (x === void 0) {
  5407. x = 0;
  5408. }
  5409. if (y === void 0) {
  5410. y = 0;
  5411. }
  5412. this.x = 0;
  5413. this.y = 0;
  5414. this.x = x;
  5415. this.y = y;
  5416. }
  5417. var _proto = Point.prototype;
  5418. _proto.clone = function clone() {
  5419. return new Point(this.x, this.y);
  5420. };
  5421. _proto.copyFrom = function copyFrom(p) {
  5422. this.x = p.x;
  5423. this.y = p.y;
  5424. };
  5425. return Point;
  5426. }();
  5427. var Rectangle = /*#__PURE__*/function () {
  5428. function Rectangle(x, y, width, height) {
  5429. this.x = void 0;
  5430. this.y = void 0;
  5431. this.width = void 0;
  5432. this.height = void 0;
  5433. this.left = void 0;
  5434. this.right = void 0;
  5435. this.top = void 0;
  5436. this.bottom = void 0;
  5437. this.x = x;
  5438. this.y = y;
  5439. this.width = width;
  5440. this.height = height;
  5441. this.left = x;
  5442. this.right = x + width;
  5443. this.top = y;
  5444. this.bottom = y + height;
  5445. }
  5446. var _proto = Rectangle.prototype;
  5447. _proto.toJSON = function toJSON() {};
  5448. return Rectangle;
  5449. }();
  5450. var CSSPropertyPath = /*#__PURE__*/function () {
  5451. function CSSPropertyPath() {
  5452. /**
  5453. * path2Curve
  5454. */
  5455. this.parser = parsePath;
  5456. this.parserWithCSSDisabled = parsePath;
  5457. this.mixer = mergePaths;
  5458. }
  5459. var _proto = CSSPropertyPath.prototype;
  5460. _proto.calculator = function calculator(name, oldParsed, parsed) {
  5461. // unset
  5462. if (parsed instanceof CSSKeywordValue && parsed.value === 'unset') {
  5463. return {
  5464. absolutePath: [],
  5465. hasArc: false,
  5466. segments: [],
  5467. polygons: [],
  5468. polylines: [],
  5469. curve: null,
  5470. totalLength: 0,
  5471. rect: new Rectangle(0, 0, 0, 0)
  5472. };
  5473. }
  5474. return parsed;
  5475. };
  5476. /**
  5477. * update local position
  5478. */
  5479. _proto.postProcessor = function postProcessor(object, attributes) {
  5480. if (object.nodeName === Shape.PATH && attributes.indexOf('transform') === -1) {
  5481. var _object$parsedStyle = object.parsedStyle,
  5482. _object$parsedStyle$d = _object$parsedStyle.defX,
  5483. defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
  5484. _object$parsedStyle$d2 = _object$parsedStyle.defY,
  5485. defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
  5486. object.setLocalPosition(defX, defY);
  5487. }
  5488. };
  5489. return CSSPropertyPath;
  5490. }();
  5491. var CSSPropertyPoints = /*#__PURE__*/function () {
  5492. function CSSPropertyPoints() {
  5493. this.parser = parsePoints;
  5494. this.mixer = mergePoints;
  5495. }
  5496. var _proto = CSSPropertyPoints.prototype;
  5497. /**
  5498. * update local position
  5499. */
  5500. _proto.postProcessor = function postProcessor(object, attributes) {
  5501. if ((object.nodeName === Shape.POLYGON || object.nodeName === Shape.POLYLINE) && attributes.indexOf('transform') === -1) {
  5502. var _object$parsedStyle = object.parsedStyle,
  5503. defX = _object$parsedStyle.defX,
  5504. defY = _object$parsedStyle.defY;
  5505. object.setLocalPosition(defX, defY);
  5506. }
  5507. };
  5508. return CSSPropertyPoints;
  5509. }();
  5510. var CSSPropertyShadowBlur = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
  5511. _inheritsLoose(CSSPropertyShadowBlur, _CSSPropertyLengthOrP);
  5512. function CSSPropertyShadowBlur() {
  5513. var _this;
  5514. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5515. args[_key] = arguments[_key];
  5516. }
  5517. _this = _CSSPropertyLengthOrP.call.apply(_CSSPropertyLengthOrP, [this].concat(args)) || this;
  5518. _this.mixer = clampedMergeNumbers(0, Infinity);
  5519. return _this;
  5520. }
  5521. return CSSPropertyShadowBlur;
  5522. }(CSSPropertyLengthOrPercentage);
  5523. var CSSPropertyText = /*#__PURE__*/function () {
  5524. function CSSPropertyText() {}
  5525. var _proto = CSSPropertyText.prototype;
  5526. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  5527. if (parsed instanceof CSSKeywordValue) {
  5528. if (parsed.value === 'unset') {
  5529. return '';
  5530. } else {
  5531. return parsed.value;
  5532. }
  5533. }
  5534. // allow number as valid text content
  5535. return "" + parsed;
  5536. };
  5537. _proto.postProcessor = function postProcessor(object) {
  5538. object.nodeValue = "" + object.parsedStyle.text || '';
  5539. };
  5540. return CSSPropertyText;
  5541. }();
  5542. /**
  5543. * it must transform after text get parsed
  5544. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform
  5545. */
  5546. var CSSPropertyTextTransform = /*#__PURE__*/function () {
  5547. function CSSPropertyTextTransform() {}
  5548. var _proto = CSSPropertyTextTransform.prototype;
  5549. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  5550. var rawText = object.getAttribute('text');
  5551. if (rawText) {
  5552. var transformedText = rawText;
  5553. if (parsed.value === 'capitalize') {
  5554. transformedText = rawText.charAt(0).toUpperCase() + rawText.slice(1);
  5555. } else if (parsed.value === 'lowercase') {
  5556. transformedText = rawText.toLowerCase();
  5557. } else if (parsed.value === 'uppercase') {
  5558. transformedText = rawText.toUpperCase();
  5559. }
  5560. object.parsedStyle.text = transformedText;
  5561. }
  5562. return parsed.value;
  5563. };
  5564. return CSSPropertyTextTransform;
  5565. }();
  5566. /**
  5567. * @see /zh/docs/api/animation#支持变换的属性
  5568. *
  5569. * support the following formats like CSS Transform:
  5570. *
  5571. * scale
  5572. * * scale(x, y)
  5573. * * scaleX(x)
  5574. * * scaleY(x)
  5575. * * scaleZ(z)
  5576. * * scale3d(x, y, z)
  5577. *
  5578. * translate (unit: none, px, %(relative to its bounds))
  5579. * * translate(x, y) eg. translate(0, 0) translate(0, 30px) translate(100%, 100%)
  5580. * * translateX(0)
  5581. * * translateY(0)
  5582. * * translateZ(0)
  5583. * * translate3d(0, 0, 0)
  5584. *
  5585. * rotate (unit: deg rad turn)
  5586. * * rotate(0.5turn) rotate(30deg) rotate(1rad)
  5587. *
  5588. * none
  5589. *
  5590. * unsupported for now:
  5591. * * calc() eg. translate(calc(100% + 10px))
  5592. * * matrix/matrix3d()
  5593. * * skew/skewX/skewY
  5594. * * perspective
  5595. */
  5596. var CSSPropertyTransform = /*#__PURE__*/function () {
  5597. function CSSPropertyTransform() {
  5598. this.parser = parseTransform;
  5599. this.parserWithCSSDisabled = parseTransform;
  5600. this.mixer = mergeTransforms;
  5601. }
  5602. var _proto = CSSPropertyTransform.prototype;
  5603. _proto.calculator = function calculator(name, oldParsed, parsed, object) {
  5604. // 'none'
  5605. if (parsed instanceof CSSKeywordValue) {
  5606. return [];
  5607. }
  5608. return parsed;
  5609. };
  5610. _proto.postProcessor = function postProcessor(object) {
  5611. var transform = object.parsedStyle.transform;
  5612. parsedTransformToMat4(transform, object);
  5613. };
  5614. return CSSPropertyTransform;
  5615. }();
  5616. /**
  5617. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
  5618. * @example
  5619. * [10px, 10px] [10%, 10%]
  5620. */
  5621. var CSSPropertyTransformOrigin = function CSSPropertyTransformOrigin() {
  5622. this.parser = parseTransformOrigin;
  5623. };
  5624. /**
  5625. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
  5626. */
  5627. var Strategy;
  5628. (function (Strategy) {
  5629. Strategy[Strategy["Standard"] = 0] = "Standard";
  5630. })(Strategy || (Strategy = {}));
  5631. var SortReason;
  5632. (function (SortReason) {
  5633. SortReason[SortReason["ADDED"] = 0] = "ADDED";
  5634. SortReason[SortReason["REMOVED"] = 1] = "REMOVED";
  5635. SortReason[SortReason["Z_INDEX_CHANGED"] = 2] = "Z_INDEX_CHANGED";
  5636. })(SortReason || (SortReason = {}));
  5637. var CSSPropertyZIndex = /*#__PURE__*/function () {
  5638. function CSSPropertyZIndex() {
  5639. this.parser = parseNumber;
  5640. }
  5641. var _proto = CSSPropertyZIndex.prototype;
  5642. _proto.calculator = function calculator(name, oldParsed, computed, object) {
  5643. return computed.value;
  5644. };
  5645. _proto.postProcessor = function postProcessor(object) {
  5646. if (object.parentNode) {
  5647. var parentEntity = object.parentNode;
  5648. var parentRenderable = parentEntity.renderable;
  5649. var parentSortable = parentEntity.sortable;
  5650. if (parentRenderable) {
  5651. parentRenderable.dirty = true;
  5652. }
  5653. // need re-sort on parent
  5654. if (parentSortable) {
  5655. parentSortable.dirty = true;
  5656. parentSortable.dirtyReason = SortReason.Z_INDEX_CHANGED;
  5657. }
  5658. }
  5659. };
  5660. return CSSPropertyZIndex;
  5661. }();
  5662. /**
  5663. * canvas.customElements
  5664. *
  5665. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
  5666. */
  5667. var CustomElementRegistry = /*#__PURE__*/function () {
  5668. function CustomElementRegistry() {
  5669. this.registry = {};
  5670. this.define(Shape.CIRCLE, Circle);
  5671. this.define(Shape.ELLIPSE, Ellipse);
  5672. this.define(Shape.RECT, Rect);
  5673. this.define(Shape.IMAGE, Image);
  5674. this.define(Shape.LINE, Line);
  5675. this.define(Shape.GROUP, Group);
  5676. this.define(Shape.PATH, Path);
  5677. this.define(Shape.POLYGON, Polygon);
  5678. this.define(Shape.POLYLINE, Polyline);
  5679. this.define(Shape.TEXT, Text);
  5680. this.define(Shape.HTML, HTML);
  5681. }
  5682. var _proto = CustomElementRegistry.prototype;
  5683. _proto.define = function define(name, constructor) {
  5684. this.registry[name] = constructor;
  5685. }
  5686. /**
  5687. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/get
  5688. */;
  5689. _proto.get = function get(name) {
  5690. return this.registry[name];
  5691. };
  5692. return CustomElementRegistry;
  5693. }();
  5694. function isFederatedEvent(value) {
  5695. return !!value.type;
  5696. }
  5697. /**
  5698. * An DOM-compatible synthetic event implementation that is "forwarded" on behalf of an original
  5699. * FederatedEvent or native {@link https://dom.spec.whatwg.org/#event Event}.
  5700. */
  5701. var FederatedEvent = /*#__PURE__*/function () {
  5702. /**
  5703. * The event boundary which manages this event. Propagation can only occur
  5704. * within the boundary's jurisdiction.
  5705. */
  5706. function FederatedEvent(manager) {
  5707. /**
  5708. * The type of event, supports the following:
  5709. * * pointerdown
  5710. * * touchstart
  5711. * * mousedown
  5712. * * rightdown
  5713. * * ...
  5714. */
  5715. this.type = void 0;
  5716. /**
  5717. * The propagation phase.
  5718. * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
  5719. */
  5720. this.eventPhase = FederatedEvent.prototype.NONE;
  5721. /**
  5722. * can be used to implement event delegation
  5723. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
  5724. */
  5725. this.target = void 0;
  5726. /**
  5727. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles
  5728. */
  5729. this.bubbles = true;
  5730. /**
  5731. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/cancelBubble
  5732. */
  5733. this.cancelBubble = true;
  5734. /**
  5735. * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
  5736. */
  5737. this.cancelable = false;
  5738. /** the event target when listeners binded */
  5739. this.currentTarget = void 0;
  5740. /** Flags whether the default response of the user agent was prevent through this event. */
  5741. this.defaultPrevented = false;
  5742. /**
  5743. * timestamp when the event created
  5744. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/timeStamp
  5745. */
  5746. this.timeStamp = void 0;
  5747. /**
  5748. * the original event.
  5749. */
  5750. this.nativeEvent = void 0;
  5751. /** The original event that caused this event, if any. */
  5752. this.originalEvent = void 0;
  5753. /** Flags whether propagation was stopped. */
  5754. this.propagationStopped = false;
  5755. /** Flags whether propagation was immediately stopped. */
  5756. this.propagationImmediatelyStopped = false;
  5757. this.manager = void 0;
  5758. /** Event-specific detail */
  5759. this.detail = void 0;
  5760. /**
  5761. * The coordinates of the evnet relative to the nearest DOM layer.
  5762. * This is a non-standard property.
  5763. */
  5764. this.layer = new Point();
  5765. /**
  5766. * The coordinates of the event relative to the DOM document.
  5767. * This is a non-standard property.
  5768. * relative to the DOM document.
  5769. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/pageX
  5770. */
  5771. this.page = new Point();
  5772. /**
  5773. * relative to Canvas, origin is left-top
  5774. */
  5775. this.canvas = new Point();
  5776. /**
  5777. * relative to Viewport, account for Camera
  5778. */
  5779. this.viewport = new Point();
  5780. this.path = void 0;
  5781. /**
  5782. * @see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
  5783. */
  5784. this.view = void 0;
  5785. this.which = void 0;
  5786. this.returnValue = void 0;
  5787. this.srcElement = void 0;
  5788. this.composed = false;
  5789. this.isTrusted = void 0;
  5790. this.NONE = 0;
  5791. this.CAPTURING_PHASE = 1;
  5792. this.AT_TARGET = 2;
  5793. this.BUBBLING_PHASE = 3;
  5794. this.manager = manager;
  5795. }
  5796. var _proto = FederatedEvent.prototype;
  5797. /**
  5798. * The propagation path for this event
  5799. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/composedPath
  5800. *
  5801. * So composedPath()[0] represents the original target.
  5802. * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events#retargeting
  5803. */
  5804. _proto.composedPath = function composedPath() {
  5805. if (this.manager && (!this.path || this.path[0] !== this.target)) {
  5806. this.path = this.target ? this.manager.propagationPath(this.target) : [];
  5807. }
  5808. return this.path;
  5809. }
  5810. /**
  5811. * @deprecated
  5812. */;
  5813. /**
  5814. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
  5815. */
  5816. _proto.preventDefault = function preventDefault() {
  5817. if (this.nativeEvent instanceof Event && this.nativeEvent.cancelable) {
  5818. this.nativeEvent.preventDefault();
  5819. }
  5820. this.defaultPrevented = true;
  5821. }
  5822. /**
  5823. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopImmediatePropagation
  5824. */;
  5825. _proto.stopImmediatePropagation = function stopImmediatePropagation() {
  5826. this.propagationImmediatelyStopped = true;
  5827. }
  5828. /**
  5829. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation
  5830. */;
  5831. _proto.stopPropagation = function stopPropagation() {
  5832. this.propagationStopped = true;
  5833. };
  5834. /**
  5835. * added for compatibility with DOM Event,
  5836. * deprecated props and methods
  5837. */
  5838. _proto.initEvent = function initEvent() {};
  5839. _proto.initUIEvent = function initUIEvent() {};
  5840. _proto.clone = function clone() {
  5841. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  5842. };
  5843. _createClass(FederatedEvent, [{
  5844. key: "name",
  5845. get:
  5846. /**
  5847. * @deprecated
  5848. */
  5849. function get() {
  5850. return this.type;
  5851. }
  5852. }, {
  5853. key: "layerX",
  5854. get: function get() {
  5855. return this.layer.x;
  5856. }
  5857. }, {
  5858. key: "layerY",
  5859. get: function get() {
  5860. return this.layer.y;
  5861. }
  5862. }, {
  5863. key: "pageX",
  5864. get: function get() {
  5865. return this.page.x;
  5866. }
  5867. }, {
  5868. key: "pageY",
  5869. get: function get() {
  5870. return this.page.y;
  5871. }
  5872. }, {
  5873. key: "x",
  5874. get: function get() {
  5875. return this.canvas.x;
  5876. }
  5877. }, {
  5878. key: "y",
  5879. get: function get() {
  5880. return this.canvas.y;
  5881. }
  5882. }, {
  5883. key: "canvasX",
  5884. get: function get() {
  5885. return this.canvas.x;
  5886. }
  5887. }, {
  5888. key: "canvasY",
  5889. get: function get() {
  5890. return this.canvas.y;
  5891. }
  5892. }, {
  5893. key: "viewportX",
  5894. get: function get() {
  5895. return this.viewport.x;
  5896. }
  5897. }, {
  5898. key: "viewportY",
  5899. get: function get() {
  5900. return this.viewport.y;
  5901. }
  5902. }, {
  5903. key: "propagationPath",
  5904. get: function get() {
  5905. return this.composedPath();
  5906. }
  5907. }]);
  5908. return FederatedEvent;
  5909. }();
  5910. /**
  5911. * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
  5912. *
  5913. * @example
  5914. const event = new CustomEvent('build', { detail: { prop1: 'xx' } });
  5915. circle.addEventListener('build', (e) => {
  5916. e.target; // circle
  5917. e.detail; // { prop1: 'xx' }
  5918. });
  5919. circle.dispatchEvent(event);
  5920. */
  5921. var CustomEvent = /*#__PURE__*/function (_FederatedEvent) {
  5922. _inheritsLoose(CustomEvent, _FederatedEvent);
  5923. // eslint-disable-next-line @typescript-eslint/ban-types
  5924. function CustomEvent(eventName, object) {
  5925. var _this;
  5926. _this = _FederatedEvent.call(this, null) || this;
  5927. _this.type = eventName;
  5928. _this.detail = object;
  5929. // compatible with G 3.0
  5930. Object.assign(_assertThisInitialized(_this), object);
  5931. return _this;
  5932. }
  5933. return CustomEvent;
  5934. }(FederatedEvent);
  5935. var DELEGATION_SPLITTER = ':';
  5936. /**
  5937. * Objects that can receive events and may have listeners for them.
  5938. * eg. Element, Canvas, DisplayObject
  5939. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
  5940. */
  5941. var EventTarget = /*#__PURE__*/function () {
  5942. function EventTarget() {
  5943. /**
  5944. * event emitter
  5945. */
  5946. this.emitter = new EventEmitter();
  5947. }
  5948. var _proto = EventTarget.prototype;
  5949. /**
  5950. * @deprecated
  5951. * @alias addEventListener
  5952. */
  5953. _proto.on = function on(type, listener, options) {
  5954. this.addEventListener(type, listener, options);
  5955. return this;
  5956. }
  5957. /**
  5958. * support `capture` & `once` in options
  5959. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
  5960. */;
  5961. _proto.addEventListener = function addEventListener(type, listener, options) {
  5962. var capture = isBoolean(options) && options || isObject(options) && options.capture;
  5963. var once = isObject(options) && options.once;
  5964. var context = isFunction(listener) ? undefined : listener;
  5965. // compatible with G 3.0
  5966. // support using delegate name in event type, eg. 'node:click'
  5967. var useDelegatedName = false;
  5968. var delegatedName = '';
  5969. if (type.indexOf(DELEGATION_SPLITTER) > -1) {
  5970. var _type$split = type.split(DELEGATION_SPLITTER),
  5971. name = _type$split[0],
  5972. eventType = _type$split[1];
  5973. type = eventType;
  5974. delegatedName = name;
  5975. useDelegatedName = true;
  5976. }
  5977. type = capture ? type + "capture" : type;
  5978. listener = isFunction(listener) ? listener : listener.handleEvent;
  5979. // compatible with G 3.0
  5980. if (useDelegatedName) {
  5981. var originListener = listener;
  5982. listener = function listener() {
  5983. var _args$0$target;
  5984. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5985. args[_key] = arguments[_key];
  5986. }
  5987. if (((_args$0$target = args[0].target) === null || _args$0$target === void 0 ? void 0 : _args$0$target.name) !== delegatedName) {
  5988. return;
  5989. }
  5990. // @ts-ignore
  5991. originListener.apply(void 0, args);
  5992. };
  5993. }
  5994. if (once) {
  5995. this.emitter.once(type, listener, context);
  5996. } else {
  5997. this.emitter.on(type, listener, context);
  5998. }
  5999. return this;
  6000. }
  6001. /**
  6002. * @deprecated
  6003. * @alias removeEventListener
  6004. */;
  6005. _proto.off = function off(type, listener, options) {
  6006. if (type) {
  6007. this.removeEventListener(type, listener, options);
  6008. } else {
  6009. // remove all listeners
  6010. this.removeAllEventListeners();
  6011. }
  6012. return this;
  6013. };
  6014. _proto.removeAllEventListeners = function removeAllEventListeners() {
  6015. this.emitter.removeAllListeners();
  6016. };
  6017. _proto.removeEventListener = function removeEventListener(type, listener, options) {
  6018. var _listener;
  6019. var capture = isBoolean(options) && options || isObject(options) && options.capture;
  6020. var context = isFunction(listener) ? undefined : listener;
  6021. type = capture ? type + "capture" : type;
  6022. listener = isFunction(listener) ? listener : (_listener = listener) === null || _listener === void 0 ? void 0 : _listener.handleEvent;
  6023. this.emitter.off(type, listener, context);
  6024. return this;
  6025. }
  6026. /**
  6027. * @deprecated
  6028. * @alias dispatchEvent
  6029. */
  6030. // eslint-disable-next-line @typescript-eslint/ban-types
  6031. ;
  6032. _proto.emit = function emit(eventName, object) {
  6033. this.dispatchEvent(new CustomEvent(eventName, object));
  6034. }
  6035. /**
  6036. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
  6037. */;
  6038. _proto.dispatchEvent = function dispatchEvent(e, skipPropagate) {
  6039. if (skipPropagate === void 0) {
  6040. skipPropagate = false;
  6041. }
  6042. if (!isFederatedEvent(e)) {
  6043. throw new Error('DisplayObject cannot propagate events outside of the Federated Events API');
  6044. }
  6045. // should account for Element / Document / Canvas
  6046. var canvas;
  6047. // @ts-ignore
  6048. if (this.document) {
  6049. canvas = this;
  6050. // @ts-ignore
  6051. } else if (this.defaultView) {
  6052. canvas = this.defaultView;
  6053. } else {
  6054. var _this$ownerDocument;
  6055. canvas = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView;
  6056. }
  6057. // assign event manager
  6058. if (canvas) {
  6059. var _e$manager;
  6060. e.manager = canvas.getEventService() || null;
  6061. if (!e.manager) {
  6062. return false;
  6063. }
  6064. e.defaultPrevented = false;
  6065. e.path = [];
  6066. if (!skipPropagate) {
  6067. e.target = this;
  6068. }
  6069. (_e$manager = e.manager) === null || _e$manager === void 0 ? void 0 : _e$manager.dispatchEvent(e, e.type, skipPropagate);
  6070. }
  6071. return !e.defaultPrevented;
  6072. };
  6073. return EventTarget;
  6074. }();
  6075. /**
  6076. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node
  6077. */
  6078. var Node = /*#__PURE__*/function (_EventTarget) {
  6079. _inheritsLoose(Node, _EventTarget);
  6080. function Node() {
  6081. var _this;
  6082. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  6083. args[_key] = arguments[_key];
  6084. }
  6085. _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
  6086. _this.shadow = false;
  6087. /**
  6088. * points to canvas.document
  6089. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument
  6090. */
  6091. _this.ownerDocument = null;
  6092. /**
  6093. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isConnected
  6094. * @example
  6095. circle.isConnected; // false
  6096. canvas.appendChild(circle);
  6097. circle.isConnected; // true
  6098. */
  6099. _this.isConnected = false;
  6100. /**
  6101. * Returns node's node document's document base URL.
  6102. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node
  6103. */
  6104. _this.baseURI = '';
  6105. /**
  6106. * Returns the children.
  6107. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
  6108. */
  6109. _this.childNodes = [];
  6110. /**
  6111. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
  6112. */
  6113. _this.nodeType = 0;
  6114. /**
  6115. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeName
  6116. */
  6117. _this.nodeName = '';
  6118. /**
  6119. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeValue
  6120. */
  6121. _this.nodeValue = null;
  6122. /**
  6123. * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode
  6124. */
  6125. _this.parentNode = null;
  6126. return _this;
  6127. }
  6128. Node.isNode = function isNode(target) {
  6129. return !!target.childNodes;
  6130. };
  6131. var _proto = Node.prototype;
  6132. /**
  6133. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/getRootNode
  6134. */
  6135. _proto.getRootNode = function getRootNode(opts) {
  6136. if (opts === void 0) {
  6137. opts = {};
  6138. }
  6139. if (this.parentNode) {
  6140. return this.parentNode.getRootNode(opts);
  6141. }
  6142. if (opts.composed && this.host) {
  6143. return this.host.getRootNode(opts);
  6144. }
  6145. return this;
  6146. };
  6147. _proto.hasChildNodes = function hasChildNodes() {
  6148. return this.childNodes.length > 0;
  6149. };
  6150. _proto.isDefaultNamespace = function isDefaultNamespace(namespace) {
  6151. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6152. };
  6153. _proto.lookupNamespaceURI = function lookupNamespaceURI(prefix) {
  6154. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6155. };
  6156. _proto.lookupPrefix = function lookupPrefix(namespace) {
  6157. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6158. };
  6159. _proto.normalize = function normalize() {
  6160. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6161. }
  6162. /**
  6163. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isEqualNode
  6164. */;
  6165. _proto.isEqualNode = function isEqualNode(otherNode) {
  6166. // TODO: compare 2 nodes, not sameness
  6167. return this === otherNode;
  6168. };
  6169. _proto.isSameNode = function isSameNode(otherNode) {
  6170. return this.isEqualNode(otherNode);
  6171. };
  6172. /**
  6173. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
  6174. * @see https://github.com/b-fuze/deno-dom/blob/master/src/dom/node.ts#L338
  6175. */
  6176. _proto.compareDocumentPosition = function compareDocumentPosition(other) {
  6177. if (other === this) {
  6178. // same node
  6179. return 0;
  6180. }
  6181. // if (!(other instanceof Node)) {
  6182. // throw new TypeError(
  6183. // 'Node.compareDocumentPosition: Argument 1 does not implement interface Node.',
  6184. // );
  6185. // }
  6186. var node1Root = other;
  6187. // eslint-disable-next-line @typescript-eslint/no-this-alias
  6188. var node2Root = this;
  6189. var node1Hierarchy = [node1Root];
  6190. var node2Hierarchy = [node2Root];
  6191. while ((_node1Root$parentNode = node1Root.parentNode) !== null && _node1Root$parentNode !== void 0 ? _node1Root$parentNode : node2Root.parentNode) {
  6192. var _node1Root$parentNode;
  6193. node1Root = node1Root.parentNode ? (node1Hierarchy.push(node1Root.parentNode), node1Root.parentNode) : node1Root;
  6194. node2Root = node2Root.parentNode ? (node2Hierarchy.push(node2Root.parentNode), node2Root.parentNode) : node2Root;
  6195. }
  6196. // Check if they don't share the same root node
  6197. if (node1Root !== node2Root) {
  6198. return Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | Node.DOCUMENT_POSITION_PRECEDING;
  6199. }
  6200. var longerHierarchy = node1Hierarchy.length > node2Hierarchy.length ? node1Hierarchy : node2Hierarchy;
  6201. var shorterHierarchy = longerHierarchy === node1Hierarchy ? node2Hierarchy : node1Hierarchy;
  6202. // Check if either is a container of the other
  6203. if (longerHierarchy[longerHierarchy.length - shorterHierarchy.length] === shorterHierarchy[0]) {
  6204. return longerHierarchy === node1Hierarchy ?
  6205. // other is a child of this
  6206. Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING :
  6207. // this is a child of other
  6208. Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING;
  6209. }
  6210. // Find their first common ancestor and see whether they
  6211. // are preceding or following
  6212. var longerStart = longerHierarchy.length - shorterHierarchy.length;
  6213. for (var i = shorterHierarchy.length - 1; i >= 0; i--) {
  6214. var shorterHierarchyNode = shorterHierarchy[i];
  6215. var longerHierarchyNode = longerHierarchy[longerStart + i];
  6216. // We found the first common ancestor
  6217. if (longerHierarchyNode !== shorterHierarchyNode) {
  6218. var siblings = shorterHierarchyNode.parentNode.childNodes;
  6219. if (siblings.indexOf(shorterHierarchyNode) < siblings.indexOf(longerHierarchyNode)) {
  6220. // Shorter is before longer
  6221. if (shorterHierarchy === node1Hierarchy) {
  6222. // Other is before this
  6223. return Node.DOCUMENT_POSITION_PRECEDING;
  6224. } else {
  6225. // This is before other
  6226. return Node.DOCUMENT_POSITION_FOLLOWING;
  6227. }
  6228. } else {
  6229. // Longer is before shorter
  6230. if (longerHierarchy === node1Hierarchy) {
  6231. // Other is before this
  6232. return Node.DOCUMENT_POSITION_PRECEDING;
  6233. } else {
  6234. // Other is after this
  6235. return Node.DOCUMENT_POSITION_FOLLOWING;
  6236. }
  6237. }
  6238. }
  6239. }
  6240. return Node.DOCUMENT_POSITION_FOLLOWING;
  6241. }
  6242. /**
  6243. * @deprecated
  6244. * @alias contains
  6245. */;
  6246. _proto.contain = function contain(other) {
  6247. return this.contains(other);
  6248. };
  6249. _proto.contains = function contains(other) {
  6250. // the node itself, one of its direct children
  6251. var tmp = other;
  6252. // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
  6253. while (tmp && this !== tmp) {
  6254. tmp = tmp.parentNode;
  6255. }
  6256. return !!tmp;
  6257. };
  6258. _proto.getAncestor = function getAncestor(n) {
  6259. // eslint-disable-next-line @typescript-eslint/no-this-alias
  6260. var temp = this;
  6261. while (n > 0 && temp) {
  6262. temp = temp.parentNode;
  6263. n--;
  6264. }
  6265. return temp;
  6266. };
  6267. _proto.forEach = function forEach(callback, assigned) {
  6268. if (assigned === void 0) {
  6269. assigned = false;
  6270. }
  6271. if (!callback(this)) {
  6272. (assigned ? this.childNodes.slice() : this.childNodes).forEach(function (child) {
  6273. child.forEach(callback);
  6274. });
  6275. }
  6276. };
  6277. _createClass(Node, [{
  6278. key: "textContent",
  6279. get:
  6280. /**
  6281. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent
  6282. */
  6283. function get() {
  6284. var out = '';
  6285. if (this.nodeName === Shape.TEXT) {
  6286. // @ts-ignore
  6287. out += this.style.text;
  6288. }
  6289. for (var _iterator = _createForOfIteratorHelperLoose(this.childNodes), _step; !(_step = _iterator()).done;) {
  6290. var child = _step.value;
  6291. if (child.nodeName === Shape.TEXT) {
  6292. out += child.nodeValue;
  6293. } else {
  6294. out += child.textContent;
  6295. }
  6296. }
  6297. return out;
  6298. },
  6299. set: function set(content) {
  6300. var _this2 = this;
  6301. // remove all children
  6302. this.childNodes.slice().forEach(function (child) {
  6303. _this2.removeChild(child);
  6304. });
  6305. if (this.nodeName === Shape.TEXT) {
  6306. // @ts-ignore
  6307. this.style.text = "" + content;
  6308. }
  6309. }
  6310. }, {
  6311. key: "parent",
  6312. get:
  6313. /**
  6314. * @deprecated
  6315. * @alias parentNode
  6316. */
  6317. function get() {
  6318. return this.parentNode;
  6319. }
  6320. }, {
  6321. key: "parentElement",
  6322. get: function get() {
  6323. return null;
  6324. }
  6325. }, {
  6326. key: "nextSibling",
  6327. get: function get() {
  6328. return null;
  6329. }
  6330. }, {
  6331. key: "previousSibling",
  6332. get: function get() {
  6333. return null;
  6334. }
  6335. }, {
  6336. key: "firstChild",
  6337. get: function get() {
  6338. return this.childNodes.length > 0 ? this.childNodes[0] : null;
  6339. }
  6340. }, {
  6341. key: "lastChild",
  6342. get: function get() {
  6343. return this.childNodes.length > 0 ? this.childNodes[this.childNodes.length - 1] : null;
  6344. }
  6345. }]);
  6346. return Node;
  6347. }(EventTarget);
  6348. /**
  6349. * Both nodes are in different documents or different trees in the same document.
  6350. */
  6351. Node.DOCUMENT_POSITION_DISCONNECTED = 1;
  6352. /**
  6353. * otherNode precedes the node in either a pre-order depth-first traversal
  6354. * 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.
  6355. */
  6356. Node.DOCUMENT_POSITION_PRECEDING = 2;
  6357. /**
  6358. * 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.
  6359. */
  6360. Node.DOCUMENT_POSITION_FOLLOWING = 4;
  6361. /**
  6362. * otherNode is an ancestor of the node.
  6363. */
  6364. Node.DOCUMENT_POSITION_CONTAINS = 8;
  6365. /**
  6366. * otherNode is a descendant of the node.
  6367. */
  6368. Node.DOCUMENT_POSITION_CONTAINED_BY = 16;
  6369. /**
  6370. * The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable.
  6371. */
  6372. Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
  6373. /**
  6374. * the entry of DOM tree
  6375. * Document -> Node -> EventTarget
  6376. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
  6377. */
  6378. var Document = /*#__PURE__*/function (_Node) {
  6379. _inheritsLoose(Document, _Node);
  6380. function Document() {
  6381. var _this;
  6382. _this = _Node.call(this) || this;
  6383. /**
  6384. * only document has defaultView, points to canvas,
  6385. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView
  6386. */
  6387. _this.defaultView = null;
  6388. /**
  6389. * the root element of document, eg. <html>
  6390. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement
  6391. */
  6392. _this.documentElement = void 0;
  6393. /**
  6394. * document.timeline in WAAPI
  6395. */
  6396. _this.timeline = void 0;
  6397. _this.ownerDocument = null;
  6398. _this.nodeName = 'document';
  6399. // create timeline
  6400. try {
  6401. _this.timeline = new runtime.AnimationTimeline(_assertThisInitialized(_this));
  6402. } catch (e) {}
  6403. /**
  6404. * for inherited properties, the initial value is used on the root element only,
  6405. * as long as no specified value is supplied.
  6406. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value
  6407. */
  6408. var initialStyle = {};
  6409. BUILT_IN_PROPERTIES.forEach(function (_ref) {
  6410. var n = _ref.n,
  6411. inh = _ref.inh,
  6412. d = _ref.d;
  6413. if (inh && d) {
  6414. initialStyle[n] = isFunction(d) ? d(Shape.GROUP) : d;
  6415. }
  6416. });
  6417. // like <html> in DOM tree
  6418. _this.documentElement = new Group({
  6419. id: 'g-root',
  6420. style: initialStyle
  6421. });
  6422. _this.documentElement.ownerDocument = _assertThisInitialized(_this);
  6423. _this.documentElement.parentNode = _assertThisInitialized(_this);
  6424. _this.childNodes = [_this.documentElement];
  6425. return _this;
  6426. }
  6427. var _proto = Document.prototype;
  6428. /**
  6429. * @example const circle = document.createElement('circle', { style: { r: 10 } });
  6430. */
  6431. _proto.createElement = function createElement(tagName, options) {
  6432. // @observablehq/plot will create <svg>
  6433. if (tagName === 'svg') {
  6434. return this.documentElement;
  6435. }
  6436. // d3 will use <tspan>
  6437. var clazz = this.defaultView.customElements.get(tagName);
  6438. if (!clazz) {
  6439. console.warn('Unsupported tagName: ', tagName);
  6440. clazz = tagName === 'tspan' ? Text : Group;
  6441. }
  6442. var shape = new clazz(options);
  6443. shape.ownerDocument = this;
  6444. return shape;
  6445. };
  6446. _proto.createElementNS = function createElementNS(namespaceURI, tagName, options) {
  6447. return this.createElement(tagName, options);
  6448. };
  6449. _proto.cloneNode = function cloneNode(deep) {
  6450. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6451. };
  6452. _proto.destroy = function destroy() {
  6453. try {
  6454. this.documentElement.destroyChildren();
  6455. this.timeline.destroy();
  6456. } catch (e) {}
  6457. }
  6458. /**
  6459. * Picking 2D graphics with RBush based on BBox, fast but inaccurate.
  6460. */;
  6461. _proto.elementsFromBBox = function elementsFromBBox(minX, minY, maxX, maxY) {
  6462. var rBush = this.defaultView.context.rBushRoot;
  6463. var rBushNodes = rBush.search({
  6464. minX: minX,
  6465. minY: minY,
  6466. maxX: maxX,
  6467. maxY: maxY
  6468. });
  6469. var hitTestList = [];
  6470. rBushNodes.forEach(function (_ref2) {
  6471. var displayObject = _ref2.displayObject;
  6472. var pointerEvents = displayObject.parsedStyle.pointerEvents;
  6473. // account for `visibility`
  6474. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
  6475. var isVisibilityAffected = ['auto', 'visiblepainted', 'visiblefill', 'visiblestroke', 'visible'].includes(pointerEvents);
  6476. if ((!isVisibilityAffected || isVisibilityAffected && displayObject.isVisible()) && !displayObject.isCulled() && displayObject.isInteractive()) {
  6477. hitTestList.push(displayObject);
  6478. }
  6479. });
  6480. // find group with max z-index
  6481. hitTestList.sort(function (a, b) {
  6482. return b.sortable.renderOrder - a.sortable.renderOrder;
  6483. });
  6484. return hitTestList;
  6485. };
  6486. _proto.elementFromPointSync = function elementFromPointSync(x, y) {
  6487. var _this$defaultView$can = this.defaultView.canvas2Viewport({
  6488. x: x,
  6489. y: y
  6490. }),
  6491. viewportX = _this$defaultView$can.x,
  6492. viewportY = _this$defaultView$can.y;
  6493. var _this$defaultView$get = this.defaultView.getConfig(),
  6494. width = _this$defaultView$get.width,
  6495. height = _this$defaultView$get.height;
  6496. // outside canvas' viewport
  6497. if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
  6498. return null;
  6499. }
  6500. var _this$defaultView$vie = this.defaultView.viewport2Client({
  6501. x: viewportX,
  6502. y: viewportY
  6503. }),
  6504. clientX = _this$defaultView$vie.x,
  6505. clientY = _this$defaultView$vie.y;
  6506. var _this$defaultView$get2 = this.defaultView.getRenderingService().hooks.pickSync.call({
  6507. topmost: true,
  6508. position: {
  6509. x: x,
  6510. y: y,
  6511. viewportX: viewportX,
  6512. viewportY: viewportY,
  6513. clientX: clientX,
  6514. clientY: clientY
  6515. },
  6516. picked: []
  6517. }),
  6518. picked = _this$defaultView$get2.picked;
  6519. return picked && picked[0] || this.documentElement;
  6520. }
  6521. /**
  6522. * Do picking with API instead of triggering interactive events.
  6523. *
  6524. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementFromPoint
  6525. */;
  6526. _proto.elementFromPoint =
  6527. /*#__PURE__*/
  6528. function () {
  6529. var _elementFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(x, y) {
  6530. var _this$defaultView$can2, viewportX, viewportY, _this$defaultView$get3, width, height, _this$defaultView$vie2, clientX, clientY, _yield$this$defaultVi, picked;
  6531. return _regeneratorRuntime().wrap(function _callee$(_context) {
  6532. while (1) switch (_context.prev = _context.next) {
  6533. case 0:
  6534. _this$defaultView$can2 = this.defaultView.canvas2Viewport({
  6535. x: x,
  6536. y: y
  6537. }), viewportX = _this$defaultView$can2.x, viewportY = _this$defaultView$can2.y;
  6538. _this$defaultView$get3 = this.defaultView.getConfig(), width = _this$defaultView$get3.width, height = _this$defaultView$get3.height; // outside canvas' viewport
  6539. if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
  6540. _context.next = 4;
  6541. break;
  6542. }
  6543. return _context.abrupt("return", null);
  6544. case 4:
  6545. _this$defaultView$vie2 = this.defaultView.viewport2Client({
  6546. x: viewportX,
  6547. y: viewportY
  6548. }), clientX = _this$defaultView$vie2.x, clientY = _this$defaultView$vie2.y;
  6549. _context.next = 7;
  6550. return this.defaultView.getRenderingService().hooks.pick.promise({
  6551. topmost: true,
  6552. position: {
  6553. x: x,
  6554. y: y,
  6555. viewportX: viewportX,
  6556. viewportY: viewportY,
  6557. clientX: clientX,
  6558. clientY: clientY
  6559. },
  6560. picked: []
  6561. });
  6562. case 7:
  6563. _yield$this$defaultVi = _context.sent;
  6564. picked = _yield$this$defaultVi.picked;
  6565. return _context.abrupt("return", picked && picked[0] || this.documentElement);
  6566. case 10:
  6567. case "end":
  6568. return _context.stop();
  6569. }
  6570. }, _callee, this);
  6571. }));
  6572. function elementFromPoint(_x, _x2) {
  6573. return _elementFromPoint.apply(this, arguments);
  6574. }
  6575. return elementFromPoint;
  6576. }();
  6577. _proto.elementsFromPointSync = function elementsFromPointSync(x, y) {
  6578. var _this$defaultView$can3 = this.defaultView.canvas2Viewport({
  6579. x: x,
  6580. y: y
  6581. }),
  6582. viewportX = _this$defaultView$can3.x,
  6583. viewportY = _this$defaultView$can3.y;
  6584. var _this$defaultView$get4 = this.defaultView.getConfig(),
  6585. width = _this$defaultView$get4.width,
  6586. height = _this$defaultView$get4.height;
  6587. // outside canvas' viewport
  6588. if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
  6589. return [];
  6590. }
  6591. var _this$defaultView$vie3 = this.defaultView.viewport2Client({
  6592. x: viewportX,
  6593. y: viewportY
  6594. }),
  6595. clientX = _this$defaultView$vie3.x,
  6596. clientY = _this$defaultView$vie3.y;
  6597. var _this$defaultView$get5 = this.defaultView.getRenderingService().hooks.pickSync.call({
  6598. topmost: false,
  6599. position: {
  6600. x: x,
  6601. y: y,
  6602. viewportX: viewportX,
  6603. viewportY: viewportY,
  6604. clientX: clientX,
  6605. clientY: clientY
  6606. },
  6607. picked: []
  6608. }),
  6609. picked = _this$defaultView$get5.picked;
  6610. if (picked[picked.length - 1] !== this.documentElement) {
  6611. picked.push(this.documentElement);
  6612. }
  6613. return picked;
  6614. }
  6615. /**
  6616. * Do picking with API instead of triggering interactive events.
  6617. *
  6618. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementsFromPoint
  6619. */;
  6620. _proto.elementsFromPoint =
  6621. /*#__PURE__*/
  6622. function () {
  6623. var _elementsFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(x, y) {
  6624. var _this$defaultView$can4, viewportX, viewportY, _this$defaultView$get6, width, height, _this$defaultView$vie4, clientX, clientY, _yield$this$defaultVi2, picked;
  6625. return _regeneratorRuntime().wrap(function _callee2$(_context2) {
  6626. while (1) switch (_context2.prev = _context2.next) {
  6627. case 0:
  6628. _this$defaultView$can4 = this.defaultView.canvas2Viewport({
  6629. x: x,
  6630. y: y
  6631. }), viewportX = _this$defaultView$can4.x, viewportY = _this$defaultView$can4.y;
  6632. _this$defaultView$get6 = this.defaultView.getConfig(), width = _this$defaultView$get6.width, height = _this$defaultView$get6.height; // outside canvas' viewport
  6633. if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
  6634. _context2.next = 4;
  6635. break;
  6636. }
  6637. return _context2.abrupt("return", []);
  6638. case 4:
  6639. _this$defaultView$vie4 = this.defaultView.viewport2Client({
  6640. x: viewportX,
  6641. y: viewportY
  6642. }), clientX = _this$defaultView$vie4.x, clientY = _this$defaultView$vie4.y;
  6643. _context2.next = 7;
  6644. return this.defaultView.getRenderingService().hooks.pick.promise({
  6645. topmost: false,
  6646. position: {
  6647. x: x,
  6648. y: y,
  6649. viewportX: viewportX,
  6650. viewportY: viewportY,
  6651. clientX: clientX,
  6652. clientY: clientY
  6653. },
  6654. picked: []
  6655. });
  6656. case 7:
  6657. _yield$this$defaultVi2 = _context2.sent;
  6658. picked = _yield$this$defaultVi2.picked;
  6659. if (picked[picked.length - 1] !== this.documentElement) {
  6660. picked.push(this.documentElement);
  6661. }
  6662. return _context2.abrupt("return", picked);
  6663. case 11:
  6664. case "end":
  6665. return _context2.stop();
  6666. }
  6667. }, _callee2, this);
  6668. }));
  6669. function elementsFromPoint(_x3, _x4) {
  6670. return _elementsFromPoint.apply(this, arguments);
  6671. }
  6672. return elementsFromPoint;
  6673. }()
  6674. /**
  6675. * eg. Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
  6676. */
  6677. ;
  6678. _proto.appendChild = function appendChild(newChild, index) {
  6679. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6680. };
  6681. _proto.insertBefore = function insertBefore(newChild, refChild) {
  6682. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6683. };
  6684. _proto.removeChild = function removeChild(oldChild, destroy) {
  6685. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6686. };
  6687. _proto.replaceChild = function replaceChild(newChild, oldChild, destroy) {
  6688. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6689. };
  6690. _proto.append = function append() {
  6691. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6692. };
  6693. _proto.prepend = function prepend() {
  6694. throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
  6695. }
  6696. /**
  6697. * Execute query on documentElement.
  6698. */;
  6699. _proto.getElementById = function getElementById(id) {
  6700. return this.documentElement.getElementById(id);
  6701. };
  6702. _proto.getElementsByName = function getElementsByName(name) {
  6703. return this.documentElement.getElementsByName(name);
  6704. };
  6705. _proto.getElementsByTagName = function getElementsByTagName(tagName) {
  6706. return this.documentElement.getElementsByTagName(tagName);
  6707. };
  6708. _proto.getElementsByClassName = function getElementsByClassName(className) {
  6709. return this.documentElement.getElementsByClassName(className);
  6710. };
  6711. _proto.querySelector = function querySelector(selectors) {
  6712. return this.documentElement.querySelector(selectors);
  6713. };
  6714. _proto.querySelectorAll = function querySelectorAll(selectors) {
  6715. return this.documentElement.querySelectorAll(selectors);
  6716. };
  6717. _proto.find = function find(filter) {
  6718. return this.documentElement.find(filter);
  6719. };
  6720. _proto.findAll = function findAll(filter) {
  6721. return this.documentElement.findAll(filter);
  6722. };
  6723. _createClass(Document, [{
  6724. key: "children",
  6725. get: function get() {
  6726. return this.childNodes;
  6727. }
  6728. }, {
  6729. key: "childElementCount",
  6730. get: function get() {
  6731. return this.childNodes.length;
  6732. }
  6733. }, {
  6734. key: "firstElementChild",
  6735. get: function get() {
  6736. return this.firstChild;
  6737. }
  6738. }, {
  6739. key: "lastElementChild",
  6740. get: function get() {
  6741. return this.lastChild;
  6742. }
  6743. }]);
  6744. return Document;
  6745. }(Node);
  6746. /**
  6747. * built-in events for element
  6748. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
  6749. *
  6750. * TODO: use MutationObserver instead
  6751. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
  6752. */
  6753. var ElementEvent;
  6754. (function (ElementEvent) {
  6755. ElementEvent["REPARENT"] = "reparent";
  6756. ElementEvent["DESTROY"] = "destroy";
  6757. /**
  6758. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified
  6759. */
  6760. ElementEvent["ATTR_MODIFIED"] = "DOMAttrModified";
  6761. /**
  6762. * it has been inserted
  6763. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted
  6764. */
  6765. ElementEvent["INSERTED"] = "DOMNodeInserted";
  6766. /**
  6767. * it is being removed
  6768. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved
  6769. */
  6770. ElementEvent["REMOVED"] = "removed";
  6771. /**
  6772. * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnodeinsertedintodocument
  6773. */
  6774. ElementEvent["MOUNTED"] = "DOMNodeInsertedIntoDocument";
  6775. /**
  6776. * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnoderemovedfromdocument
  6777. */
  6778. ElementEvent["UNMOUNTED"] = "DOMNodeRemovedFromDocument";
  6779. ElementEvent["BOUNDS_CHANGED"] = "bounds-changed";
  6780. ElementEvent["CULLED"] = "culled";
  6781. })(ElementEvent || (ElementEvent = {}));
  6782. var MutationEvent = /*#__PURE__*/function (_FederatedEvent) {
  6783. _inheritsLoose(MutationEvent, _FederatedEvent);
  6784. function MutationEvent(typeArg, relatedNode, prevValue, newValue, attrName, attrChange, prevParsedValue, newParsedValue) {
  6785. var _this;
  6786. _this = _FederatedEvent.call(this, null) || this;
  6787. _this.relatedNode = void 0;
  6788. _this.prevValue = void 0;
  6789. _this.newValue = void 0;
  6790. _this.attrName = void 0;
  6791. _this.attrChange = void 0;
  6792. _this.prevParsedValue = void 0;
  6793. _this.newParsedValue = void 0;
  6794. _this.relatedNode = relatedNode;
  6795. _this.prevValue = prevValue;
  6796. _this.newValue = newValue;
  6797. _this.attrName = attrName;
  6798. _this.attrChange = attrChange;
  6799. _this.prevParsedValue = prevParsedValue;
  6800. _this.newParsedValue = newParsedValue;
  6801. _this.type = typeArg;
  6802. return _this;
  6803. }
  6804. return MutationEvent;
  6805. }(FederatedEvent);
  6806. MutationEvent.ADDITION = 2;
  6807. MutationEvent.MODIFICATION = 1;
  6808. MutationEvent.REMOVAL = 3;
  6809. var entityCounter = 0;
  6810. function resetEntityCounter() {
  6811. entityCounter = 0;
  6812. }
  6813. var insertedEvent = new MutationEvent(ElementEvent.INSERTED, null, '', '', '', 0, '', '');
  6814. var removedEvent = new MutationEvent(ElementEvent.REMOVED, null, '', '', '', 0, '', '');
  6815. var destroyEvent = new CustomEvent(ElementEvent.DESTROY);
  6816. /**
  6817. * Has following capabilities:
  6818. * * Node insert/remove, eg. appendChild, removeChild, remove...
  6819. * * Query eg. querySelector getElementById...
  6820. * * Animation
  6821. */
  6822. var Element = /*#__PURE__*/function (_Node) {
  6823. _inheritsLoose(Element, _Node);
  6824. function Element() {
  6825. var _this;
  6826. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  6827. args[_key] = arguments[_key];
  6828. }
  6829. _this = _Node.call.apply(_Node, [this].concat(args)) || this;
  6830. /**
  6831. * Unique id.
  6832. */
  6833. _this.entity = entityCounter++;
  6834. _this.renderable = {
  6835. bounds: undefined,
  6836. boundsDirty: true,
  6837. renderBounds: undefined,
  6838. renderBoundsDirty: true,
  6839. dirtyRenderBounds: undefined,
  6840. dirty: false,
  6841. proxyNodeName: undefined
  6842. };
  6843. _this.cullable = {
  6844. strategy: Strategy.Standard,
  6845. visibilityPlaneMask: -1,
  6846. visible: true,
  6847. enable: true
  6848. };
  6849. _this.transformable = {
  6850. dirtyFlag: false,
  6851. localDirtyFlag: false,
  6852. frozen: false,
  6853. localPosition: [0, 0, 0],
  6854. localRotation: [0, 0, 0, 1],
  6855. localScale: [1, 1, 1],
  6856. localTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
  6857. localSkew: [0, 0],
  6858. position: [0, 0, 0],
  6859. rotation: [0, 0, 0, 1],
  6860. scaling: [1, 1, 1],
  6861. worldTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
  6862. origin: [0, 0, 0]
  6863. };
  6864. _this.sortable = {
  6865. dirty: false,
  6866. sorted: undefined,
  6867. renderOrder: 0,
  6868. dirtyChildren: [],
  6869. dirtyReason: undefined
  6870. };
  6871. _this.geometry = {
  6872. contentBounds: undefined,
  6873. renderBounds: undefined
  6874. };
  6875. _this.rBushNode = {
  6876. aabb: undefined
  6877. };
  6878. /**
  6879. * used with `getElementById()`
  6880. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/id
  6881. */
  6882. _this.id = void 0;
  6883. /**
  6884. * used in `getElementsByName`
  6885. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
  6886. */
  6887. _this.name = void 0;
  6888. /**
  6889. * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/namespaceURI
  6890. */
  6891. _this.namespaceURI = 'g';
  6892. _this.scrollLeft = 0;
  6893. _this.scrollTop = 0;
  6894. /**
  6895. * We don't support border now
  6896. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
  6897. */
  6898. _this.clientTop = 0;
  6899. _this.clientLeft = 0;
  6900. /**
  6901. * is destroyed or not
  6902. */
  6903. _this.destroyed = false;
  6904. /**
  6905. * compatible with `style`
  6906. * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
  6907. */
  6908. _this.style = {};
  6909. _this.computedStyle = runtime.enableCSSParsing ? {
  6910. anchor: unsetKeywordValue,
  6911. opacity: unsetKeywordValue,
  6912. fillOpacity: unsetKeywordValue,
  6913. strokeOpacity: unsetKeywordValue,
  6914. fill: unsetKeywordValue,
  6915. stroke: unsetKeywordValue,
  6916. transform: unsetKeywordValue,
  6917. transformOrigin: unsetKeywordValue,
  6918. visibility: unsetKeywordValue,
  6919. pointerEvents: unsetKeywordValue,
  6920. lineWidth: unsetKeywordValue,
  6921. lineCap: unsetKeywordValue,
  6922. lineJoin: unsetKeywordValue,
  6923. increasedLineWidthForHitTesting: unsetKeywordValue,
  6924. fontSize: unsetKeywordValue,
  6925. fontFamily: unsetKeywordValue,
  6926. fontStyle: unsetKeywordValue,
  6927. fontWeight: unsetKeywordValue,
  6928. fontVariant: unsetKeywordValue,
  6929. textAlign: unsetKeywordValue,
  6930. textBaseline: unsetKeywordValue,
  6931. textTransform: unsetKeywordValue,
  6932. zIndex: unsetKeywordValue,
  6933. filter: unsetKeywordValue,
  6934. shadowType: unsetKeywordValue
  6935. } : null;
  6936. /**
  6937. * Renderers will use these used values.
  6938. */
  6939. _this.parsedStyle = {
  6940. // opacity: '',
  6941. // fillOpacity: '',
  6942. // strokeOpacity: '',
  6943. // transformOrigin: '',
  6944. // visibility: '',
  6945. // pointerEvents: '',
  6946. // lineWidth: '',
  6947. // lineCap: '',
  6948. // lineJoin: '',
  6949. // increasedLineWidthForHitTesting: '',
  6950. // fontSize: '',
  6951. // fontFamily: '',
  6952. // fontStyle: '',
  6953. // fontWeight: '',
  6954. // fontVariant: '',
  6955. // textAlign: '',
  6956. // textBaseline: '',
  6957. // textTransform: '',
  6958. };
  6959. /**
  6960. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
  6961. */
  6962. _this.attributes = {};
  6963. return _this;
  6964. }
  6965. Element.isElement = function isElement(target) {
  6966. return !!target.getAttribute;
  6967. };
  6968. var _proto = Element.prototype;
  6969. _proto.cloneNode = function cloneNode(deep) {
  6970. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  6971. };
  6972. _proto.appendChild = function appendChild(child, index) {
  6973. var _this$ownerDocument;
  6974. if (child.destroyed) {
  6975. throw new Error(ERROR_MSG_APPEND_DESTROYED_ELEMENT);
  6976. }
  6977. runtime.sceneGraphService.attach(child, this, index);
  6978. if ((_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView) {
  6979. this.ownerDocument.defaultView.mountChildren(child);
  6980. }
  6981. insertedEvent.relatedNode = this;
  6982. child.dispatchEvent(insertedEvent);
  6983. return child;
  6984. };
  6985. _proto.insertBefore = function insertBefore(newChild, refChild) {
  6986. if (!refChild) {
  6987. this.appendChild(newChild);
  6988. } else {
  6989. var index = this.childNodes.indexOf(refChild);
  6990. this.appendChild(newChild, index - 1);
  6991. }
  6992. return newChild;
  6993. };
  6994. _proto.replaceChild = function replaceChild(newChild, oldChild) {
  6995. var index = this.childNodes.indexOf(oldChild);
  6996. this.removeChild(oldChild);
  6997. this.appendChild(newChild, index);
  6998. return oldChild;
  6999. };
  7000. _proto.removeChild = function removeChild(child) {
  7001. var _child$ownerDocument;
  7002. // should emit on itself before detach
  7003. removedEvent.relatedNode = this;
  7004. child.dispatchEvent(removedEvent);
  7005. if ((_child$ownerDocument = child.ownerDocument) === null || _child$ownerDocument === void 0 ? void 0 : _child$ownerDocument.defaultView) {
  7006. child.ownerDocument.defaultView.unmountChildren(child);
  7007. }
  7008. // remove from scene graph
  7009. runtime.sceneGraphService.detach(child);
  7010. return child;
  7011. }
  7012. /**
  7013. * Remove all children which can be appended to its original parent later again.
  7014. */;
  7015. _proto.removeChildren = function removeChildren() {
  7016. for (var i = this.childNodes.length - 1; i >= 0; i--) {
  7017. var child = this.childNodes[i];
  7018. this.removeChild(child);
  7019. }
  7020. }
  7021. /**
  7022. * Recursively destroy all children which can not be appended to its original parent later again.
  7023. */;
  7024. _proto.destroyChildren = function destroyChildren() {
  7025. for (var i = this.childNodes.length - 1; i >= 0; i--) {
  7026. var child = this.childNodes[i];
  7027. if (child.childNodes.length) {
  7028. child.destroyChildren();
  7029. }
  7030. child.destroy();
  7031. }
  7032. }
  7033. /**
  7034. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
  7035. */;
  7036. _proto.matches = function matches(selector) {
  7037. return runtime.sceneGraphService.matches(selector, this);
  7038. };
  7039. _proto.getElementById = function getElementById(id) {
  7040. return runtime.sceneGraphService.querySelector("#" + id, this);
  7041. };
  7042. _proto.getElementsByName = function getElementsByName(name) {
  7043. return runtime.sceneGraphService.querySelectorAll("[name=\"" + name + "\"]", this);
  7044. };
  7045. _proto.getElementsByClassName = function getElementsByClassName(className) {
  7046. return runtime.sceneGraphService.querySelectorAll("." + className, this);
  7047. };
  7048. _proto.getElementsByTagName = function getElementsByTagName(tagName) {
  7049. return runtime.sceneGraphService.querySelectorAll(tagName, this);
  7050. };
  7051. _proto.querySelector = function querySelector(selectors) {
  7052. return runtime.sceneGraphService.querySelector(selectors, this);
  7053. };
  7054. _proto.querySelectorAll = function querySelectorAll(selectors) {
  7055. return runtime.sceneGraphService.querySelectorAll(selectors, this);
  7056. }
  7057. /**
  7058. * should traverses the element and its parents (heading toward the document root)
  7059. * until it finds a node that matches the specified CSS selector.
  7060. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
  7061. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill
  7062. */;
  7063. _proto.closest = function closest(selectors) {
  7064. var el = this;
  7065. do {
  7066. if (runtime.sceneGraphService.matches(selectors, el)) return el;
  7067. el = el.parentElement;
  7068. } while (el !== null);
  7069. return null;
  7070. }
  7071. /**
  7072. * search in scene group, but should not include itself
  7073. */;
  7074. _proto.find = function find(filter) {
  7075. var _this2 = this;
  7076. var target = null;
  7077. this.forEach(function (object) {
  7078. if (object !== _this2 && filter(object)) {
  7079. target = object;
  7080. return true;
  7081. }
  7082. return false;
  7083. });
  7084. return target;
  7085. };
  7086. _proto.findAll = function findAll(filter) {
  7087. var _this3 = this;
  7088. var objects = [];
  7089. this.forEach(function (object) {
  7090. if (object !== _this3 && filter(object)) {
  7091. objects.push(object);
  7092. }
  7093. });
  7094. return objects;
  7095. }
  7096. /**
  7097. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/after
  7098. */;
  7099. _proto.after = function after() {
  7100. var _this4 = this;
  7101. if (this.parentNode) {
  7102. var index = this.parentNode.childNodes.indexOf(this);
  7103. for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  7104. nodes[_key2] = arguments[_key2];
  7105. }
  7106. nodes.forEach(function (node, i) {
  7107. var _this4$parentNode;
  7108. return (_this4$parentNode = _this4.parentNode) === null || _this4$parentNode === void 0 ? void 0 : _this4$parentNode.appendChild(node, index + i + 1);
  7109. });
  7110. }
  7111. }
  7112. /**
  7113. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/before
  7114. */;
  7115. _proto.before = function before() {
  7116. if (this.parentNode) {
  7117. var index = this.parentNode.childNodes.indexOf(this);
  7118. for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  7119. nodes[_key3] = arguments[_key3];
  7120. }
  7121. var first = nodes[0],
  7122. rest = nodes.slice(1);
  7123. this.parentNode.appendChild(first, index);
  7124. first.after.apply(first, rest);
  7125. }
  7126. }
  7127. /**
  7128. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceWith
  7129. */;
  7130. _proto.replaceWith = function replaceWith() {
  7131. this.after.apply(this, arguments);
  7132. this.remove();
  7133. }
  7134. /**
  7135. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/append
  7136. */;
  7137. _proto.append = function append() {
  7138. var _this5 = this;
  7139. for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  7140. nodes[_key4] = arguments[_key4];
  7141. }
  7142. nodes.forEach(function (node) {
  7143. return _this5.appendChild(node);
  7144. });
  7145. }
  7146. /**
  7147. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/prepend
  7148. */;
  7149. _proto.prepend = function prepend() {
  7150. var _this6 = this;
  7151. for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  7152. nodes[_key5] = arguments[_key5];
  7153. }
  7154. nodes.forEach(function (node, i) {
  7155. return _this6.appendChild(node, i);
  7156. });
  7157. }
  7158. /**
  7159. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceChildren
  7160. */;
  7161. _proto.replaceChildren = function replaceChildren() {
  7162. while (this.childNodes.length && this.firstChild) {
  7163. this.removeChild(this.firstChild);
  7164. }
  7165. this.append.apply(this, arguments);
  7166. }
  7167. /**
  7168. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/remove
  7169. */;
  7170. _proto.remove = function remove() {
  7171. if (this.parentNode) {
  7172. return this.parentNode.removeChild(this);
  7173. }
  7174. return this;
  7175. };
  7176. _proto.destroy = function destroy() {
  7177. // destroy itself before remove
  7178. this.dispatchEvent(destroyEvent);
  7179. // remove from scenegraph first
  7180. this.remove();
  7181. // remove event listeners
  7182. this.emitter.removeAllListeners();
  7183. this.destroyed = true;
  7184. };
  7185. _proto.getGeometryBounds = function getGeometryBounds() {
  7186. return runtime.sceneGraphService.getGeometryBounds(this);
  7187. };
  7188. _proto.getRenderBounds = function getRenderBounds() {
  7189. return runtime.sceneGraphService.getBounds(this, true);
  7190. }
  7191. /**
  7192. * get bounds in world space, account for children
  7193. */;
  7194. _proto.getBounds = function getBounds() {
  7195. return runtime.sceneGraphService.getBounds(this);
  7196. }
  7197. /**
  7198. * get bounds in local space, account for children
  7199. */;
  7200. _proto.getLocalBounds = function getLocalBounds() {
  7201. return runtime.sceneGraphService.getLocalBounds(this);
  7202. }
  7203. /**
  7204. * account for context's bounds in client space,
  7205. * but not accounting for children
  7206. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
  7207. */;
  7208. _proto.getBoundingClientRect = function getBoundingClientRect() {
  7209. return runtime.sceneGraphService.getBoundingClientRect(this);
  7210. }
  7211. /**
  7212. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getClientRects
  7213. */;
  7214. _proto.getClientRects = function getClientRects() {
  7215. return [this.getBoundingClientRect()];
  7216. };
  7217. /**
  7218. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap
  7219. * eg. circle.computedStyleMap().get('fill');
  7220. */
  7221. _proto.computedStyleMap = function computedStyleMap() {
  7222. return new Map(Object.entries(this.computedStyle));
  7223. };
  7224. /**
  7225. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
  7226. */
  7227. _proto.getAttributeNames = function getAttributeNames() {
  7228. return Object.keys(this.attributes);
  7229. }
  7230. /**
  7231. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  7232. */;
  7233. _proto.getAttribute = function getAttribute(name) {
  7234. // @see https://github.com/antvis/G/issues/1267
  7235. if (isSymbol(name)) {
  7236. return runtime.enableCSSParsing ? null : undefined;
  7237. }
  7238. var value = this.attributes[name];
  7239. if (value === undefined) {
  7240. var attributeName = formatAttributeName(name);
  7241. value = this.attributes[attributeName];
  7242. // if the given attribute does not exist, the value returned will either be null or ""
  7243. return runtime.enableCSSParsing ? isNil(value) ? null : value : value;
  7244. } else {
  7245. return value;
  7246. }
  7247. }
  7248. /**
  7249. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
  7250. */;
  7251. _proto.hasAttribute = function hasAttribute(qualifiedName) {
  7252. return this.getAttributeNames().includes(qualifiedName);
  7253. }
  7254. /**
  7255. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
  7256. */;
  7257. _proto.hasAttributes = function hasAttributes() {
  7258. return !!this.getAttributeNames().length;
  7259. }
  7260. /**
  7261. * 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.
  7262. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
  7263. */;
  7264. _proto.removeAttribute = function removeAttribute(attributeName) {
  7265. this.setAttribute(attributeName, null);
  7266. delete this.attributes[attributeName];
  7267. }
  7268. /**
  7269. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
  7270. */;
  7271. _proto.setAttribute = function setAttribute(attributeName, value, force) {
  7272. this.attributes[attributeName] = value;
  7273. };
  7274. _proto.getAttributeNS = function getAttributeNS(namespace, localName) {
  7275. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7276. };
  7277. _proto.getAttributeNode = function getAttributeNode(qualifiedName) {
  7278. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7279. };
  7280. _proto.getAttributeNodeNS = function getAttributeNodeNS(namespace, localName) {
  7281. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7282. };
  7283. _proto.hasAttributeNS = function hasAttributeNS(namespace, localName) {
  7284. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7285. };
  7286. _proto.removeAttributeNS = function removeAttributeNS(namespace, localName) {
  7287. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7288. };
  7289. _proto.removeAttributeNode = function removeAttributeNode(attr) {
  7290. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7291. };
  7292. _proto.setAttributeNS = function setAttributeNS(namespace, qualifiedName, value) {
  7293. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7294. };
  7295. _proto.setAttributeNode = function setAttributeNode(attr) {
  7296. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7297. };
  7298. _proto.setAttributeNodeNS = function setAttributeNodeNS(attr) {
  7299. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7300. };
  7301. _proto.toggleAttribute = function toggleAttribute(qualifiedName, force) {
  7302. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7303. };
  7304. _createClass(Element, [{
  7305. key: "className",
  7306. get:
  7307. /**
  7308. * used in `getElementsByClassName`
  7309. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  7310. */
  7311. function get() {
  7312. // @ts-ignore
  7313. return this.getAttribute('class') || '';
  7314. },
  7315. set: function set(className) {
  7316. this.setAttribute('class', className);
  7317. }
  7318. }, {
  7319. key: "classList",
  7320. get:
  7321. /**
  7322. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
  7323. */
  7324. function get() {
  7325. return this.className.split(' ').filter(function (c) {
  7326. return c !== '';
  7327. });
  7328. }
  7329. }, {
  7330. key: "tagName",
  7331. get: function get() {
  7332. return this.nodeName;
  7333. }
  7334. }, {
  7335. key: "children",
  7336. get: function get() {
  7337. return this.childNodes;
  7338. }
  7339. }, {
  7340. key: "childElementCount",
  7341. get: function get() {
  7342. return this.childNodes.length;
  7343. }
  7344. }, {
  7345. key: "firstElementChild",
  7346. get: function get() {
  7347. return this.firstChild;
  7348. }
  7349. }, {
  7350. key: "lastElementChild",
  7351. get: function get() {
  7352. return this.lastChild;
  7353. }
  7354. }, {
  7355. key: "parentElement",
  7356. get: function get() {
  7357. return this.parentNode;
  7358. }
  7359. }, {
  7360. key: "nextSibling",
  7361. get: function get() {
  7362. if (this.parentNode) {
  7363. var index = this.parentNode.childNodes.indexOf(this);
  7364. return this.parentNode.childNodes[index + 1] || null;
  7365. }
  7366. return null;
  7367. }
  7368. }, {
  7369. key: "previousSibling",
  7370. get: function get() {
  7371. if (this.parentNode) {
  7372. var index = this.parentNode.childNodes.indexOf(this);
  7373. return this.parentNode.childNodes[index - 1] || null;
  7374. }
  7375. return null;
  7376. }
  7377. }]);
  7378. return Element;
  7379. }(Node);
  7380. var FederatedMouseEvent = /*#__PURE__*/function (_FederatedEvent) {
  7381. _inheritsLoose(FederatedMouseEvent, _FederatedEvent);
  7382. function FederatedMouseEvent() {
  7383. var _this;
  7384. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  7385. args[_key] = arguments[_key];
  7386. }
  7387. _this = _FederatedEvent.call.apply(_FederatedEvent, [this].concat(args)) || this;
  7388. /** Whether the "alt" key was pressed when this mouse event occurred. */
  7389. _this.altKey = void 0;
  7390. /** The specific button that was pressed in this mouse event. */
  7391. _this.button = void 0;
  7392. /** The button depressed when this event occurred. */
  7393. _this.buttons = void 0;
  7394. /** Whether the "control" key was pressed when this mouse event occurred. */
  7395. _this.ctrlKey = void 0;
  7396. /** Whether the "meta" key was pressed when this mouse event occurred. */
  7397. _this.metaKey = void 0;
  7398. /** This is currently not implemented in the Federated Events API. */
  7399. _this.relatedTarget = void 0;
  7400. /** Whether the "shift" key was pressed when this mouse event occurred. */
  7401. _this.shiftKey = void 0;
  7402. /**
  7403. * The coordinates of the mouse event relative to the canvas.
  7404. */
  7405. _this.client = new Point();
  7406. /**
  7407. * The movement in this pointer relative to the last `mousemove` event.
  7408. */
  7409. _this.movement = new Point();
  7410. /**
  7411. * The offset of the pointer coordinates w.r.t. target DisplayObject in world space. This is
  7412. * not supported at the moment.
  7413. */
  7414. _this.offset = new Point();
  7415. /**
  7416. * The pointer coordinates in world space.
  7417. */
  7418. _this.global = new Point();
  7419. /**
  7420. * The pointer coordinates in sceen space.
  7421. */
  7422. _this.screen = new Point();
  7423. return _this;
  7424. }
  7425. var _proto = FederatedMouseEvent.prototype;
  7426. _proto.getModifierState = function getModifierState(key) {
  7427. return 'getModifierState' in this.nativeEvent && this.nativeEvent.getModifierState(key);
  7428. };
  7429. _proto.initMouseEvent = function initMouseEvent() {
  7430. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  7431. };
  7432. _createClass(FederatedMouseEvent, [{
  7433. key: "clientX",
  7434. get: function get() {
  7435. return this.client.x;
  7436. }
  7437. }, {
  7438. key: "clientY",
  7439. get: function get() {
  7440. return this.client.y;
  7441. }
  7442. }, {
  7443. key: "movementX",
  7444. get: function get() {
  7445. return this.movement.x;
  7446. }
  7447. }, {
  7448. key: "movementY",
  7449. get: function get() {
  7450. return this.movement.y;
  7451. }
  7452. }, {
  7453. key: "offsetX",
  7454. get: function get() {
  7455. return this.offset.x;
  7456. }
  7457. }, {
  7458. key: "offsetY",
  7459. get: function get() {
  7460. return this.offset.y;
  7461. }
  7462. }, {
  7463. key: "globalX",
  7464. get: function get() {
  7465. return this.global.x;
  7466. }
  7467. }, {
  7468. key: "globalY",
  7469. get: function get() {
  7470. return this.global.y;
  7471. }
  7472. }, {
  7473. key: "screenX",
  7474. get: function get() {
  7475. return this.screen.x;
  7476. }
  7477. }, {
  7478. key: "screenY",
  7479. get: function get() {
  7480. return this.screen.y;
  7481. }
  7482. }]);
  7483. return FederatedMouseEvent;
  7484. }(FederatedEvent);
  7485. var FederatedPointerEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
  7486. _inheritsLoose(FederatedPointerEvent, _FederatedMouseEvent);
  7487. function FederatedPointerEvent() {
  7488. var _this;
  7489. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  7490. args[_key] = arguments[_key];
  7491. }
  7492. _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
  7493. /**
  7494. * The unique identifier of the pointer.
  7495. *
  7496. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
  7497. */
  7498. _this.pointerId = void 0;
  7499. /**
  7500. * The width of the pointer's contact along the x-axis, measured in CSS pixels.
  7501. * radiusX of TouchEvents will be represented by this value.
  7502. *
  7503. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
  7504. */
  7505. _this.width = 0;
  7506. /**
  7507. * The height of the pointer's contact along the y-axis, measured in CSS pixels.
  7508. * radiusY of TouchEvents will be represented by this value.
  7509. *
  7510. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
  7511. */
  7512. _this.height = 0;
  7513. /**
  7514. * Indicates whether or not the pointer device that created the event is the primary pointer.
  7515. *
  7516. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
  7517. */
  7518. _this.isPrimary = false;
  7519. /**
  7520. * The type of pointer that triggered the event.
  7521. *
  7522. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
  7523. */
  7524. _this.pointerType = void 0;
  7525. /**
  7526. * Pressure applied by the pointing device during the event.
  7527. *s
  7528. * A Touch's force property will be represented by this value.
  7529. *
  7530. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
  7531. */
  7532. _this.pressure = void 0;
  7533. /**
  7534. * Barrel pressure on a stylus pointer.
  7535. *
  7536. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  7537. */
  7538. _this.tangentialPressure = void 0;
  7539. /**
  7540. * The angle, in degrees, between the pointer device and the screen.
  7541. *
  7542. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
  7543. */
  7544. _this.tiltX = void 0;
  7545. /**
  7546. * The angle, in degrees, between the pointer device and the screen.
  7547. *
  7548. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
  7549. */
  7550. _this.tiltY = void 0;
  7551. /**
  7552. * Twist of a stylus pointer.
  7553. *
  7554. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  7555. */
  7556. _this.twist = void 0;
  7557. return _this;
  7558. }
  7559. var _proto = FederatedPointerEvent.prototype;
  7560. /**
  7561. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents
  7562. */
  7563. _proto.getCoalescedEvents = function getCoalescedEvents() {
  7564. if (this.type === 'pointermove' || this.type === 'mousemove' || this.type === 'touchmove') {
  7565. return [this];
  7566. }
  7567. return [];
  7568. }
  7569. /**
  7570. * @see https://chromestatus.com/feature/5765569655603200
  7571. */;
  7572. _proto.getPredictedEvents = function getPredictedEvents() {
  7573. throw new Error('getPredictedEvents is not supported!');
  7574. }
  7575. /**
  7576. * @see https://github.com/antvis/G/issues/1115
  7577. * We currently reuses event objects in the event system,
  7578. * avoiding the creation of a large number of event objects.
  7579. * Reused objects are only used to carry different data,
  7580. * such as coordinate information, native event objects,
  7581. * and therefore the lifecycle is limited to the event handler,
  7582. * which can lead to unintended consequences if an attempt is made to cache the entire event object.
  7583. *
  7584. * 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.
  7585. */;
  7586. _proto.clone = function clone() {
  7587. return this.manager.clonePointerEvent(this);
  7588. };
  7589. return FederatedPointerEvent;
  7590. }(FederatedMouseEvent);
  7591. var FederatedWheelEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
  7592. _inheritsLoose(FederatedWheelEvent, _FederatedMouseEvent);
  7593. function FederatedWheelEvent() {
  7594. var _this;
  7595. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  7596. args[_key] = arguments[_key];
  7597. }
  7598. _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
  7599. /**
  7600. * The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
  7601. * `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
  7602. */
  7603. _this.deltaMode = void 0;
  7604. /** Horizontal scroll amount */
  7605. _this.deltaX = void 0;
  7606. /** Vertical scroll amount */
  7607. _this.deltaY = void 0;
  7608. /** z-axis scroll amount. */
  7609. _this.deltaZ = void 0;
  7610. /** Units specified in lines. */
  7611. _this.DOM_DELTA_LINE = 0;
  7612. /** Units specified in pages. */
  7613. _this.DOM_DELTA_PAGE = 1;
  7614. /** Units specified in pixels. */
  7615. _this.DOM_DELTA_PIXEL = 2;
  7616. return _this;
  7617. }
  7618. var _proto = FederatedWheelEvent.prototype;
  7619. _proto.clone = function clone() {
  7620. return this.manager.cloneWheelEvent(this);
  7621. };
  7622. return FederatedWheelEvent;
  7623. }(FederatedMouseEvent);
  7624. function isDisplayObject(value) {
  7625. return !!(value === null || value === void 0 ? void 0 : value.nodeName);
  7626. }
  7627. var mutationEvent = new MutationEvent(ElementEvent.ATTR_MODIFIED, null, null, null, null, MutationEvent.MODIFICATION, null, null);
  7628. var DEFAULT_STYLE_PROPS = {
  7629. anchor: '',
  7630. opacity: '',
  7631. fillOpacity: '',
  7632. strokeOpacity: '',
  7633. fill: '',
  7634. stroke: '',
  7635. transform: '',
  7636. transformOrigin: '',
  7637. visibility: '',
  7638. pointerEvents: '',
  7639. lineWidth: '',
  7640. lineCap: '',
  7641. lineJoin: '',
  7642. increasedLineWidthForHitTesting: '',
  7643. fontSize: '',
  7644. fontFamily: '',
  7645. fontStyle: '',
  7646. fontWeight: '',
  7647. fontVariant: '',
  7648. textAlign: '',
  7649. textBaseline: '',
  7650. textTransform: '',
  7651. zIndex: '',
  7652. filter: '',
  7653. shadowType: ''
  7654. };
  7655. var DEFAULT_PARSED_STYLE_PROPS = {
  7656. anchor: [0, 0],
  7657. fill: noneColor,
  7658. stroke: noneColor,
  7659. transform: [],
  7660. zIndex: 0,
  7661. filter: [],
  7662. shadowType: 'outer',
  7663. miterLimit: 10
  7664. };
  7665. var DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED = _extends({}, DEFAULT_PARSED_STYLE_PROPS, {
  7666. opacity: 1,
  7667. fillOpacity: 1,
  7668. strokeOpacity: 1,
  7669. visibility: 'visible',
  7670. pointerEvents: 'auto',
  7671. lineWidth: 1,
  7672. lineCap: 'butt',
  7673. lineJoin: 'miter',
  7674. increasedLineWidthForHitTesting: 0,
  7675. fillRule: 'nonzero'
  7676. // TODO: transformOrigin
  7677. });
  7678. var INHERITABLE_BASE_STYLE_PROPS = ['opacity', 'fillOpacity', 'strokeOpacity', 'transformOrigin', 'visibility', 'pointerEvents', 'lineWidth', 'lineCap', 'lineJoin', 'increasedLineWidthForHitTesting'];
  7679. var INHERITABLE_STYLE_PROPS = [].concat(INHERITABLE_BASE_STYLE_PROPS, ['fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'fontVariant', 'textAlign', 'textBaseline', 'textTransform']);
  7680. var DATASET_PREFIX = 'data-';
  7681. /**
  7682. * prototype chains: DisplayObject -> Element -> Node -> EventTarget
  7683. *
  7684. * mixins: Animatable, Transformable, Visible
  7685. * @see https://github.com/tannerntannern/ts-mixer/blob/master/README.md#mixing-generic-classes
  7686. *
  7687. * Provide abilities in scene graph, such as:
  7688. * * transform `translate/rotate/scale`
  7689. * * add/remove child
  7690. * * visibility and z-index
  7691. *
  7692. * Those abilities are implemented with those components: `Transform/Sortable/Visible`.
  7693. *
  7694. * Emit following events:
  7695. * * init
  7696. * * destroy
  7697. * * attributeChanged
  7698. */
  7699. var DisplayObject = /*#__PURE__*/function (_Element) {
  7700. _inheritsLoose(DisplayObject, _Element);
  7701. function DisplayObject(config) {
  7702. var _this$config$capture;
  7703. var _this;
  7704. _this = _Element.call(this) || this;
  7705. // assign name, id to config
  7706. // eg. group.get('name')
  7707. /**
  7708. * contains style props in constructor's params, eg. fill, stroke...
  7709. */
  7710. _this.config = void 0;
  7711. _this.isCustomElement = false;
  7712. _this.isMutationObserved = false;
  7713. /**
  7714. * push to active animations after calling `animate()`
  7715. */
  7716. _this.activeAnimations = [];
  7717. /**
  7718. * Use data-* attribute.
  7719. * @see https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
  7720. * @example
  7721. * group.dataset.prop1 = 1;
  7722. * group.getAttribute('data-prop1'); // 1
  7723. */
  7724. _this.dataset = void 0;
  7725. /**
  7726. * Use `this.style.clipPath` instead.
  7727. * @deprecated
  7728. */
  7729. _this.getClip = function () {
  7730. return this.style.clipPath || null;
  7731. };
  7732. _this.config = config;
  7733. // compatible with G 3.0
  7734. _this.config.interactive = (_this$config$capture = _this.config.capture) !== null && _this$config$capture !== void 0 ? _this$config$capture : _this.config.interactive;
  7735. // init scene graph node
  7736. _this.id = _this.config.id || '';
  7737. _this.name = _this.config.name || '';
  7738. if (_this.config.className || _this.config.class) {
  7739. _this.className = _this.config.className || _this.config.class;
  7740. }
  7741. _this.nodeName = _this.config.type || Shape.GROUP;
  7742. // compatible with G 3.0
  7743. _this.config.style = _this.config.style || _this.config.attrs || {};
  7744. Object.assign(_this.config.style, _this.config.attrs);
  7745. // this.config.style = {
  7746. // // ...DEFAULT_STYLE_PROPS,
  7747. // ...this.config.style,
  7748. // ...this.config.attrs,
  7749. // };
  7750. if (_this.config.visible != null) {
  7751. _this.config.style.visibility = _this.config.visible === false ? 'hidden' : 'visible';
  7752. }
  7753. if (_this.config.interactive != null) {
  7754. _this.config.style.pointerEvents = _this.config.interactive === false ? 'none' : 'auto';
  7755. }
  7756. // merge parsed value
  7757. Object.assign(_this.parsedStyle, runtime.enableCSSParsing ? DEFAULT_PARSED_STYLE_PROPS : DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED, _this.config.initialParsedStyle);
  7758. if (runtime.enableCSSParsing) {
  7759. Object.assign(_this.attributes, DEFAULT_STYLE_PROPS);
  7760. }
  7761. // start to process attributes
  7762. _this.initAttributes(_this.config.style);
  7763. var Proxy = runtime.globalThis.Proxy ? runtime.globalThis.Proxy : function () {};
  7764. if (runtime.enableDataset) {
  7765. _this.dataset = new Proxy({}, {
  7766. get: function get(target, name) {
  7767. var formattedName = "" + DATASET_PREFIX + kebabize(name);
  7768. if (target[formattedName] !== undefined) {
  7769. return target[formattedName];
  7770. }
  7771. return _this.getAttribute(formattedName);
  7772. },
  7773. set: function set(_, prop, value) {
  7774. _this.setAttribute("" + DATASET_PREFIX + kebabize(prop), value);
  7775. return true;
  7776. }
  7777. });
  7778. }
  7779. if (runtime.enableStyleSyntax) {
  7780. _this.style = new Proxy(
  7781. // @ts-ignore
  7782. {
  7783. // ...this.attributes,
  7784. setProperty: function setProperty(propertyName, value) {
  7785. _this.setAttribute(propertyName, value);
  7786. },
  7787. getPropertyValue: function getPropertyValue(propertyName) {
  7788. return _this.getAttribute(propertyName);
  7789. },
  7790. removeProperty: function removeProperty(propertyName) {
  7791. _this.removeAttribute(propertyName);
  7792. },
  7793. item: function item() {
  7794. return '';
  7795. }
  7796. }, {
  7797. get: function get(target, name) {
  7798. if (target[name] !== undefined) {
  7799. // if (name in target) {
  7800. return target[name];
  7801. }
  7802. return _this.getAttribute(name);
  7803. },
  7804. set: function set(_, prop, value) {
  7805. _this.setAttribute(prop, value);
  7806. return true;
  7807. }
  7808. });
  7809. }
  7810. return _this;
  7811. }
  7812. var _proto = DisplayObject.prototype;
  7813. _proto.destroy = function destroy() {
  7814. _Element.prototype.destroy.call(this);
  7815. // stop all active animations
  7816. this.getAnimations().forEach(function (animation) {
  7817. animation.cancel();
  7818. });
  7819. // FIXME
  7820. // this.renderable = null;
  7821. // this.cullable = null;
  7822. // this.transformable = null;
  7823. // this.rBushNode = null;
  7824. // this.geometry = null;
  7825. // this.sortable = null;
  7826. };
  7827. _proto.cloneNode = function cloneNode(deep, customCloneFunc) {
  7828. var clonedStyle = _extends({}, this.attributes);
  7829. for (var attributeName in clonedStyle) {
  7830. var attribute = clonedStyle[attributeName];
  7831. // @see https://github.com/antvis/G/issues/1095
  7832. if (isDisplayObject(attribute) &&
  7833. // share the same clipPath if possible
  7834. attributeName !== 'clipPath' && attributeName !== 'offsetPath' && attributeName !== 'textPath') {
  7835. clonedStyle[attributeName] = attribute.cloneNode(deep);
  7836. }
  7837. // TODO: clone other type
  7838. if (customCloneFunc) {
  7839. clonedStyle[attributeName] = customCloneFunc(attributeName, attribute);
  7840. }
  7841. }
  7842. var cloned = new this.constructor({
  7843. // copy id & name
  7844. // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode#notes
  7845. id: this.id,
  7846. name: this.name,
  7847. className: this.name,
  7848. interactive: this.interactive,
  7849. style: clonedStyle
  7850. });
  7851. // apply transform
  7852. cloned.setLocalTransform(this.getLocalTransform());
  7853. if (deep) {
  7854. this.children.forEach(function (child) {
  7855. // skip marker
  7856. if (!child.style.isMarker) {
  7857. var clonedChild = child.cloneNode(deep);
  7858. cloned.appendChild(clonedChild);
  7859. }
  7860. });
  7861. }
  7862. return cloned;
  7863. };
  7864. _proto.initAttributes = function initAttributes(attributes) {
  7865. if (attributes === void 0) {
  7866. attributes = {};
  7867. }
  7868. var renderable = this.renderable;
  7869. var options = {
  7870. forceUpdateGeometry: true
  7871. // usedAttributes:
  7872. // // only Group / Text should account for text relative props
  7873. // this.tagName === Shape.GROUP || this.tagName === Shape.TEXT
  7874. // ? INHERITABLE_STYLE_PROPS
  7875. // : INHERITABLE_BASE_STYLE_PROPS,
  7876. };
  7877. if (runtime.enableCSSParsing) {
  7878. // @ts-ignore
  7879. options.usedAttributes = INHERITABLE_STYLE_PROPS;
  7880. }
  7881. // account for FCP, process properties as less as possible
  7882. var formattedAttributes = {};
  7883. for (var name in attributes) {
  7884. var attributeName = formatAttributeName(name);
  7885. formattedAttributes[attributeName] = attributes[name];
  7886. }
  7887. runtime.styleValueRegistry.processProperties(this, formattedAttributes, options);
  7888. // redraw at next frame
  7889. renderable.dirty = true;
  7890. };
  7891. _proto.setAttribute = function setAttribute(name, value, force) {
  7892. if (force === void 0) {
  7893. force = false;
  7894. }
  7895. var attributeName = formatAttributeName(name);
  7896. // ignore undefined value
  7897. if (isUndefined(value)) {
  7898. return;
  7899. }
  7900. if (force || value !== this.attributes[attributeName]) {
  7901. this.internalSetAttribute(attributeName, value);
  7902. _Element.prototype.setAttribute.call(this, attributeName, value);
  7903. }
  7904. }
  7905. /**
  7906. * called when attributes get changed or initialized
  7907. */;
  7908. _proto.internalSetAttribute = function internalSetAttribute(name, value, parseOptions) {
  7909. var _runtime$styleValueRe;
  7910. if (parseOptions === void 0) {
  7911. parseOptions = {};
  7912. }
  7913. var renderable = this.renderable;
  7914. var oldValue = this.attributes[name];
  7915. var oldParsedValue = this.parsedStyle[name];
  7916. runtime.styleValueRegistry.processProperties(this, (_runtime$styleValueRe = {}, _runtime$styleValueRe[name] = value, _runtime$styleValueRe), parseOptions);
  7917. // redraw at next frame
  7918. renderable.dirty = true;
  7919. var newParsedValue = this.parsedStyle[name];
  7920. if (this.isConnected) {
  7921. mutationEvent.relatedNode = this;
  7922. mutationEvent.prevValue = oldValue;
  7923. mutationEvent.newValue = value;
  7924. mutationEvent.attrName = name;
  7925. mutationEvent.prevParsedValue = oldParsedValue;
  7926. mutationEvent.newParsedValue = newParsedValue;
  7927. if (this.isMutationObserved) {
  7928. this.dispatchEvent(mutationEvent);
  7929. } else {
  7930. mutationEvent.target = this;
  7931. this.ownerDocument.defaultView.dispatchEvent(mutationEvent, true);
  7932. }
  7933. }
  7934. if ((this.isCustomElement && this.isConnected || !this.isCustomElement) && this.attributeChangedCallback) {
  7935. this.attributeChangedCallback(name, oldValue, value, oldParsedValue, newParsedValue);
  7936. }
  7937. }
  7938. // #region transformable
  7939. /**
  7940. * returns different values than getBoundingClientRect(), as the latter returns value relative to the viewport
  7941. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
  7942. *
  7943. * FIXME: It is worth noting that getBBox responds to original untransformed values of a drawn object.
  7944. * @see https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox
  7945. */;
  7946. _proto.getBBox = function getBBox() {
  7947. var aabb = this.getBounds();
  7948. var _aabb$getMin = aabb.getMin(),
  7949. left = _aabb$getMin[0],
  7950. top = _aabb$getMin[1];
  7951. var _aabb$getMax = aabb.getMax(),
  7952. right = _aabb$getMax[0],
  7953. bottom = _aabb$getMax[1];
  7954. return new Rectangle(left, top, right - left, bottom - top);
  7955. };
  7956. _proto.setOrigin = function setOrigin(position, y, z) {
  7957. if (y === void 0) {
  7958. y = 0;
  7959. }
  7960. if (z === void 0) {
  7961. z = 0;
  7962. }
  7963. runtime.sceneGraphService.setOrigin(this, createVec3(position, y, z));
  7964. return this;
  7965. };
  7966. _proto.getOrigin = function getOrigin() {
  7967. return runtime.sceneGraphService.getOrigin(this);
  7968. }
  7969. /**
  7970. * set position in world space
  7971. */;
  7972. _proto.setPosition = function setPosition(position, y, z) {
  7973. if (y === void 0) {
  7974. y = 0;
  7975. }
  7976. if (z === void 0) {
  7977. z = 0;
  7978. }
  7979. runtime.sceneGraphService.setPosition(this, createVec3(position, y, z));
  7980. return this;
  7981. }
  7982. /**
  7983. * set position in local space
  7984. */;
  7985. _proto.setLocalPosition = function setLocalPosition(position, y, z) {
  7986. if (y === void 0) {
  7987. y = 0;
  7988. }
  7989. if (z === void 0) {
  7990. z = 0;
  7991. }
  7992. runtime.sceneGraphService.setLocalPosition(this, createVec3(position, y, z));
  7993. return this;
  7994. }
  7995. /**
  7996. * translate in world space
  7997. */;
  7998. _proto.translate = function translate(position, y, z) {
  7999. if (y === void 0) {
  8000. y = 0;
  8001. }
  8002. if (z === void 0) {
  8003. z = 0;
  8004. }
  8005. runtime.sceneGraphService.translate(this, createVec3(position, y, z));
  8006. return this;
  8007. }
  8008. /**
  8009. * translate in local space
  8010. */;
  8011. _proto.translateLocal = function translateLocal(position, y, z) {
  8012. if (y === void 0) {
  8013. y = 0;
  8014. }
  8015. if (z === void 0) {
  8016. z = 0;
  8017. }
  8018. runtime.sceneGraphService.translateLocal(this, createVec3(position, y, z));
  8019. return this;
  8020. };
  8021. _proto.getPosition = function getPosition() {
  8022. return runtime.sceneGraphService.getPosition(this);
  8023. };
  8024. _proto.getLocalPosition = function getLocalPosition() {
  8025. return runtime.sceneGraphService.getLocalPosition(this);
  8026. }
  8027. /**
  8028. * compatible with G 3.0
  8029. *
  8030. * scaling in local space
  8031. * scale(10) = scale(10, 10, 10)
  8032. *
  8033. * we can't set scale in world space
  8034. */;
  8035. _proto.scale = function scale(scaling, y, z) {
  8036. return this.scaleLocal(scaling, y, z);
  8037. };
  8038. _proto.scaleLocal = function scaleLocal(scaling, y, z) {
  8039. if (typeof scaling === 'number') {
  8040. y = y || scaling;
  8041. z = z || scaling;
  8042. scaling = createVec3(scaling, y, z);
  8043. }
  8044. runtime.sceneGraphService.scaleLocal(this, scaling);
  8045. return this;
  8046. }
  8047. /**
  8048. * set scaling in local space
  8049. */;
  8050. _proto.setLocalScale = function setLocalScale(scaling, y, z) {
  8051. if (typeof scaling === 'number') {
  8052. y = y || scaling;
  8053. z = z || scaling;
  8054. scaling = createVec3(scaling, y, z);
  8055. }
  8056. runtime.sceneGraphService.setLocalScale(this, scaling);
  8057. return this;
  8058. }
  8059. /**
  8060. * get scaling in local space
  8061. */;
  8062. _proto.getLocalScale = function getLocalScale() {
  8063. return runtime.sceneGraphService.getLocalScale(this);
  8064. }
  8065. /**
  8066. * get scaling in world space
  8067. */;
  8068. _proto.getScale = function getScale() {
  8069. return runtime.sceneGraphService.getScale(this);
  8070. }
  8071. /**
  8072. * only return degrees of Z axis in world space
  8073. */;
  8074. _proto.getEulerAngles = function getEulerAngles() {
  8075. var _getEuler = getEuler(vec3.create(), runtime.sceneGraphService.getWorldTransform(this)),
  8076. ez = _getEuler[2];
  8077. return rad2deg(ez);
  8078. }
  8079. /**
  8080. * only return degrees of Z axis in local space
  8081. */;
  8082. _proto.getLocalEulerAngles = function getLocalEulerAngles() {
  8083. var _getEuler2 = getEuler(vec3.create(), runtime.sceneGraphService.getLocalRotation(this)),
  8084. ez = _getEuler2[2];
  8085. return rad2deg(ez);
  8086. }
  8087. /**
  8088. * set euler angles(degrees) in world space
  8089. */;
  8090. _proto.setEulerAngles = function setEulerAngles(z) {
  8091. runtime.sceneGraphService.setEulerAngles(this, 0, 0, z);
  8092. return this;
  8093. }
  8094. /**
  8095. * set euler angles(degrees) in local space
  8096. */;
  8097. _proto.setLocalEulerAngles = function setLocalEulerAngles(z) {
  8098. runtime.sceneGraphService.setLocalEulerAngles(this, 0, 0, z);
  8099. return this;
  8100. };
  8101. _proto.rotateLocal = function rotateLocal(x, y, z) {
  8102. if (isNil(y) && isNil(z)) {
  8103. runtime.sceneGraphService.rotateLocal(this, 0, 0, x);
  8104. } else {
  8105. runtime.sceneGraphService.rotateLocal(this, x, y, z);
  8106. }
  8107. return this;
  8108. };
  8109. _proto.rotate = function rotate(x, y, z) {
  8110. if (isNil(y) && isNil(z)) {
  8111. runtime.sceneGraphService.rotate(this, 0, 0, x);
  8112. } else {
  8113. runtime.sceneGraphService.rotate(this, x, y, z);
  8114. }
  8115. return this;
  8116. };
  8117. _proto.setRotation = function setRotation(rotation, y, z, w) {
  8118. runtime.sceneGraphService.setRotation(this, rotation, y, z, w);
  8119. return this;
  8120. };
  8121. _proto.setLocalRotation = function setLocalRotation(rotation, y, z, w) {
  8122. runtime.sceneGraphService.setLocalRotation(this, rotation, y, z, w);
  8123. return this;
  8124. };
  8125. _proto.setLocalSkew = function setLocalSkew(skew, y) {
  8126. runtime.sceneGraphService.setLocalSkew(this, skew, y);
  8127. return this;
  8128. };
  8129. _proto.getRotation = function getRotation() {
  8130. return runtime.sceneGraphService.getRotation(this);
  8131. };
  8132. _proto.getLocalRotation = function getLocalRotation() {
  8133. return runtime.sceneGraphService.getLocalRotation(this);
  8134. };
  8135. _proto.getLocalSkew = function getLocalSkew() {
  8136. return runtime.sceneGraphService.getLocalSkew(this);
  8137. };
  8138. _proto.getLocalTransform = function getLocalTransform() {
  8139. return runtime.sceneGraphService.getLocalTransform(this);
  8140. };
  8141. _proto.getWorldTransform = function getWorldTransform() {
  8142. return runtime.sceneGraphService.getWorldTransform(this);
  8143. };
  8144. _proto.setLocalTransform = function setLocalTransform(transform) {
  8145. runtime.sceneGraphService.setLocalTransform(this, transform);
  8146. return this;
  8147. };
  8148. _proto.resetLocalTransform = function resetLocalTransform() {
  8149. runtime.sceneGraphService.resetLocalTransform(this);
  8150. }
  8151. // #endregion transformable
  8152. // #region animatable
  8153. /**
  8154. * returns an array of all Animation objects affecting this element
  8155. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
  8156. */;
  8157. _proto.getAnimations = function getAnimations() {
  8158. return this.activeAnimations;
  8159. }
  8160. /**
  8161. * create an animation with WAAPI
  8162. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/animate
  8163. */;
  8164. _proto.animate = function animate(keyframes, options) {
  8165. var _this$ownerDocument;
  8166. var timeline = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.timeline;
  8167. if (timeline) {
  8168. return timeline.play(this, keyframes, options);
  8169. }
  8170. return null;
  8171. }
  8172. // #endregion animatable
  8173. // #region visible
  8174. /**
  8175. * shortcut for Used value of `visibility`
  8176. */;
  8177. _proto.isVisible = function isVisible() {
  8178. var _this$parsedStyle;
  8179. return ((_this$parsedStyle = this.parsedStyle) === null || _this$parsedStyle === void 0 ? void 0 : _this$parsedStyle.visibility) === 'visible';
  8180. };
  8181. _proto.isInteractive = function isInteractive() {
  8182. var _this$parsedStyle2;
  8183. return ((_this$parsedStyle2 = this.parsedStyle) === null || _this$parsedStyle2 === void 0 ? void 0 : _this$parsedStyle2.pointerEvents) !== 'none';
  8184. };
  8185. _proto.isCulled = function isCulled() {
  8186. return !!(this.cullable && this.cullable.enable && !this.cullable.visible);
  8187. }
  8188. /**
  8189. * bring to front in current group
  8190. */;
  8191. _proto.toFront = function toFront() {
  8192. if (this.parentNode) {
  8193. this.style.zIndex = Math.max.apply(Math, this.parentNode.children.map(function (child) {
  8194. return Number(child.style.zIndex);
  8195. })) + 1;
  8196. }
  8197. return this;
  8198. }
  8199. /**
  8200. * send to back in current group
  8201. */;
  8202. _proto.toBack = function toBack() {
  8203. if (this.parentNode) {
  8204. this.style.zIndex = Math.min.apply(Math, this.parentNode.children.map(function (child) {
  8205. return Number(child.style.zIndex);
  8206. })) - 1;
  8207. }
  8208. return this;
  8209. }
  8210. // #endregion visible
  8211. // #region deprecated
  8212. /**
  8213. * compatible with G 3.0
  8214. * @alias object.config
  8215. * @deprecated
  8216. */;
  8217. _proto.getConfig = function getConfig() {
  8218. return this.config;
  8219. };
  8220. _proto.attr = function attr() {
  8221. var _this2 = this;
  8222. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  8223. args[_key] = arguments[_key];
  8224. }
  8225. var name = args[0],
  8226. value = args[1];
  8227. if (!name) {
  8228. return this.attributes;
  8229. }
  8230. if (isObject(name)) {
  8231. Object.keys(name).forEach(function (key) {
  8232. _this2.setAttribute(key, name[key]);
  8233. });
  8234. return this;
  8235. }
  8236. if (args.length === 2) {
  8237. this.setAttribute(name, value);
  8238. return this;
  8239. }
  8240. return this.attributes[name];
  8241. }
  8242. /**
  8243. * return 3x3 matrix in world space
  8244. * @deprecated
  8245. */;
  8246. _proto.getMatrix = function getMatrix(transformMat4) {
  8247. var transform = transformMat4 || this.getWorldTransform();
  8248. var _mat4$getTranslation = mat4.getTranslation(vec3.create(), transform),
  8249. tx = _mat4$getTranslation[0],
  8250. ty = _mat4$getTranslation[1];
  8251. var _mat4$getScaling = mat4.getScaling(vec3.create(), transform),
  8252. sx = _mat4$getScaling[0],
  8253. sy = _mat4$getScaling[1];
  8254. var rotation = mat4.getRotation(quat$1.create(), transform);
  8255. var _getEuler3 = getEuler(vec3.create(), rotation),
  8256. eux = _getEuler3[0],
  8257. euz = _getEuler3[2];
  8258. // gimbal lock at 90 degrees
  8259. return fromRotationTranslationScale(eux || euz, tx, ty, sx, sy);
  8260. }
  8261. /**
  8262. * return 3x3 matrix in local space
  8263. * @deprecated
  8264. */;
  8265. _proto.getLocalMatrix = function getLocalMatrix() {
  8266. return this.getMatrix(this.getLocalTransform());
  8267. }
  8268. /**
  8269. * set 3x3 matrix in world space
  8270. * @deprecated
  8271. */;
  8272. _proto.setMatrix = function setMatrix(mat) {
  8273. var _decompose = decompose(mat),
  8274. tx = _decompose[0],
  8275. ty = _decompose[1],
  8276. scalingX = _decompose[2],
  8277. scalingY = _decompose[3],
  8278. angle = _decompose[4];
  8279. this.setEulerAngles(angle).setPosition(tx, ty).setLocalScale(scalingX, scalingY);
  8280. }
  8281. /**
  8282. * set 3x3 matrix in local space
  8283. * @deprecated
  8284. */;
  8285. _proto.setLocalMatrix = function setLocalMatrix(mat) {
  8286. var _decompose2 = decompose(mat),
  8287. tx = _decompose2[0],
  8288. ty = _decompose2[1],
  8289. scalingX = _decompose2[2],
  8290. scalingY = _decompose2[3],
  8291. angle = _decompose2[4];
  8292. this.setLocalEulerAngles(angle).setLocalPosition(tx, ty).setLocalScale(scalingX, scalingY);
  8293. }
  8294. /**
  8295. * Use `visibility: visible` instead.
  8296. * @deprecated
  8297. */;
  8298. _proto.show = function show() {
  8299. if (runtime.enableCSSParsing) {
  8300. this.style.visibility = 'visible';
  8301. } else {
  8302. this.forEach(function (object) {
  8303. object.style.visibility = 'visible';
  8304. });
  8305. }
  8306. }
  8307. /**
  8308. * Use `visibility: hidden` instead.
  8309. * @deprecated
  8310. */;
  8311. _proto.hide = function hide() {
  8312. if (runtime.enableCSSParsing) {
  8313. this.style.visibility = 'hidden';
  8314. } else {
  8315. this.forEach(function (object) {
  8316. object.style.visibility = 'hidden';
  8317. });
  8318. }
  8319. }
  8320. /**
  8321. * Use `childElementCount` instead.
  8322. * @deprecated
  8323. */;
  8324. _proto.getCount = function getCount() {
  8325. return this.childElementCount;
  8326. }
  8327. /**
  8328. * Use `parentElement` instead.
  8329. * @deprecated
  8330. */;
  8331. _proto.getParent = function getParent() {
  8332. return this.parentElement;
  8333. }
  8334. /**
  8335. * Use `children` instead.
  8336. * @deprecated
  8337. */;
  8338. _proto.getChildren = function getChildren() {
  8339. return this.children;
  8340. }
  8341. /**
  8342. * Use `firstElementChild` instead.
  8343. * @deprecated
  8344. */;
  8345. _proto.getFirst = function getFirst() {
  8346. return this.firstElementChild;
  8347. }
  8348. /**
  8349. * Use `lastElementChild` instead.
  8350. * @deprecated
  8351. */;
  8352. _proto.getLast = function getLast() {
  8353. return this.lastElementChild;
  8354. }
  8355. /**
  8356. * Use `this.children[index]` instead.
  8357. * @deprecated
  8358. */;
  8359. _proto.getChildByIndex = function getChildByIndex(index) {
  8360. return this.children[index] || null;
  8361. }
  8362. /**
  8363. * Use `appendChild` instead.
  8364. * @deprecated
  8365. */;
  8366. _proto.add = function add(child, index) {
  8367. return this.appendChild(child, index);
  8368. }
  8369. /**
  8370. * Use `this.style.clipPath` instead.
  8371. * @deprecated
  8372. */;
  8373. _proto.setClip = function setClip(clipPath) {
  8374. this.style.clipPath = clipPath;
  8375. };
  8376. /**
  8377. * @deprecated
  8378. */
  8379. _proto.set = function set(name, value) {
  8380. // @ts-ignore
  8381. this.config[name] = value;
  8382. }
  8383. /**
  8384. * @deprecated
  8385. */;
  8386. _proto.get = function get(name) {
  8387. return this.config[name];
  8388. }
  8389. /**
  8390. * Use `setPosition` instead.
  8391. * @deprecated
  8392. */;
  8393. _proto.moveTo = function moveTo(position, y, z) {
  8394. if (y === void 0) {
  8395. y = 0;
  8396. }
  8397. if (z === void 0) {
  8398. z = 0;
  8399. }
  8400. this.setPosition(position, y, z);
  8401. return this;
  8402. }
  8403. /**
  8404. * Use `setPosition` instead.
  8405. * @deprecated
  8406. */;
  8407. _proto.move = function move(position, y, z) {
  8408. if (y === void 0) {
  8409. y = 0;
  8410. }
  8411. if (z === void 0) {
  8412. z = 0;
  8413. }
  8414. this.setPosition(position, y, z);
  8415. return this;
  8416. }
  8417. /**
  8418. * Use `this.style.zIndex` instead.
  8419. * @deprecated
  8420. */;
  8421. _proto.setZIndex = function setZIndex(zIndex) {
  8422. this.style.zIndex = zIndex;
  8423. return this;
  8424. };
  8425. _createClass(DisplayObject, [{
  8426. key: "interactive",
  8427. get: function get() {
  8428. return this.isInteractive();
  8429. },
  8430. set: function set(b) {
  8431. this.style.pointerEvents = b ? 'auto' : 'none';
  8432. }
  8433. }]);
  8434. return DisplayObject;
  8435. }(Element);
  8436. var _excluded = ["style"];
  8437. var Circle = /*#__PURE__*/function (_DisplayObject) {
  8438. _inheritsLoose(Circle, _DisplayObject);
  8439. function Circle(_temp) {
  8440. var _ref = _temp === void 0 ? {} : _temp,
  8441. style = _ref.style,
  8442. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  8443. return _DisplayObject.call(this, _extends({
  8444. type: Shape.CIRCLE,
  8445. style: runtime.enableCSSParsing ? _extends({
  8446. cx: '',
  8447. cy: '',
  8448. r: ''
  8449. }, style) : _extends({}, style),
  8450. initialParsedStyle: {
  8451. anchor: [0.5, 0.5],
  8452. transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
  8453. }
  8454. }, rest)) || this;
  8455. }
  8456. return Circle;
  8457. }(DisplayObject);
  8458. var _excluded$1 = ["style"];
  8459. /**
  8460. * shadow root
  8461. * @see https://yuque.antfin-inc.com/antv/czqvg5/pgqipg
  8462. */
  8463. var CustomElement = /*#__PURE__*/function (_DisplayObject) {
  8464. _inheritsLoose(CustomElement, _DisplayObject);
  8465. // private shadowNodes: DisplayObject[] = [];
  8466. function CustomElement(_temp) {
  8467. var _this;
  8468. var _ref = _temp === void 0 ? {} : _temp,
  8469. style = _ref.style,
  8470. rest = _objectWithoutPropertiesLoose(_ref, _excluded$1);
  8471. _this = _DisplayObject.call(this, _extends({
  8472. style: runtime.enableCSSParsing ? _extends({
  8473. x: '',
  8474. y: ''
  8475. }, style) : _extends({}, style)
  8476. }, rest)) || this;
  8477. // static get observedAttributes(): string[] {
  8478. // return [];
  8479. // }
  8480. _this.isCustomElement = true;
  8481. return _this;
  8482. }
  8483. return CustomElement;
  8484. }(DisplayObject);
  8485. var _excluded$2 = ["style"];
  8486. var Ellipse = /*#__PURE__*/function (_DisplayObject) {
  8487. _inheritsLoose(Ellipse, _DisplayObject);
  8488. function Ellipse(_temp) {
  8489. var _ref = _temp === void 0 ? {} : _temp,
  8490. style = _ref.style,
  8491. rest = _objectWithoutPropertiesLoose(_ref, _excluded$2);
  8492. return _DisplayObject.call(this, _extends({
  8493. type: Shape.ELLIPSE,
  8494. style: runtime.enableCSSParsing ? _extends({
  8495. cx: '',
  8496. cy: '',
  8497. rx: '',
  8498. ry: ''
  8499. }, style) : _extends({}, style),
  8500. initialParsedStyle: {
  8501. anchor: [0.5, 0.5],
  8502. transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
  8503. }
  8504. }, rest)) || this;
  8505. }
  8506. return Ellipse;
  8507. }(DisplayObject);
  8508. var _excluded$3 = ["style"];
  8509. /**
  8510. * its attributes are inherited by its children.
  8511. * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g
  8512. *
  8513. * @example
  8514. * <g fill="white" stroke="green" stroke-width="5">
  8515. <circle cx="40" cy="40" r="25" />
  8516. <circle cx="60" cy="60" r="25" />
  8517. </g>
  8518. */
  8519. var Group = /*#__PURE__*/function (_DisplayObject) {
  8520. _inheritsLoose(Group, _DisplayObject);
  8521. function Group(_temp) {
  8522. var _ref = _temp === void 0 ? {} : _temp,
  8523. style = _ref.style,
  8524. rest = _objectWithoutPropertiesLoose(_ref, _excluded$3);
  8525. return _DisplayObject.call(this, _extends({
  8526. type: Shape.GROUP,
  8527. style: runtime.enableCSSParsing ? _extends({
  8528. x: '',
  8529. y: '',
  8530. width: '',
  8531. height: ''
  8532. }, style) : _extends({}, style)
  8533. }, rest)) || this;
  8534. }
  8535. return Group;
  8536. }(DisplayObject);
  8537. var _excluded$4 = ["style"];
  8538. /**
  8539. * HTML container
  8540. * @see https://github.com/pmndrs/drei#html
  8541. */
  8542. var HTML = /*#__PURE__*/function (_DisplayObject) {
  8543. _inheritsLoose(HTML, _DisplayObject);
  8544. function HTML(_temp) {
  8545. var _this;
  8546. var _ref = _temp === void 0 ? {} : _temp,
  8547. style = _ref.style,
  8548. rest = _objectWithoutPropertiesLoose(_ref, _excluded$4);
  8549. _this = _DisplayObject.call(this, _extends({
  8550. type: Shape.HTML,
  8551. style: runtime.enableCSSParsing ? _extends({
  8552. x: '',
  8553. y: '',
  8554. width: 'auto',
  8555. height: 'auto',
  8556. innerHTML: ''
  8557. }, style) : _extends({}, style)
  8558. }, rest)) || this;
  8559. _this.cullable.enable = false;
  8560. return _this;
  8561. }
  8562. /**
  8563. * return wrapper HTMLElement
  8564. * * <div> in g-webgl/canvas
  8565. * * <foreignObject> in g-svg
  8566. */
  8567. var _proto = HTML.prototype;
  8568. _proto.getDomElement = function getDomElement() {
  8569. return this.parsedStyle.$el;
  8570. }
  8571. /**
  8572. * override with $el.getBoundingClientRect
  8573. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
  8574. */;
  8575. _proto.getBoundingClientRect = function getBoundingClientRect() {
  8576. return this.parsedStyle.$el.getBoundingClientRect();
  8577. };
  8578. _proto.getClientRects = function getClientRects() {
  8579. return [this.getBoundingClientRect()];
  8580. };
  8581. _proto.getBounds = function getBounds() {
  8582. var _this$ownerDocument, _this$ownerDocument$d;
  8583. var clientRect = this.getBoundingClientRect();
  8584. // calc context's offset
  8585. // @ts-ignore
  8586. 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();
  8587. if (canvasRect) {
  8588. var minX = clientRect.left - canvasRect.left;
  8589. var minY = clientRect.top - canvasRect.top;
  8590. var aabb = new AABB();
  8591. // aabb.setMinMax(
  8592. // vec3.fromValues(minX, minY, 0),
  8593. // vec3.fromValues(minX + clientRect.width, minY + clientRect.height, 0),
  8594. // );
  8595. aabb.setMinMax([minX, minY, 0], [minX + clientRect.width, minY + clientRect.height, 0]);
  8596. return aabb;
  8597. }
  8598. return null;
  8599. };
  8600. _proto.getLocalBounds = function getLocalBounds() {
  8601. if (this.parentNode) {
  8602. var parentInvert = mat4.invert(mat4.create(), this.parentNode.getWorldTransform());
  8603. var bounds = this.getBounds();
  8604. if (!AABB.isEmpty(bounds)) {
  8605. var localBounds = new AABB();
  8606. localBounds.setFromTransformedAABB(bounds, parentInvert);
  8607. return localBounds;
  8608. }
  8609. }
  8610. return this.getBounds();
  8611. };
  8612. return HTML;
  8613. }(DisplayObject);
  8614. var _excluded$5 = ["style"];
  8615. var Image = /*#__PURE__*/function (_DisplayObject) {
  8616. _inheritsLoose(Image, _DisplayObject);
  8617. function Image(_temp) {
  8618. var _ref = _temp === void 0 ? {} : _temp,
  8619. style = _ref.style,
  8620. rest = _objectWithoutPropertiesLoose(_ref, _excluded$5);
  8621. return _DisplayObject.call(this, _extends({
  8622. type: Shape.IMAGE,
  8623. style: runtime.enableCSSParsing ? _extends({
  8624. x: '',
  8625. y: '',
  8626. img: '',
  8627. width: '',
  8628. height: ''
  8629. }, style) : _extends({}, style)
  8630. }, rest)) || this;
  8631. }
  8632. return Image;
  8633. }(DisplayObject);
  8634. var _excluded$6 = ["style"];
  8635. /**
  8636. * Create a line connecting two points.
  8637. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line
  8638. *
  8639. * Also support for using marker.
  8640. */
  8641. var Line = /*#__PURE__*/function (_DisplayObject) {
  8642. _inheritsLoose(Line, _DisplayObject);
  8643. function Line(_temp) {
  8644. var _this;
  8645. var _ref = _temp === void 0 ? {} : _temp,
  8646. style = _ref.style,
  8647. rest = _objectWithoutPropertiesLoose(_ref, _excluded$6);
  8648. _this = _DisplayObject.call(this, _extends({
  8649. type: Shape.LINE,
  8650. style: _extends({
  8651. x1: 0,
  8652. y1: 0,
  8653. x2: 0,
  8654. y2: 0,
  8655. z1: 0,
  8656. z2: 0,
  8657. isBillboard: false
  8658. }, style)
  8659. }, rest)) || this;
  8660. _this.markerStartAngle = 0;
  8661. _this.markerEndAngle = 0;
  8662. var _this$parsedStyle = _this.parsedStyle,
  8663. markerStart = _this$parsedStyle.markerStart,
  8664. markerEnd = _this$parsedStyle.markerEnd;
  8665. if (markerStart && isDisplayObject(markerStart)) {
  8666. _this.markerStartAngle = markerStart.getLocalEulerAngles();
  8667. _this.appendChild(markerStart);
  8668. }
  8669. if (markerEnd && isDisplayObject(markerEnd)) {
  8670. _this.markerEndAngle = markerEnd.getLocalEulerAngles();
  8671. _this.appendChild(markerEnd);
  8672. }
  8673. _this.transformMarker(true);
  8674. _this.transformMarker(false);
  8675. return _this;
  8676. }
  8677. var _proto = Line.prototype;
  8678. _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
  8679. if (attrName === 'x1' || attrName === 'y1' || attrName === 'x2' || attrName === 'y2' || attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
  8680. this.transformMarker(true);
  8681. this.transformMarker(false);
  8682. } else if (attrName === 'markerStart') {
  8683. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8684. this.markerStartAngle = 0;
  8685. prevParsedValue.remove();
  8686. }
  8687. // CSSKeyword 'unset'
  8688. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8689. this.markerStartAngle = newParsedValue.getLocalEulerAngles();
  8690. this.appendChild(newParsedValue);
  8691. this.transformMarker(true);
  8692. }
  8693. } else if (attrName === 'markerEnd') {
  8694. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8695. this.markerEndAngle = 0;
  8696. prevParsedValue.remove();
  8697. }
  8698. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8699. this.markerEndAngle = newParsedValue.getLocalEulerAngles();
  8700. this.appendChild(newParsedValue);
  8701. this.transformMarker(false);
  8702. }
  8703. }
  8704. };
  8705. _proto.transformMarker = function transformMarker(isStart) {
  8706. var _this$parsedStyle2 = this.parsedStyle,
  8707. markerStart = _this$parsedStyle2.markerStart,
  8708. markerEnd = _this$parsedStyle2.markerEnd,
  8709. markerStartOffset = _this$parsedStyle2.markerStartOffset,
  8710. markerEndOffset = _this$parsedStyle2.markerEndOffset,
  8711. x1 = _this$parsedStyle2.x1,
  8712. x2 = _this$parsedStyle2.x2,
  8713. y1 = _this$parsedStyle2.y1,
  8714. y2 = _this$parsedStyle2.y2,
  8715. defX = _this$parsedStyle2.defX,
  8716. defY = _this$parsedStyle2.defY;
  8717. var marker = isStart ? markerStart : markerEnd;
  8718. if (!marker || !isDisplayObject(marker)) {
  8719. return;
  8720. }
  8721. var rad = 0;
  8722. var x;
  8723. var y;
  8724. var ox;
  8725. var oy;
  8726. var offset;
  8727. var originalAngle;
  8728. if (isStart) {
  8729. ox = x1 - defX;
  8730. oy = y1 - defY;
  8731. x = x2 - x1;
  8732. y = y2 - y1;
  8733. offset = markerStartOffset || 0;
  8734. originalAngle = this.markerStartAngle;
  8735. } else {
  8736. ox = x2 - defX;
  8737. oy = y2 - defY;
  8738. x = x1 - x2;
  8739. y = y1 - y2;
  8740. offset = markerEndOffset || 0;
  8741. originalAngle = this.markerEndAngle;
  8742. }
  8743. rad = Math.atan2(y, x);
  8744. // account for markerOffset
  8745. marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
  8746. marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
  8747. };
  8748. _proto.getPoint = function getPoint(ratio, inWorldSpace) {
  8749. if (inWorldSpace === void 0) {
  8750. inWorldSpace = false;
  8751. }
  8752. // TODO: account for z1/z2 in 3D line
  8753. var _this$parsedStyle3 = this.parsedStyle,
  8754. x1 = _this$parsedStyle3.x1,
  8755. y1 = _this$parsedStyle3.y1,
  8756. x2 = _this$parsedStyle3.x2,
  8757. y2 = _this$parsedStyle3.y2,
  8758. defX = _this$parsedStyle3.defX,
  8759. defY = _this$parsedStyle3.defY;
  8760. var _LineUtil$pointAt = Line$1.pointAt(x1, y1, x2, y2, ratio),
  8761. x = _LineUtil$pointAt.x,
  8762. y = _LineUtil$pointAt.y;
  8763. var transformed = vec3.transformMat4(vec3.create(), vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
  8764. // apply local transformation
  8765. return new Point(transformed[0], transformed[1]);
  8766. };
  8767. _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
  8768. if (inWorldSpace === void 0) {
  8769. inWorldSpace = false;
  8770. }
  8771. return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
  8772. };
  8773. _proto.getTotalLength = function getTotalLength() {
  8774. // TODO: account for z1/z2 in 3D line
  8775. var _this$parsedStyle4 = this.parsedStyle,
  8776. x1 = _this$parsedStyle4.x1,
  8777. y1 = _this$parsedStyle4.y1,
  8778. x2 = _this$parsedStyle4.x2,
  8779. y2 = _this$parsedStyle4.y2;
  8780. return Line$1.length(x1, y1, x2, y2);
  8781. };
  8782. return Line;
  8783. }(DisplayObject);
  8784. var _excluded$7 = ["style"];
  8785. var EMPTY_PARSED_PATH = {
  8786. absolutePath: [],
  8787. hasArc: false,
  8788. segments: [],
  8789. polygons: [],
  8790. polylines: [],
  8791. curve: null,
  8792. totalLength: 0,
  8793. rect: new Rectangle(0, 0, 0, 0)
  8794. };
  8795. var Path = /*#__PURE__*/function (_DisplayObject) {
  8796. _inheritsLoose(Path, _DisplayObject);
  8797. function Path(_temp) {
  8798. var _this;
  8799. var _ref = _temp === void 0 ? {} : _temp,
  8800. style = _ref.style,
  8801. rest = _objectWithoutPropertiesLoose(_ref, _excluded$7);
  8802. _this = _DisplayObject.call(this, _extends({
  8803. type: Shape.PATH,
  8804. style: runtime.enableCSSParsing ? _extends({
  8805. path: '',
  8806. miterLimit: ''
  8807. }, style) : _extends({}, style),
  8808. initialParsedStyle: runtime.enableCSSParsing ? null : {
  8809. miterLimit: 4,
  8810. path: _extends({}, EMPTY_PARSED_PATH)
  8811. }
  8812. }, rest)) || this;
  8813. _this.markerStartAngle = 0;
  8814. _this.markerEndAngle = 0;
  8815. /**
  8816. * markers placed at the mid
  8817. */
  8818. _this.markerMidList = [];
  8819. var _this$parsedStyle = _this.parsedStyle,
  8820. markerStart = _this$parsedStyle.markerStart,
  8821. markerEnd = _this$parsedStyle.markerEnd,
  8822. markerMid = _this$parsedStyle.markerMid;
  8823. if (markerStart && isDisplayObject(markerStart)) {
  8824. _this.markerStartAngle = markerStart.getLocalEulerAngles();
  8825. _this.appendChild(markerStart);
  8826. }
  8827. if (markerMid && isDisplayObject(markerMid)) {
  8828. _this.placeMarkerMid(markerMid);
  8829. }
  8830. if (markerEnd && isDisplayObject(markerEnd)) {
  8831. _this.markerEndAngle = markerEnd.getLocalEulerAngles();
  8832. _this.appendChild(markerEnd);
  8833. }
  8834. _this.transformMarker(true);
  8835. _this.transformMarker(false);
  8836. return _this;
  8837. }
  8838. var _proto = Path.prototype;
  8839. _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
  8840. if (attrName === 'path') {
  8841. // recalc markers
  8842. this.transformMarker(true);
  8843. this.transformMarker(false);
  8844. this.placeMarkerMid(this.parsedStyle.markerMid);
  8845. } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
  8846. this.transformMarker(true);
  8847. this.transformMarker(false);
  8848. } else if (attrName === 'markerStart') {
  8849. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8850. this.markerStartAngle = 0;
  8851. prevParsedValue.remove();
  8852. }
  8853. // CSSKeyword 'unset'
  8854. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8855. this.markerStartAngle = newParsedValue.getLocalEulerAngles();
  8856. this.appendChild(newParsedValue);
  8857. this.transformMarker(true);
  8858. }
  8859. } else if (attrName === 'markerEnd') {
  8860. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  8861. this.markerEndAngle = 0;
  8862. prevParsedValue.remove();
  8863. }
  8864. if (newParsedValue && isDisplayObject(newParsedValue)) {
  8865. this.markerEndAngle = newParsedValue.getLocalEulerAngles();
  8866. this.appendChild(newParsedValue);
  8867. this.transformMarker(false);
  8868. }
  8869. } else if (attrName === 'markerMid') {
  8870. this.placeMarkerMid(newParsedValue);
  8871. }
  8872. };
  8873. _proto.transformMarker = function transformMarker(isStart) {
  8874. var _this$parsedStyle2 = this.parsedStyle,
  8875. markerStart = _this$parsedStyle2.markerStart,
  8876. markerEnd = _this$parsedStyle2.markerEnd,
  8877. markerStartOffset = _this$parsedStyle2.markerStartOffset,
  8878. markerEndOffset = _this$parsedStyle2.markerEndOffset,
  8879. defX = _this$parsedStyle2.defX,
  8880. defY = _this$parsedStyle2.defY;
  8881. var marker = isStart ? markerStart : markerEnd;
  8882. if (!marker || !isDisplayObject(marker)) {
  8883. return;
  8884. }
  8885. var rad = 0;
  8886. var x;
  8887. var y;
  8888. var ox;
  8889. var oy;
  8890. var offset;
  8891. var originalAngle;
  8892. if (isStart) {
  8893. var _this$getStartTangent = this.getStartTangent(),
  8894. p1 = _this$getStartTangent[0],
  8895. p2 = _this$getStartTangent[1];
  8896. ox = p2[0] - defX;
  8897. oy = p2[1] - defY;
  8898. x = p1[0] - p2[0];
  8899. y = p1[1] - p2[1];
  8900. offset = markerStartOffset || 0;
  8901. originalAngle = this.markerStartAngle;
  8902. } else {
  8903. var _this$getEndTangent = this.getEndTangent(),
  8904. _p = _this$getEndTangent[0],
  8905. _p2 = _this$getEndTangent[1];
  8906. ox = _p2[0] - defX;
  8907. oy = _p2[1] - defY;
  8908. x = _p[0] - _p2[0];
  8909. y = _p[1] - _p2[1];
  8910. offset = markerEndOffset || 0;
  8911. originalAngle = this.markerEndAngle;
  8912. }
  8913. rad = Math.atan2(y, x);
  8914. // account for markerOffset
  8915. marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
  8916. marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
  8917. };
  8918. _proto.placeMarkerMid = function placeMarkerMid(marker) {
  8919. var _this$parsedStyle3 = this.parsedStyle,
  8920. segments = _this$parsedStyle3.path.segments,
  8921. defX = _this$parsedStyle3.defX,
  8922. defY = _this$parsedStyle3.defY;
  8923. // clear all existed markers
  8924. this.markerMidList.forEach(function (marker) {
  8925. marker.remove();
  8926. });
  8927. if (marker && isDisplayObject(marker)) {
  8928. for (var i = 1; i < segments.length - 1; i++) {
  8929. var _segments$i$currentPo = segments[i].currentPoint,
  8930. ox = _segments$i$currentPo[0],
  8931. oy = _segments$i$currentPo[1];
  8932. var cloned = i === 1 ? marker : marker.cloneNode(true);
  8933. this.markerMidList.push(cloned);
  8934. this.appendChild(cloned);
  8935. cloned.setLocalPosition(ox - defX, oy - defY);
  8936. // TODO: orient of marker
  8937. }
  8938. }
  8939. }
  8940. /**
  8941. * Returns the total length of the path.
  8942. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
  8943. */;
  8944. _proto.getTotalLength = function getTotalLength() {
  8945. return getOrCalculatePathTotalLength(this);
  8946. }
  8947. /**
  8948. * Returns the point at a given distance along the path.
  8949. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getPointAtLength
  8950. */;
  8951. _proto.getPointAtLength = function getPointAtLength$1(distance, inWorldSpace) {
  8952. if (inWorldSpace === void 0) {
  8953. inWorldSpace = false;
  8954. }
  8955. var _this$parsedStyle4 = this.parsedStyle,
  8956. defX = _this$parsedStyle4.defX,
  8957. defY = _this$parsedStyle4.defY,
  8958. absolutePath = _this$parsedStyle4.path.absolutePath;
  8959. var _getPointAtLength2 = getPointAtLength(absolutePath, distance),
  8960. x = _getPointAtLength2.x,
  8961. y = _getPointAtLength2.y;
  8962. var transformed = vec3.transformMat4(vec3.create(), vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
  8963. // apply local transformation
  8964. return new Point(transformed[0], transformed[1]);
  8965. }
  8966. /**
  8967. * Returns the point at a given ratio of the total length in path.
  8968. */;
  8969. _proto.getPoint = function getPoint(ratio, inWorldSpace) {
  8970. if (inWorldSpace === void 0) {
  8971. inWorldSpace = false;
  8972. }
  8973. return this.getPointAtLength(ratio * getOrCalculatePathTotalLength(this), inWorldSpace);
  8974. }
  8975. /**
  8976. * Get start tangent vector
  8977. */;
  8978. _proto.getStartTangent = function getStartTangent() {
  8979. var segments = this.parsedStyle.path.segments;
  8980. var result = [];
  8981. if (segments.length > 1) {
  8982. var startPoint = segments[0].currentPoint;
  8983. var endPoint = segments[1].currentPoint;
  8984. var tangent = segments[1].startTangent;
  8985. result = [];
  8986. if (tangent) {
  8987. result.push([startPoint[0] - tangent[0], startPoint[1] - tangent[1]]);
  8988. result.push([startPoint[0], startPoint[1]]);
  8989. } else {
  8990. result.push([endPoint[0], endPoint[1]]);
  8991. result.push([startPoint[0], startPoint[1]]);
  8992. }
  8993. }
  8994. return result;
  8995. }
  8996. /**
  8997. * Get end tangent vector
  8998. */;
  8999. _proto.getEndTangent = function getEndTangent() {
  9000. var segments = this.parsedStyle.path.segments;
  9001. var length = segments.length;
  9002. var result = [];
  9003. if (length > 1) {
  9004. var startPoint = segments[length - 2].currentPoint;
  9005. var endPoint = segments[length - 1].currentPoint;
  9006. var tangent = segments[length - 1].endTangent;
  9007. result = [];
  9008. if (tangent) {
  9009. result.push([endPoint[0] - tangent[0], endPoint[1] - tangent[1]]);
  9010. result.push([endPoint[0], endPoint[1]]);
  9011. } else {
  9012. result.push([startPoint[0], startPoint[1]]);
  9013. result.push([endPoint[0], endPoint[1]]);
  9014. }
  9015. }
  9016. return result;
  9017. };
  9018. return Path;
  9019. }(DisplayObject);
  9020. var _excluded$8 = ["style"];
  9021. var Polygon = /*#__PURE__*/function (_DisplayObject) {
  9022. _inheritsLoose(Polygon, _DisplayObject);
  9023. function Polygon(_temp) {
  9024. var _this;
  9025. var _ref = _temp === void 0 ? {} : _temp,
  9026. style = _ref.style,
  9027. rest = _objectWithoutPropertiesLoose(_ref, _excluded$8);
  9028. _this = _DisplayObject.call(this, _extends({
  9029. type: Shape.POLYGON,
  9030. style: runtime.enableCSSParsing ? _extends({
  9031. points: '',
  9032. miterLimit: '',
  9033. isClosed: true
  9034. }, style) : _extends({}, style),
  9035. initialParsedStyle: runtime.enableCSSParsing ? null : {
  9036. points: {
  9037. points: [],
  9038. totalLength: 0,
  9039. segments: []
  9040. },
  9041. miterLimit: 4,
  9042. isClosed: true
  9043. }
  9044. }, rest)) || this;
  9045. _this.markerStartAngle = 0;
  9046. _this.markerEndAngle = 0;
  9047. /**
  9048. * markers placed at the mid
  9049. */
  9050. _this.markerMidList = [];
  9051. var _this$parsedStyle = _this.parsedStyle,
  9052. markerStart = _this$parsedStyle.markerStart,
  9053. markerEnd = _this$parsedStyle.markerEnd,
  9054. markerMid = _this$parsedStyle.markerMid;
  9055. if (markerStart && isDisplayObject(markerStart)) {
  9056. _this.markerStartAngle = markerStart.getLocalEulerAngles();
  9057. _this.appendChild(markerStart);
  9058. }
  9059. if (markerMid && isDisplayObject(markerMid)) {
  9060. _this.placeMarkerMid(markerMid);
  9061. }
  9062. if (markerEnd && isDisplayObject(markerEnd)) {
  9063. _this.markerEndAngle = markerEnd.getLocalEulerAngles();
  9064. _this.appendChild(markerEnd);
  9065. }
  9066. _this.transformMarker(true);
  9067. _this.transformMarker(false);
  9068. return _this;
  9069. }
  9070. var _proto = Polygon.prototype;
  9071. _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
  9072. if (attrName === 'points') {
  9073. // recalc markers
  9074. this.transformMarker(true);
  9075. this.transformMarker(false);
  9076. this.placeMarkerMid(this.parsedStyle.markerMid);
  9077. } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
  9078. this.transformMarker(true);
  9079. this.transformMarker(false);
  9080. } else if (attrName === 'markerStart') {
  9081. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  9082. this.markerStartAngle = 0;
  9083. prevParsedValue.remove();
  9084. }
  9085. // CSSKeyword 'unset'
  9086. if (newParsedValue && isDisplayObject(newParsedValue)) {
  9087. this.markerStartAngle = newParsedValue.getLocalEulerAngles();
  9088. this.appendChild(newParsedValue);
  9089. this.transformMarker(true);
  9090. }
  9091. } else if (attrName === 'markerEnd') {
  9092. if (prevParsedValue && isDisplayObject(prevParsedValue)) {
  9093. this.markerEndAngle = 0;
  9094. prevParsedValue.remove();
  9095. }
  9096. if (newParsedValue && isDisplayObject(newParsedValue)) {
  9097. this.markerEndAngle = newParsedValue.getLocalEulerAngles();
  9098. this.appendChild(newParsedValue);
  9099. this.transformMarker(false);
  9100. }
  9101. } else if (attrName === 'markerMid') {
  9102. this.placeMarkerMid(newParsedValue);
  9103. }
  9104. };
  9105. _proto.transformMarker = function transformMarker(isStart) {
  9106. var _this$parsedStyle2 = this.parsedStyle,
  9107. markerStart = _this$parsedStyle2.markerStart,
  9108. markerEnd = _this$parsedStyle2.markerEnd,
  9109. markerStartOffset = _this$parsedStyle2.markerStartOffset,
  9110. markerEndOffset = _this$parsedStyle2.markerEndOffset,
  9111. points = _this$parsedStyle2.points.points,
  9112. defX = _this$parsedStyle2.defX,
  9113. defY = _this$parsedStyle2.defY;
  9114. var marker = isStart ? markerStart : markerEnd;
  9115. if (!marker || !isDisplayObject(marker)) {
  9116. return;
  9117. }
  9118. var rad = 0;
  9119. var x;
  9120. var y;
  9121. var ox;
  9122. var oy;
  9123. var offset;
  9124. var originalAngle;
  9125. ox = points[0][0] - defX;
  9126. oy = points[0][1] - defY;
  9127. if (isStart) {
  9128. x = points[1][0] - points[0][0];
  9129. y = points[1][1] - points[0][1];
  9130. offset = markerStartOffset || 0;
  9131. originalAngle = this.markerStartAngle;
  9132. } else {
  9133. var length = points.length;
  9134. if (!this.parsedStyle.isClosed) {
  9135. ox = points[length - 1][0] - defX;
  9136. oy = points[length - 1][1] - defY;
  9137. x = points[length - 2][0] - points[length - 1][0];
  9138. y = points[length - 2][1] - points[length - 1][1];
  9139. } else {
  9140. x = points[length - 1][0] - points[0][0];
  9141. y = points[length - 1][1] - points[0][1];
  9142. }
  9143. offset = markerEndOffset || 0;
  9144. originalAngle = this.markerEndAngle;
  9145. }
  9146. rad = Math.atan2(y, x);
  9147. // account for markerOffset
  9148. marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
  9149. marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
  9150. };
  9151. _proto.placeMarkerMid = function placeMarkerMid(marker) {
  9152. var _this$parsedStyle3 = this.parsedStyle,
  9153. points = _this$parsedStyle3.points.points,
  9154. defX = _this$parsedStyle3.defX,
  9155. defY = _this$parsedStyle3.defY;
  9156. // clear all existed markers
  9157. this.markerMidList.forEach(function (marker) {
  9158. marker.remove();
  9159. });
  9160. this.markerMidList = [];
  9161. if (marker && isDisplayObject(marker)) {
  9162. for (var i = 1; i < (this.parsedStyle.isClosed ? points.length : points.length - 1); i++) {
  9163. var ox = points[i][0] - defX;
  9164. var oy = points[i][1] - defY;
  9165. var cloned = i === 1 ? marker : marker.cloneNode(true);
  9166. this.markerMidList.push(cloned);
  9167. this.appendChild(cloned);
  9168. cloned.setLocalPosition(ox, oy);
  9169. // TODO: orient of marker
  9170. }
  9171. }
  9172. };
  9173. return Polygon;
  9174. }(DisplayObject);
  9175. var _excluded$9 = ["style"];
  9176. /**
  9177. * Polyline inherits the marker-related capabilities of Polygon.
  9178. */
  9179. var Polyline = /*#__PURE__*/function (_Polygon) {
  9180. _inheritsLoose(Polyline, _Polygon);
  9181. function Polyline(_temp) {
  9182. var _ref = _temp === void 0 ? {} : _temp,
  9183. style = _ref.style,
  9184. rest = _objectWithoutPropertiesLoose(_ref, _excluded$9);
  9185. return _Polygon.call(this, _extends({
  9186. type: Shape.POLYLINE,
  9187. style: runtime.enableCSSParsing ? _extends({
  9188. points: '',
  9189. miterLimit: '',
  9190. isClosed: false
  9191. }, style) : _extends({}, style),
  9192. initialParsedStyle: runtime.enableCSSParsing ? null : {
  9193. points: {
  9194. points: [],
  9195. totalLength: 0,
  9196. segments: []
  9197. },
  9198. miterLimit: 4,
  9199. isClosed: false
  9200. }
  9201. }, rest)) || this;
  9202. }
  9203. var _proto = Polyline.prototype;
  9204. _proto.getTotalLength = function getTotalLength() {
  9205. return this.parsedStyle.points.totalLength;
  9206. };
  9207. _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
  9208. if (inWorldSpace === void 0) {
  9209. inWorldSpace = false;
  9210. }
  9211. return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
  9212. };
  9213. _proto.getPoint = function getPoint(ratio, inWorldSpace) {
  9214. if (inWorldSpace === void 0) {
  9215. inWorldSpace = false;
  9216. }
  9217. var _this$parsedStyle = this.parsedStyle,
  9218. defX = _this$parsedStyle.defX,
  9219. defY = _this$parsedStyle.defY,
  9220. _this$parsedStyle$poi = _this$parsedStyle.points,
  9221. points = _this$parsedStyle$poi.points,
  9222. segments = _this$parsedStyle$poi.segments;
  9223. var subt = 0;
  9224. var index = 0;
  9225. segments.forEach(function (v, i) {
  9226. if (ratio >= v[0] && ratio <= v[1]) {
  9227. subt = (ratio - v[0]) / (v[1] - v[0]);
  9228. index = i;
  9229. }
  9230. });
  9231. var _LineUtil$pointAt = Line$1.pointAt(points[index][0], points[index][1], points[index + 1][0], points[index + 1][1], subt),
  9232. x = _LineUtil$pointAt.x,
  9233. y = _LineUtil$pointAt.y;
  9234. var transformed = vec3.transformMat4(vec3.create(), vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
  9235. // apply local transformation
  9236. return new Point(transformed[0], transformed[1]);
  9237. };
  9238. _proto.getStartTangent = function getStartTangent() {
  9239. var points = this.parsedStyle.points.points;
  9240. var result = [];
  9241. result.push([points[1][0], points[1][1]]);
  9242. result.push([points[0][0], points[0][1]]);
  9243. return result;
  9244. };
  9245. _proto.getEndTangent = function getEndTangent() {
  9246. var points = this.parsedStyle.points.points;
  9247. var l = points.length - 1;
  9248. var result = [];
  9249. result.push([points[l - 1][0], points[l - 1][1]]);
  9250. result.push([points[l][0], points[l][1]]);
  9251. return result;
  9252. };
  9253. return Polyline;
  9254. }(Polygon);
  9255. var _excluded$a = ["style"];
  9256. var Rect = /*#__PURE__*/function (_DisplayObject) {
  9257. _inheritsLoose(Rect, _DisplayObject);
  9258. function Rect(_temp) {
  9259. var _ref = _temp === void 0 ? {} : _temp,
  9260. style = _ref.style,
  9261. rest = _objectWithoutPropertiesLoose(_ref, _excluded$a);
  9262. return _DisplayObject.call(this, _extends({
  9263. type: Shape.RECT,
  9264. style: runtime.enableCSSParsing ? _extends({
  9265. x: '',
  9266. y: '',
  9267. width: '',
  9268. height: '',
  9269. radius: ''
  9270. }, style) : _extends({}, style)
  9271. }, rest)) || this;
  9272. }
  9273. return Rect;
  9274. }(DisplayObject);
  9275. var _excluded$b = ["style"];
  9276. /**
  9277. * <text> @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextElement
  9278. */
  9279. var Text = /*#__PURE__*/function (_DisplayObject) {
  9280. _inheritsLoose(Text, _DisplayObject);
  9281. /**
  9282. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement#constants
  9283. */
  9284. // LENGTHADJUST_SPACING: number = 1;
  9285. // LENGTHADJUST_SPACINGANDGLYPHS: number = 2;
  9286. // LENGTHADJUST_UNKNOWN: number = 0;
  9287. function Text(_temp) {
  9288. var _ref = _temp === void 0 ? {} : _temp,
  9289. style = _ref.style,
  9290. rest = _objectWithoutPropertiesLoose(_ref, _excluded$b);
  9291. return _DisplayObject.call(this, _extends({
  9292. type: Shape.TEXT,
  9293. style: runtime.enableCSSParsing ? _extends({
  9294. x: '',
  9295. y: '',
  9296. text: '',
  9297. fontSize: '',
  9298. fontFamily: '',
  9299. fontStyle: '',
  9300. fontWeight: '',
  9301. fontVariant: '',
  9302. textAlign: '',
  9303. textBaseline: '',
  9304. textTransform: '',
  9305. fill: 'black',
  9306. letterSpacing: '',
  9307. lineHeight: '',
  9308. miterLimit: '',
  9309. // whiteSpace: 'pre',
  9310. wordWrap: false,
  9311. wordWrapWidth: 0,
  9312. leading: 0,
  9313. dx: '',
  9314. dy: '',
  9315. isBillboard: false,
  9316. sizeAttenuation: true
  9317. }, style) : _extends({
  9318. fill: 'black'
  9319. }, style),
  9320. initialParsedStyle: runtime.enableCSSParsing ? {} : {
  9321. x: 0,
  9322. y: 0,
  9323. fontSize: 16,
  9324. fontFamily: 'sans-serif',
  9325. fontStyle: 'normal',
  9326. fontWeight: 'normal',
  9327. fontVariant: 'normal',
  9328. lineHeight: 0,
  9329. letterSpacing: 0,
  9330. textBaseline: 'alphabetic',
  9331. textAlign: 'start',
  9332. wordWrap: false,
  9333. wordWrapWidth: 0,
  9334. leading: 0,
  9335. dx: 0,
  9336. dy: 0,
  9337. isBillboard: false,
  9338. sizeAttenuation: true
  9339. }
  9340. }, rest)) || this;
  9341. }
  9342. // lengthAdjust: SVGAnimatedEnumeration;
  9343. // textLength: SVGAnimatedLength;
  9344. // getCharNumAtPosition(point?: DOMPointInit): number {
  9345. // throw new Error('Method not implemented.');
  9346. // }
  9347. /**
  9348. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement
  9349. */
  9350. var _proto = Text.prototype;
  9351. _proto.getComputedTextLength = function getComputedTextLength() {
  9352. var _this$parsedStyle$met;
  9353. return ((_this$parsedStyle$met = this.parsedStyle.metrics) === null || _this$parsedStyle$met === void 0 ? void 0 : _this$parsedStyle$met.maxLineWidth) || 0;
  9354. }
  9355. // getEndPositionOfChar(charnum: number): DOMPoint {
  9356. // throw new Error('Method not implemented.');
  9357. // }
  9358. // getExtentOfChar(charnum: number): DOMRect {
  9359. // throw new Error('Method not implemented.');
  9360. // }
  9361. // getNumberOfChars(): number {
  9362. // throw new Error('Method not implemented.');
  9363. // }
  9364. // getRotationOfChar(charnum: number): number {
  9365. // throw new Error('Method not implemented.');
  9366. // }
  9367. // getStartPositionOfChar(charnum: number): DOMPoint {
  9368. // throw new Error('Method not implemented.');
  9369. // }
  9370. // getSubStringLength(charnum: number, nchars: number): number {
  9371. // throw new Error('Method not implemented.');
  9372. // }
  9373. // selectSubString(charnum: number, nchars: number): void {
  9374. // throw new Error('Method not implemented.');
  9375. // }
  9376. ;
  9377. _proto.getLineBoundingRects = function getLineBoundingRects() {
  9378. var _this$parsedStyle$met2;
  9379. return ((_this$parsedStyle$met2 = this.parsedStyle.metrics) === null || _this$parsedStyle$met2 === void 0 ? void 0 : _this$parsedStyle$met2.lineMetrics) || [];
  9380. };
  9381. _proto.isOverflowing = function isOverflowing() {
  9382. return !!this.parsedStyle.isOverflowing;
  9383. };
  9384. return Text;
  9385. }(DisplayObject);
  9386. /**
  9387. * Blink used them in code generation(css_properties.json5)
  9388. */
  9389. var BUILT_IN_PROPERTIES = [{
  9390. /**
  9391. * used in CSS Layout API
  9392. * eg. `display: 'flex'`
  9393. */
  9394. n: 'display',
  9395. k: ['none']
  9396. }, {
  9397. /**
  9398. * range [0.0, 1.0]
  9399. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity
  9400. */
  9401. n: 'opacity',
  9402. int: true,
  9403. inh: true,
  9404. d: '1',
  9405. syntax: PropertySyntax.OPACITY_VALUE
  9406. }, {
  9407. /**
  9408. * inheritable, range [0.0, 1.0]
  9409. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity
  9410. * @see https://svgwg.org/svg2-draft/painting.html#FillOpacity
  9411. */
  9412. n: 'fillOpacity',
  9413. int: true,
  9414. inh: true,
  9415. d: '1',
  9416. syntax: PropertySyntax.OPACITY_VALUE
  9417. }, {
  9418. /**
  9419. * inheritable, range [0.0, 1.0]
  9420. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity
  9421. * @see https://svgwg.org/svg2-draft/painting.html#StrokeOpacity
  9422. */
  9423. n: 'strokeOpacity',
  9424. int: true,
  9425. inh: true,
  9426. d: '1',
  9427. syntax: PropertySyntax.OPACITY_VALUE
  9428. }, {
  9429. /**
  9430. * background-color is not inheritable
  9431. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
  9432. */
  9433. n: 'fill',
  9434. int: true,
  9435. k: ['none'],
  9436. d: 'none',
  9437. syntax: PropertySyntax.PAINT
  9438. }, {
  9439. n: 'fillRule',
  9440. k: ['nonzero', 'evenodd'],
  9441. d: 'nonzero'
  9442. },
  9443. /**
  9444. * default to none
  9445. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke#usage_notes
  9446. */
  9447. {
  9448. n: 'stroke',
  9449. int: true,
  9450. k: ['none'],
  9451. d: 'none',
  9452. syntax: PropertySyntax.PAINT,
  9453. /**
  9454. * Stroke 'none' won't affect geometry but others will.
  9455. */
  9456. l: true
  9457. }, {
  9458. n: 'shadowType',
  9459. k: ['inner', 'outer', 'both'],
  9460. d: 'outer',
  9461. l: true
  9462. }, {
  9463. n: 'shadowColor',
  9464. int: true,
  9465. syntax: PropertySyntax.COLOR
  9466. }, {
  9467. n: 'shadowOffsetX',
  9468. int: true,
  9469. l: true,
  9470. d: '0',
  9471. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9472. }, {
  9473. n: 'shadowOffsetY',
  9474. int: true,
  9475. l: true,
  9476. d: '0',
  9477. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9478. }, {
  9479. n: 'shadowBlur',
  9480. int: true,
  9481. l: true,
  9482. d: '0',
  9483. syntax: PropertySyntax.SHADOW_BLUR
  9484. }, {
  9485. /**
  9486. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width
  9487. */
  9488. n: 'lineWidth',
  9489. int: true,
  9490. inh: true,
  9491. d: '1',
  9492. l: true,
  9493. a: ['strokeWidth'],
  9494. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9495. }, {
  9496. n: 'increasedLineWidthForHitTesting',
  9497. inh: true,
  9498. d: '0',
  9499. l: true,
  9500. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9501. }, {
  9502. n: 'lineJoin',
  9503. inh: true,
  9504. l: true,
  9505. a: ['strokeLinejoin'],
  9506. k: ['miter', 'bevel', 'round'],
  9507. d: 'miter'
  9508. }, {
  9509. n: 'lineCap',
  9510. inh: true,
  9511. l: true,
  9512. a: ['strokeLinecap'],
  9513. k: ['butt', 'round', 'square'],
  9514. d: 'butt'
  9515. }, {
  9516. n: 'lineDash',
  9517. int: true,
  9518. inh: true,
  9519. k: ['none'],
  9520. a: ['strokeDasharray'],
  9521. syntax: PropertySyntax.LENGTH_PERCENTAGE_12
  9522. }, {
  9523. n: 'lineDashOffset',
  9524. int: true,
  9525. inh: true,
  9526. d: '0',
  9527. a: ['strokeDashoffset'],
  9528. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9529. }, {
  9530. n: 'offsetPath',
  9531. syntax: PropertySyntax.DEFINED_PATH
  9532. }, {
  9533. n: 'offsetDistance',
  9534. int: true,
  9535. syntax: PropertySyntax.OFFSET_DISTANCE
  9536. }, {
  9537. n: 'dx',
  9538. int: true,
  9539. l: true,
  9540. d: '0',
  9541. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9542. }, {
  9543. n: 'dy',
  9544. int: true,
  9545. l: true,
  9546. d: '0',
  9547. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9548. }, {
  9549. n: 'zIndex',
  9550. ind: true,
  9551. int: true,
  9552. d: '0',
  9553. k: ['auto'],
  9554. syntax: PropertySyntax.Z_INDEX
  9555. }, {
  9556. n: 'visibility',
  9557. k: ['visible', 'hidden'],
  9558. ind: true,
  9559. inh: true,
  9560. /**
  9561. * support interpolation
  9562. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#interpolation
  9563. */
  9564. int: true,
  9565. d: 'visible'
  9566. }, {
  9567. n: 'pointerEvents',
  9568. inh: true,
  9569. k: ['none', 'auto', 'stroke', 'fill', 'painted', 'visible', 'visiblestroke', 'visiblefill', 'visiblepainted',
  9570. // 'bounding-box',
  9571. 'all'],
  9572. d: 'auto'
  9573. }, {
  9574. n: 'filter',
  9575. ind: true,
  9576. l: true,
  9577. k: ['none'],
  9578. d: 'none',
  9579. syntax: PropertySyntax.FILTER
  9580. }, {
  9581. n: 'clipPath',
  9582. syntax: PropertySyntax.DEFINED_PATH
  9583. }, {
  9584. n: 'textPath',
  9585. syntax: PropertySyntax.DEFINED_PATH
  9586. }, {
  9587. n: 'textPathSide',
  9588. k: ['left', 'right'],
  9589. d: 'left'
  9590. }, {
  9591. n: 'textPathStartOffset',
  9592. l: true,
  9593. d: '0',
  9594. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9595. }, {
  9596. n: 'transform',
  9597. p: 100,
  9598. int: true,
  9599. k: ['none'],
  9600. d: 'none',
  9601. syntax: PropertySyntax.TRANSFORM
  9602. }, {
  9603. n: 'transformOrigin',
  9604. p: 100,
  9605. // int: true,
  9606. d: function d(nodeName) {
  9607. if (nodeName === Shape.CIRCLE || nodeName === Shape.ELLIPSE) {
  9608. return 'center';
  9609. }
  9610. if (nodeName === Shape.TEXT) {
  9611. return 'text-anchor';
  9612. }
  9613. return 'left top';
  9614. },
  9615. l: true,
  9616. syntax: PropertySyntax.TRANSFORM_ORIGIN
  9617. }, {
  9618. n: 'anchor',
  9619. p: 99,
  9620. d: function d(nodeName) {
  9621. if (nodeName === Shape.CIRCLE || nodeName === Shape.ELLIPSE) {
  9622. return '0.5 0.5';
  9623. }
  9624. return '0 0';
  9625. },
  9626. l: true,
  9627. syntax: PropertySyntax.LENGTH_PERCENTAGE_12
  9628. },
  9629. // <circle> & <ellipse>
  9630. {
  9631. n: 'cx',
  9632. int: true,
  9633. d: '0',
  9634. syntax: PropertySyntax.COORDINATE
  9635. }, {
  9636. n: 'cy',
  9637. int: true,
  9638. d: '0',
  9639. syntax: PropertySyntax.COORDINATE
  9640. }, {
  9641. n: 'cz',
  9642. int: true,
  9643. d: '0',
  9644. syntax: PropertySyntax.COORDINATE
  9645. }, {
  9646. n: 'r',
  9647. int: true,
  9648. l: true,
  9649. d: '0',
  9650. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9651. }, {
  9652. n: 'rx',
  9653. int: true,
  9654. l: true,
  9655. d: '0',
  9656. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9657. }, {
  9658. n: 'ry',
  9659. int: true,
  9660. l: true,
  9661. d: '0',
  9662. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9663. },
  9664. // Rect Image Group
  9665. {
  9666. // x in local space
  9667. n: 'x',
  9668. int: true,
  9669. d: '0',
  9670. syntax: PropertySyntax.COORDINATE
  9671. }, {
  9672. // y in local space
  9673. n: 'y',
  9674. int: true,
  9675. d: '0',
  9676. syntax: PropertySyntax.COORDINATE
  9677. }, {
  9678. // z in local space
  9679. n: 'z',
  9680. int: true,
  9681. d: '0',
  9682. syntax: PropertySyntax.COORDINATE
  9683. }, {
  9684. n: 'width',
  9685. int: true,
  9686. l: true,
  9687. /**
  9688. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
  9689. */
  9690. k: ['auto', 'fit-content', 'min-content', 'max-content'],
  9691. d: '0',
  9692. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9693. }, {
  9694. n: 'height',
  9695. int: true,
  9696. l: true,
  9697. /**
  9698. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/height
  9699. */
  9700. k: ['auto', 'fit-content', 'min-content', 'max-content'],
  9701. d: '0',
  9702. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9703. }, {
  9704. n: 'radius',
  9705. int: true,
  9706. l: true,
  9707. d: '0',
  9708. syntax: PropertySyntax.LENGTH_PERCENTAGE_14
  9709. },
  9710. // Line
  9711. {
  9712. n: 'x1',
  9713. int: true,
  9714. l: true,
  9715. syntax: PropertySyntax.COORDINATE
  9716. }, {
  9717. n: 'y1',
  9718. int: true,
  9719. l: true,
  9720. syntax: PropertySyntax.COORDINATE
  9721. }, {
  9722. n: 'z1',
  9723. int: true,
  9724. l: true,
  9725. syntax: PropertySyntax.COORDINATE
  9726. }, {
  9727. n: 'x2',
  9728. int: true,
  9729. l: true,
  9730. syntax: PropertySyntax.COORDINATE
  9731. }, {
  9732. n: 'y2',
  9733. int: true,
  9734. l: true,
  9735. syntax: PropertySyntax.COORDINATE
  9736. }, {
  9737. n: 'z2',
  9738. int: true,
  9739. l: true,
  9740. syntax: PropertySyntax.COORDINATE
  9741. },
  9742. // Path
  9743. {
  9744. n: 'path',
  9745. int: true,
  9746. l: true,
  9747. d: '',
  9748. a: ['d'],
  9749. syntax: PropertySyntax.PATH,
  9750. p: 50
  9751. },
  9752. // Polyline & Polygon
  9753. {
  9754. n: 'points',
  9755. /**
  9756. * support interpolation
  9757. */
  9758. int: true,
  9759. l: true,
  9760. syntax: PropertySyntax.LIST_OF_POINTS,
  9761. p: 50
  9762. },
  9763. // Text
  9764. {
  9765. n: 'text',
  9766. l: true,
  9767. d: '',
  9768. syntax: PropertySyntax.TEXT,
  9769. p: 50
  9770. }, {
  9771. n: 'textTransform',
  9772. l: true,
  9773. inh: true,
  9774. k: ['capitalize', 'uppercase', 'lowercase', 'none'],
  9775. d: 'none',
  9776. syntax: PropertySyntax.TEXT_TRANSFORM,
  9777. p: 51 // it must get parsed after text
  9778. }, {
  9779. n: 'font',
  9780. l: true
  9781. }, {
  9782. n: 'fontSize',
  9783. int: true,
  9784. inh: true,
  9785. /**
  9786. * @see https://www.w3schools.com/css/css_font_size.asp
  9787. */
  9788. d: '16px',
  9789. l: true,
  9790. syntax: PropertySyntax.LENGTH_PERCENTAGE
  9791. }, {
  9792. n: 'fontFamily',
  9793. l: true,
  9794. inh: true,
  9795. d: 'sans-serif'
  9796. }, {
  9797. n: 'fontStyle',
  9798. l: true,
  9799. inh: true,
  9800. k: ['normal', 'italic', 'oblique'],
  9801. d: 'normal'
  9802. }, {
  9803. n: 'fontWeight',
  9804. l: true,
  9805. inh: true,
  9806. k: ['normal', 'bold', 'bolder', 'lighter'],
  9807. d: 'normal'
  9808. }, {
  9809. n: 'fontVariant',
  9810. l: true,
  9811. inh: true,
  9812. k: ['normal', 'small-caps'],
  9813. d: 'normal'
  9814. }, {
  9815. n: 'lineHeight',
  9816. l: true,
  9817. syntax: PropertySyntax.LENGTH,
  9818. int: true,
  9819. d: '0'
  9820. }, {
  9821. n: 'letterSpacing',
  9822. l: true,
  9823. syntax: PropertySyntax.LENGTH,
  9824. int: true,
  9825. d: '0'
  9826. }, {
  9827. n: 'miterLimit',
  9828. l: true,
  9829. syntax: PropertySyntax.NUMBER,
  9830. d: function d(nodeName) {
  9831. if (nodeName === Shape.PATH || nodeName === Shape.POLYGON || nodeName === Shape.POLYLINE) {
  9832. return '4';
  9833. }
  9834. return '10';
  9835. }
  9836. }, {
  9837. n: 'wordWrap',
  9838. l: true
  9839. }, {
  9840. n: 'wordWrapWidth',
  9841. l: true
  9842. }, {
  9843. n: 'maxLines',
  9844. l: true
  9845. }, {
  9846. n: 'textOverflow',
  9847. l: true,
  9848. d: 'clip'
  9849. }, {
  9850. n: 'leading',
  9851. l: true
  9852. }, {
  9853. n: 'textBaseline',
  9854. l: true,
  9855. inh: true,
  9856. k: ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'],
  9857. d: 'alphabetic'
  9858. }, {
  9859. n: 'textAlign',
  9860. l: true,
  9861. inh: true,
  9862. k: ['start', 'center', 'middle', 'end', 'left', 'right'],
  9863. d: 'start'
  9864. },
  9865. // {
  9866. // n: 'whiteSpace',
  9867. // l: true,
  9868. // },
  9869. {
  9870. n: 'markerStart',
  9871. syntax: PropertySyntax.MARKER
  9872. }, {
  9873. n: 'markerEnd',
  9874. syntax: PropertySyntax.MARKER
  9875. }, {
  9876. n: 'markerMid',
  9877. syntax: PropertySyntax.MARKER
  9878. }, {
  9879. n: 'markerStartOffset',
  9880. syntax: PropertySyntax.LENGTH,
  9881. l: true,
  9882. int: true,
  9883. d: '0'
  9884. }, {
  9885. n: 'markerEndOffset',
  9886. syntax: PropertySyntax.LENGTH,
  9887. l: true,
  9888. int: true,
  9889. d: '0'
  9890. }];
  9891. var GEOMETRY_ATTRIBUTE_NAMES = BUILT_IN_PROPERTIES.filter(function (n) {
  9892. return !!n.l;
  9893. }).map(function (n) {
  9894. return n.n;
  9895. });
  9896. var propertyMetadataCache = {};
  9897. var unresolvedProperties = new WeakMap();
  9898. // const uniqueAttributeSet = new Set<string>();
  9899. // const tmpVec3a = vec3.create();
  9900. // const tmpVec3b = vec3.create();
  9901. // const tmpVec3c = vec3.create();
  9902. var isPropertyResolved = function isPropertyResolved(object, name) {
  9903. var properties = unresolvedProperties.get(object);
  9904. if (!properties || properties.length === 0) {
  9905. return true;
  9906. }
  9907. return properties.includes(name);
  9908. };
  9909. var DefaultStyleValueRegistry = /*#__PURE__*/function () {
  9910. /**
  9911. * need recalc later
  9912. */
  9913. // dirty = false;
  9914. function DefaultStyleValueRegistry() {
  9915. var _this = this;
  9916. BUILT_IN_PROPERTIES.forEach(function (property) {
  9917. _this.registerMetadata(property);
  9918. });
  9919. }
  9920. var _proto = DefaultStyleValueRegistry.prototype;
  9921. _proto.registerMetadata = function registerMetadata(metadata) {
  9922. [metadata.n].concat(metadata.a || []).forEach(function (name) {
  9923. propertyMetadataCache[name] = metadata;
  9924. });
  9925. };
  9926. _proto.unregisterMetadata = function unregisterMetadata(name) {
  9927. delete propertyMetadataCache[name];
  9928. };
  9929. _proto.getPropertySyntax = function getPropertySyntax(syntax) {
  9930. return runtime.CSSPropertySyntaxFactory[syntax];
  9931. }
  9932. /**
  9933. * * parse value, eg.
  9934. * fill: 'red' => CSSRGB
  9935. * translateX: '10px' => CSSUnitValue { unit: 'px', value: 10 }
  9936. * fontSize: '2em' => { unit: 'px', value: 32 }
  9937. *
  9938. * * calculate used value
  9939. * * post process
  9940. */;
  9941. _proto.processProperties = function processProperties(object, attributes, options) {
  9942. var _this2 = this;
  9943. if (options === void 0) {
  9944. options = {
  9945. skipUpdateAttribute: false,
  9946. skipParse: false,
  9947. forceUpdateGeometry: false,
  9948. usedAttributes: []
  9949. };
  9950. }
  9951. if (!runtime.enableCSSParsing) {
  9952. Object.assign(object.attributes, attributes);
  9953. var _attributeNames = Object.keys(attributes);
  9954. // clipPath
  9955. var oldClipPath = object.parsedStyle.clipPath;
  9956. var oldOffsetPath = object.parsedStyle.offsetPath;
  9957. object.parsedStyle = Object.assign(object.parsedStyle, attributes);
  9958. var _needUpdateGeometry = !!options.forceUpdateGeometry;
  9959. if (!_needUpdateGeometry) {
  9960. for (var i = 0; i < GEOMETRY_ATTRIBUTE_NAMES.length; i++) {
  9961. if (GEOMETRY_ATTRIBUTE_NAMES[i] in attributes) {
  9962. _needUpdateGeometry = true;
  9963. break;
  9964. }
  9965. }
  9966. }
  9967. if (attributes.fill) {
  9968. object.parsedStyle.fill = parseColor(attributes.fill);
  9969. }
  9970. if (attributes.stroke) {
  9971. object.parsedStyle.stroke = parseColor(attributes.stroke);
  9972. }
  9973. if (attributes.shadowColor) {
  9974. object.parsedStyle.shadowColor = parseColor(attributes.shadowColor);
  9975. }
  9976. if (attributes.filter) {
  9977. object.parsedStyle.filter = parseFilter(attributes.filter);
  9978. }
  9979. // Rect
  9980. // @ts-ignore
  9981. if (!isNil(attributes.radius)) {
  9982. // @ts-ignore
  9983. object.parsedStyle.radius = parseDimensionArrayFormat(
  9984. // @ts-ignore
  9985. attributes.radius, 4);
  9986. }
  9987. // Polyline
  9988. if (!isNil(attributes.lineDash)) {
  9989. object.parsedStyle.lineDash = parseDimensionArrayFormat(attributes.lineDash, 2);
  9990. }
  9991. // @ts-ignore
  9992. if (attributes.points) {
  9993. // @ts-ignore
  9994. object.parsedStyle.points = parsePoints(attributes.points, object);
  9995. }
  9996. // Path
  9997. // @ts-ignore
  9998. if (attributes.path === '') {
  9999. object.parsedStyle.path = _extends({}, EMPTY_PARSED_PATH);
  10000. }
  10001. // @ts-ignore
  10002. if (attributes.path) {
  10003. object.parsedStyle.path = parsePath(
  10004. // @ts-ignore
  10005. attributes.path, object);
  10006. }
  10007. // Text
  10008. if (attributes.textTransform) {
  10009. runtime.CSSPropertySyntaxFactory['<text-transform>'].calculator(null, null, {
  10010. value: attributes.textTransform
  10011. }, object, null);
  10012. }
  10013. if (attributes.clipPath) {
  10014. runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('clipPath', oldClipPath, attributes.clipPath, object, this);
  10015. }
  10016. if (attributes.offsetPath) {
  10017. runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('offsetPath', oldOffsetPath, attributes.offsetPath, object, this);
  10018. }
  10019. if (attributes.anchor) {
  10020. object.parsedStyle.anchor = parseDimensionArrayFormat(
  10021. // @ts-ignorex
  10022. attributes.anchor, 2);
  10023. }
  10024. if (attributes.transform) {
  10025. object.parsedStyle.transform = parseTransform(attributes.transform);
  10026. }
  10027. if (attributes.transformOrigin) {
  10028. object.parsedStyle.transformOrigin = parseTransformOrigin(attributes.transformOrigin);
  10029. }
  10030. // Marker
  10031. // @ts-ignore
  10032. if (attributes.markerStart) {
  10033. // @ts-ignore
  10034. object.parsedStyle.markerStart = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
  10035. // @ts-ignore
  10036. attributes.markerStart,
  10037. // @ts-ignore
  10038. attributes.markerStart, null, null);
  10039. }
  10040. // @ts-ignore
  10041. if (attributes.markerEnd) {
  10042. // @ts-ignore
  10043. object.parsedStyle.markerEnd = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
  10044. // @ts-ignore
  10045. attributes.markerEnd,
  10046. // @ts-ignore
  10047. attributes.markerEnd, null, null);
  10048. }
  10049. // @ts-ignore
  10050. if (attributes.markerMid) {
  10051. // @ts-ignore
  10052. object.parsedStyle.markerMid = runtime.CSSPropertySyntaxFactory['<marker>'].calculator('',
  10053. // @ts-ignore
  10054. attributes.markerMid,
  10055. // @ts-ignore
  10056. attributes.markerMid, null, null);
  10057. }
  10058. if (
  10059. // Circle & Ellipse
  10060. (object.nodeName === Shape.CIRCLE || object.nodeName === Shape.ELLIPSE) && (
  10061. // @ts-ignore
  10062. !isNil(attributes.cx) ||
  10063. // @ts-ignore
  10064. !isNil(attributes.cy)) || (object.nodeName === Shape.RECT || object.nodeName === Shape.IMAGE || object.nodeName === Shape.GROUP || object.nodeName === Shape.HTML || object.nodeName === Shape.TEXT || object.nodeName === Shape.MESH) && (
  10065. // @ts-ignore
  10066. !isNil(attributes.x) ||
  10067. // @ts-ignore
  10068. !isNil(attributes.y) ||
  10069. // @ts-ignore
  10070. !isNil(attributes.z)) ||
  10071. // Line
  10072. object.nodeName === Shape.LINE && (
  10073. // @ts-ignore
  10074. !isNil(attributes.x1) ||
  10075. // @ts-ignore
  10076. !isNil(attributes.y1) ||
  10077. // @ts-ignore
  10078. !isNil(attributes.z1) ||
  10079. // @ts-ignore
  10080. !isNil(attributes.x2) ||
  10081. // @ts-ignore
  10082. !isNil(attributes.y2) ||
  10083. // @ts-ignore
  10084. !isNil(attributes.z2))) {
  10085. runtime.CSSPropertySyntaxFactory['<coordinate>'].postProcessor(object, _attributeNames);
  10086. }
  10087. if (!isNil(attributes.zIndex)) {
  10088. runtime.CSSPropertySyntaxFactory['<z-index>'].postProcessor(object, _attributeNames);
  10089. }
  10090. // @ts-ignore
  10091. if (attributes.path) {
  10092. runtime.CSSPropertySyntaxFactory['<path>'].postProcessor(object, _attributeNames);
  10093. }
  10094. // @ts-ignore
  10095. if (attributes.points) {
  10096. runtime.CSSPropertySyntaxFactory['<list-of-points>'].postProcessor(object, _attributeNames);
  10097. }
  10098. if (!isNil(attributes.offsetDistance)) {
  10099. runtime.CSSPropertySyntaxFactory['<offset-distance>'].postProcessor(object, _attributeNames);
  10100. }
  10101. if (attributes.transform) {
  10102. runtime.CSSPropertySyntaxFactory['<transform>'].postProcessor(object, _attributeNames);
  10103. }
  10104. if (_needUpdateGeometry) {
  10105. this.updateGeometry(object);
  10106. }
  10107. return;
  10108. }
  10109. var _options = options,
  10110. skipUpdateAttribute = _options.skipUpdateAttribute,
  10111. skipParse = _options.skipParse,
  10112. forceUpdateGeometry = _options.forceUpdateGeometry,
  10113. usedAttributes = _options.usedAttributes;
  10114. var needUpdateGeometry = forceUpdateGeometry;
  10115. var attributeNames = Object.keys(attributes);
  10116. attributeNames.forEach(function (attributeName) {
  10117. var _propertyMetadataCach;
  10118. if (!skipUpdateAttribute) {
  10119. object.attributes[attributeName] = attributes[attributeName];
  10120. }
  10121. if (!needUpdateGeometry && ((_propertyMetadataCach = propertyMetadataCache[attributeName]) === null || _propertyMetadataCach === void 0 ? void 0 : _propertyMetadataCach.l)) {
  10122. needUpdateGeometry = true;
  10123. }
  10124. });
  10125. if (!skipParse) {
  10126. attributeNames.forEach(function (name) {
  10127. object.computedStyle[name] = _this2.parseProperty(name, object.attributes[name], object);
  10128. });
  10129. }
  10130. // let hasUnresolvedProperties = false;
  10131. // parse according to priority
  10132. // path 50
  10133. // points 50
  10134. // text 50
  10135. // textTransform 51
  10136. // anchor 99
  10137. // transform 100
  10138. // transformOrigin 100
  10139. if (usedAttributes === null || usedAttributes === void 0 ? void 0 : usedAttributes.length) {
  10140. // uniqueAttributeSet.clear();
  10141. attributeNames = Array.from(new Set(attributeNames.concat(usedAttributes)));
  10142. }
  10143. // [
  10144. // 'path',
  10145. // 'points',
  10146. // 'text',
  10147. // 'textTransform',
  10148. // 'anchor',
  10149. // 'transform',
  10150. // 'transformOrigin',
  10151. // ].forEach((name) => {
  10152. // const index = attributeNames.indexOf(name);
  10153. // if (index > -1) {
  10154. // attributeNames.splice(index, 1);
  10155. // attributeNames.push(name);
  10156. // }
  10157. // });
  10158. attributeNames.forEach(function (name) {
  10159. // some style props maybe deleted after parsing such as `anchor` in Text
  10160. if (name in object.computedStyle) {
  10161. object.parsedStyle[name] = _this2.computeProperty(name, object.computedStyle[name], object);
  10162. }
  10163. });
  10164. // if (hasUnresolvedProperties) {
  10165. // this.dirty = true;
  10166. // return;
  10167. // }
  10168. // update geometry
  10169. if (needUpdateGeometry) {
  10170. // object.geometry.dirty = true;
  10171. // runtime.sceneGraphService.dirtifyToRoot(object);
  10172. this.updateGeometry(object);
  10173. }
  10174. attributeNames.forEach(function (name) {
  10175. if (name in object.parsedStyle) {
  10176. _this2.postProcessProperty(name, object, attributeNames);
  10177. }
  10178. });
  10179. if (runtime.enableCSSParsing && object.children.length) {
  10180. attributeNames.forEach(function (name) {
  10181. if (name in object.parsedStyle && _this2.isPropertyInheritable(name)) {
  10182. // update children's inheritable
  10183. object.children.forEach(function (child) {
  10184. child.internalSetAttribute(name, null, {
  10185. skipUpdateAttribute: true,
  10186. skipParse: true
  10187. });
  10188. });
  10189. }
  10190. });
  10191. }
  10192. }
  10193. /**
  10194. * string -> parsed value
  10195. */;
  10196. _proto.parseProperty = function parseProperty(name, value, object) {
  10197. var metadata = propertyMetadataCache[name];
  10198. var computed = value;
  10199. if (value === '' || isNil(value)) {
  10200. value = 'unset';
  10201. }
  10202. if (value === 'unset' || value === 'initial' || value === 'inherit') {
  10203. // computed = new CSSKeywordValue(value);
  10204. computed = getOrCreateKeyword(value);
  10205. } else {
  10206. if (metadata) {
  10207. var keywords = metadata.k,
  10208. syntax = metadata.syntax;
  10209. var handler = syntax && this.getPropertySyntax(syntax);
  10210. // use keywords
  10211. if (keywords && keywords.indexOf(value) > -1) {
  10212. // computed = new CSSKeywordValue(value);
  10213. computed = getOrCreateKeyword(value);
  10214. } else if (handler && handler.parser) {
  10215. // try to parse it to CSSStyleValue, eg. '10px' -> CSS.px(10)
  10216. computed = handler.parser(value, object);
  10217. }
  10218. }
  10219. }
  10220. return computed;
  10221. }
  10222. /**
  10223. * computed value -> used value
  10224. */;
  10225. _proto.computeProperty = function computeProperty(name, computed, object) {
  10226. var metadata = propertyMetadataCache[name];
  10227. var isDocumentElement = object.id === 'g-root';
  10228. // let used: CSSStyleValue = computed instanceof CSSStyleValue ? computed.clone() : computed;
  10229. var used = computed;
  10230. if (metadata) {
  10231. var syntax = metadata.syntax,
  10232. inherited = metadata.inh,
  10233. defaultValue = metadata.d;
  10234. if (computed instanceof CSSKeywordValue) {
  10235. var value = computed.value;
  10236. /**
  10237. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/unset
  10238. */
  10239. if (value === 'unset') {
  10240. if (inherited && !isDocumentElement) {
  10241. value = 'inherit';
  10242. } else {
  10243. value = 'initial';
  10244. }
  10245. }
  10246. if (value === 'initial') {
  10247. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial
  10248. if (!isNil(defaultValue)) {
  10249. computed = this.parseProperty(name, isFunction(defaultValue) ? defaultValue(object.nodeName) : defaultValue, object);
  10250. }
  10251. } else if (value === 'inherit') {
  10252. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/inherit
  10253. // behave like `inherit`
  10254. var resolved = this.tryToResolveProperty(object, name, {
  10255. inherited: true
  10256. });
  10257. if (!isNil(resolved)) {
  10258. // object.parsedStyle[name] = resolved;
  10259. // return false;
  10260. return resolved;
  10261. } else {
  10262. this.addUnresolveProperty(object, name);
  10263. return;
  10264. }
  10265. }
  10266. }
  10267. var handler = syntax && this.getPropertySyntax(syntax);
  10268. if (handler && handler.calculator) {
  10269. // convert computed value to used value
  10270. var oldParsedValue = object.parsedStyle[name];
  10271. used = handler.calculator(name, oldParsedValue, computed, object, this);
  10272. } else if (computed instanceof CSSKeywordValue) {
  10273. used = computed.value;
  10274. } else {
  10275. used = computed;
  10276. }
  10277. }
  10278. // object.parsedStyle[name] = used;
  10279. // return false;
  10280. return used;
  10281. };
  10282. _proto.postProcessProperty = function postProcessProperty(name, object, attributes) {
  10283. var metadata = propertyMetadataCache[name];
  10284. if (metadata && metadata.syntax) {
  10285. var handler = metadata.syntax && this.getPropertySyntax(metadata.syntax);
  10286. var propertyHandler = handler;
  10287. if (propertyHandler && propertyHandler.postProcessor) {
  10288. propertyHandler.postProcessor(object, attributes);
  10289. }
  10290. }
  10291. }
  10292. /**
  10293. * resolve later
  10294. */;
  10295. _proto.addUnresolveProperty = function addUnresolveProperty(object, name) {
  10296. var properties = unresolvedProperties.get(object);
  10297. if (!properties) {
  10298. unresolvedProperties.set(object, []);
  10299. properties = unresolvedProperties.get(object);
  10300. }
  10301. if (properties.indexOf(name) === -1) {
  10302. properties.push(name);
  10303. }
  10304. };
  10305. _proto.tryToResolveProperty = function tryToResolveProperty(object, name, options) {
  10306. if (options === void 0) {
  10307. options = {};
  10308. }
  10309. var _options2 = options,
  10310. inherited = _options2.inherited;
  10311. if (inherited) {
  10312. if (object.parentElement && isPropertyResolved(object.parentElement, name)) {
  10313. // const computedValue = object.parentElement.computedStyle[name];
  10314. var usedValue = object.parentElement.parsedStyle[name];
  10315. if (
  10316. // usedValue instanceof CSSKeywordValue &&
  10317. usedValue === 'unset' || usedValue === 'initial' || usedValue === 'inherit') {
  10318. return;
  10319. }
  10320. // else if (
  10321. // usedValue instanceof CSSUnitValue &&
  10322. // CSSUnitValue.isRelativeUnit(usedValue.unit)
  10323. // ) {
  10324. // return false;
  10325. // }
  10326. return usedValue;
  10327. }
  10328. }
  10329. return;
  10330. };
  10331. _proto.recalc = function recalc(object) {
  10332. var properties = unresolvedProperties.get(object);
  10333. if (properties && properties.length) {
  10334. var attributes = {};
  10335. properties.forEach(function (property) {
  10336. attributes[property] = object.attributes[property];
  10337. });
  10338. this.processProperties(object, attributes);
  10339. unresolvedProperties.delete(object);
  10340. }
  10341. }
  10342. /**
  10343. * update geometry when relative props changed,
  10344. * eg. r of Circle, width/height of Rect
  10345. */;
  10346. _proto.updateGeometry = function updateGeometry(object) {
  10347. var nodeName = object.nodeName;
  10348. var geometryUpdater = runtime.geometryUpdaterFactory[nodeName];
  10349. if (geometryUpdater) {
  10350. var geometry = object.geometry;
  10351. if (!geometry.contentBounds) {
  10352. geometry.contentBounds = new AABB();
  10353. }
  10354. if (!geometry.renderBounds) {
  10355. geometry.renderBounds = new AABB();
  10356. }
  10357. var parsedStyle = object.parsedStyle;
  10358. var _geometryUpdater$upda = geometryUpdater.update(parsedStyle, object),
  10359. width = _geometryUpdater$upda.width,
  10360. height = _geometryUpdater$upda.height,
  10361. _geometryUpdater$upda2 = _geometryUpdater$upda.depth,
  10362. depth = _geometryUpdater$upda2 === void 0 ? 0 : _geometryUpdater$upda2,
  10363. _geometryUpdater$upda3 = _geometryUpdater$upda.offsetX,
  10364. offsetX = _geometryUpdater$upda3 === void 0 ? 0 : _geometryUpdater$upda3,
  10365. _geometryUpdater$upda4 = _geometryUpdater$upda.offsetY,
  10366. offsetY = _geometryUpdater$upda4 === void 0 ? 0 : _geometryUpdater$upda4,
  10367. _geometryUpdater$upda5 = _geometryUpdater$upda.offsetZ,
  10368. offsetZ = _geometryUpdater$upda5 === void 0 ? 0 : _geometryUpdater$upda5;
  10369. // init with content box
  10370. var halfExtents = [Math.abs(width) / 2, Math.abs(height) / 2, depth / 2];
  10371. // const halfExtents = vec3.set(
  10372. // tmpVec3a,
  10373. // Math.abs(width) / 2,
  10374. // Math.abs(height) / 2,
  10375. // depth / 2,
  10376. // );
  10377. // anchor is center by default, don't account for lineWidth here
  10378. var stroke = parsedStyle.stroke,
  10379. lineWidth = parsedStyle.lineWidth,
  10380. increasedLineWidthForHitTesting = parsedStyle.increasedLineWidthForHitTesting,
  10381. shadowType = parsedStyle.shadowType,
  10382. shadowColor = parsedStyle.shadowColor,
  10383. _parsedStyle$filter = parsedStyle.filter,
  10384. filter = _parsedStyle$filter === void 0 ? [] : _parsedStyle$filter,
  10385. transformOrigin = parsedStyle.transformOrigin;
  10386. var anchor = parsedStyle.anchor;
  10387. // <Text> use textAlign & textBaseline instead of anchor
  10388. if (nodeName === Shape.TEXT) {
  10389. delete parsedStyle.anchor;
  10390. } else if (nodeName === Shape.MESH) {
  10391. parsedStyle.anchor[2] = 0.5;
  10392. }
  10393. 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];
  10394. // const center = vec3.set(
  10395. // tmpVec3b,
  10396. // ((1 - ((anchor && anchor[0]) || 0) * 2) * width) / 2 + offsetX,
  10397. // ((1 - ((anchor && anchor[1]) || 0) * 2) * height) / 2 + offsetY,
  10398. // (1 - ((anchor && anchor[2]) || 0) * 2) * halfExtents[2] + offsetZ,
  10399. // );
  10400. // update geometry's AABB
  10401. geometry.contentBounds.update(center, halfExtents);
  10402. // @see https://github.molgen.mpg.de/git-mirror/cairo/blob/master/src/cairo-stroke-style.c#L97..L128
  10403. var expansion = nodeName === Shape.POLYLINE || nodeName === Shape.POLYGON || nodeName === Shape.PATH ? Math.SQRT2 : 0.5;
  10404. // if (lineCap?.value === 'square') {
  10405. // expansion = Math.SQRT1_2;
  10406. // }
  10407. // if (lineJoin?.value === 'miter' && expansion < Math.SQRT2 * miterLimit) {
  10408. // expansion = Math.SQRT1_2 * miterLimit;
  10409. // }
  10410. // append border only if stroke existed
  10411. var hasStroke = stroke && !stroke.isNone;
  10412. if (hasStroke) {
  10413. var halfLineWidth = ((lineWidth || 0) + (increasedLineWidthForHitTesting || 0)) * expansion;
  10414. // halfExtents[0] += halfLineWidth[0];
  10415. // halfExtents[1] += halfLineWidth[1];
  10416. halfExtents[0] += halfLineWidth;
  10417. halfExtents[1] += halfLineWidth;
  10418. // vec3.add(
  10419. // halfExtents,
  10420. // halfExtents,
  10421. // vec3.set(tmpVec3c, halfLineWidth, halfLineWidth, 0),
  10422. // );
  10423. }
  10424. geometry.renderBounds.update(center, halfExtents);
  10425. // account for shadow, only support constant value now
  10426. if (shadowColor && shadowType && shadowType !== 'inner') {
  10427. var _geometry$renderBound = geometry.renderBounds,
  10428. min = _geometry$renderBound.min,
  10429. max = _geometry$renderBound.max;
  10430. var shadowBlur = parsedStyle.shadowBlur,
  10431. shadowOffsetX = parsedStyle.shadowOffsetX,
  10432. shadowOffsetY = parsedStyle.shadowOffsetY;
  10433. var shadowBlurInPixels = shadowBlur || 0;
  10434. var shadowOffsetXInPixels = shadowOffsetX || 0;
  10435. var shadowOffsetYInPixels = shadowOffsetY || 0;
  10436. var shadowLeft = min[0] - shadowBlurInPixels + shadowOffsetXInPixels;
  10437. var shadowRight = max[0] + shadowBlurInPixels + shadowOffsetXInPixels;
  10438. var shadowTop = min[1] - shadowBlurInPixels + shadowOffsetYInPixels;
  10439. var shadowBottom = max[1] + shadowBlurInPixels + shadowOffsetYInPixels;
  10440. min[0] = Math.min(min[0], shadowLeft);
  10441. max[0] = Math.max(max[0], shadowRight);
  10442. min[1] = Math.min(min[1], shadowTop);
  10443. max[1] = Math.max(max[1], shadowBottom);
  10444. geometry.renderBounds.setMinMax(min, max);
  10445. }
  10446. // account for filter, eg. blur(5px), drop-shadow()
  10447. filter.forEach(function (_ref) {
  10448. var name = _ref.name,
  10449. params = _ref.params;
  10450. if (name === 'blur') {
  10451. var blurRadius = params[0].value;
  10452. geometry.renderBounds.update(geometry.renderBounds.center, addVec3(geometry.renderBounds.halfExtents, geometry.renderBounds.halfExtents, [blurRadius, blurRadius, 0]));
  10453. } else if (name === 'drop-shadow') {
  10454. var _shadowOffsetX = params[0].value;
  10455. var _shadowOffsetY = params[1].value;
  10456. var _shadowBlur = params[2].value;
  10457. var _geometry$renderBound2 = geometry.renderBounds,
  10458. _min = _geometry$renderBound2.min,
  10459. _max = _geometry$renderBound2.max;
  10460. var _shadowLeft = _min[0] - _shadowBlur + _shadowOffsetX;
  10461. var _shadowRight = _max[0] + _shadowBlur + _shadowOffsetX;
  10462. var _shadowTop = _min[1] - _shadowBlur + _shadowOffsetY;
  10463. var _shadowBottom = _max[1] + _shadowBlur + _shadowOffsetY;
  10464. _min[0] = Math.min(_min[0], _shadowLeft);
  10465. _max[0] = Math.max(_max[0], _shadowRight);
  10466. _min[1] = Math.min(_min[1], _shadowTop);
  10467. _max[1] = Math.max(_max[1], _shadowBottom);
  10468. geometry.renderBounds.setMinMax(_min, _max);
  10469. }
  10470. });
  10471. anchor = parsedStyle.anchor;
  10472. // if (nodeName === Shape.RECT) {
  10473. // account for negative width / height of Rect
  10474. // @see https://github.com/antvis/g/issues/957
  10475. var flipY = width < 0;
  10476. var flipX = height < 0;
  10477. // } else {
  10478. // }
  10479. // set transform origin
  10480. var usedOriginXValue = (flipY ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[0], 0, object) : 0);
  10481. var usedOriginYValue = (flipX ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[1], 1, object) : 0);
  10482. usedOriginXValue = usedOriginXValue - (flipY ? -1 : 1) * (anchor && anchor[0] || 0) * geometry.contentBounds.halfExtents[0] * 2;
  10483. usedOriginYValue = usedOriginYValue - (flipX ? -1 : 1) * (anchor && anchor[1] || 0) * geometry.contentBounds.halfExtents[1] * 2;
  10484. object.setOrigin(usedOriginXValue, usedOriginYValue);
  10485. // FIXME setOrigin may have already dirtified to root.
  10486. runtime.sceneGraphService.dirtifyToRoot(object);
  10487. }
  10488. };
  10489. _proto.isPropertyInheritable = function isPropertyInheritable(name) {
  10490. var metadata = propertyMetadataCache[name];
  10491. if (!metadata) {
  10492. return false;
  10493. }
  10494. return metadata.inh;
  10495. };
  10496. return DefaultStyleValueRegistry;
  10497. }();
  10498. /**
  10499. * Different type of cameras, eg. simple camera used in 2D scene or
  10500. * advanced camera which can do actions & switch between landmarks.
  10501. */
  10502. var CameraType;
  10503. (function (CameraType) {
  10504. /**
  10505. * Performs all the rotational operations with the focal point instead of the camera position.
  10506. * This type of camera is useful in applications(like CAD) where 3D objects are being designed or explored.
  10507. * Camera cannot orbits over the north & south poles.
  10508. * @see http://voxelent.com/tutorial-cameras/
  10509. *
  10510. * In Three.js it's used in OrbitControls.
  10511. * @see https://threejs.org/docs/#examples/zh/controls/OrbitControls
  10512. */
  10513. CameraType[CameraType["ORBITING"] = 0] = "ORBITING";
  10514. /**
  10515. * It's similar to the ORBITING camera, but it allows the camera to orbit over the north or south poles.
  10516. *
  10517. * In Three.js it's used in OrbitControls.
  10518. * @see https://threejs.org/docs/#examples/en/controls/TrackballControls
  10519. */
  10520. CameraType[CameraType["EXPLORING"] = 1] = "EXPLORING";
  10521. /**
  10522. * Performs all the rotational operations with the camera position.
  10523. * It's useful in first person shooting games.
  10524. * Camera cannot orbits over the north & south poles.
  10525. *
  10526. * In Three.js it's used in FirstPersonControls.
  10527. * @see https://threejs.org/docs/#examples/en/controls/FirstPersonControls
  10528. */
  10529. CameraType[CameraType["TRACKING"] = 2] = "TRACKING";
  10530. })(CameraType || (CameraType = {}));
  10531. /**
  10532. * CameraType must be TRACKING
  10533. */
  10534. var CameraTrackingMode;
  10535. (function (CameraTrackingMode) {
  10536. CameraTrackingMode[CameraTrackingMode["DEFAULT"] = 0] = "DEFAULT";
  10537. CameraTrackingMode[CameraTrackingMode["ROTATIONAL"] = 1] = "ROTATIONAL";
  10538. CameraTrackingMode[CameraTrackingMode["TRANSLATIONAL"] = 2] = "TRANSLATIONAL";
  10539. CameraTrackingMode[CameraTrackingMode["CINEMATIC"] = 3] = "CINEMATIC";
  10540. })(CameraTrackingMode || (CameraTrackingMode = {}));
  10541. var CameraProjectionMode;
  10542. (function (CameraProjectionMode) {
  10543. CameraProjectionMode[CameraProjectionMode["ORTHOGRAPHIC"] = 0] = "ORTHOGRAPHIC";
  10544. CameraProjectionMode[CameraProjectionMode["PERSPECTIVE"] = 1] = "PERSPECTIVE";
  10545. })(CameraProjectionMode || (CameraProjectionMode = {}));
  10546. var CameraEvent = {
  10547. UPDATED: 'updated'
  10548. };
  10549. var MIN_DISTANCE = 0.0002;
  10550. /**
  10551. * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计
  10552. * @see https://github.com/d13g0/nucleo.js/blob/master/source/camera/Camera.js
  10553. *
  10554. * 保存相机参数,定义相机动作:
  10555. * 1. dolly 沿 n 轴移动
  10556. * 2. pan 沿 u v 轴移动
  10557. * 3. rotate 以方位角旋转
  10558. * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互
  10559. */
  10560. var Camera = /*#__PURE__*/function () {
  10561. function Camera() {
  10562. this.canvas = void 0;
  10563. this.eventEmitter = new EventEmitter();
  10564. /**
  10565. * 相机矩阵
  10566. */
  10567. this.matrix = mat4.create();
  10568. /**
  10569. * u 轴
  10570. * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition
  10571. */
  10572. this.right = vec3.fromValues(1, 0, 0);
  10573. /**
  10574. * v 轴 +Y is down
  10575. */
  10576. this.up = vec3.fromValues(0, 1, 0);
  10577. /**
  10578. * n 轴 +Z is inside
  10579. */
  10580. this.forward = vec3.fromValues(0, 0, 1);
  10581. /**
  10582. * 相机位置
  10583. */
  10584. this.position = vec3.fromValues(0, 0, 1);
  10585. /**
  10586. * 视点位置
  10587. */
  10588. this.focalPoint = vec3.fromValues(0, 0, 0);
  10589. /**
  10590. * 视点到相机位置的向量
  10591. * focalPoint - position
  10592. */
  10593. this.distanceVector = vec3.fromValues(0, 0, -1);
  10594. /**
  10595. * 相机位置到视点距离
  10596. * length(focalPoint - position)
  10597. */
  10598. this.distance = 1;
  10599. /**
  10600. * @see https://en.wikipedia.org/wiki/Azimuth
  10601. */
  10602. this.azimuth = 0;
  10603. this.elevation = 0;
  10604. this.roll = 0;
  10605. this.relAzimuth = 0;
  10606. this.relElevation = 0;
  10607. this.relRoll = 0;
  10608. /**
  10609. * 沿 n 轴移动时,保证移动速度从快到慢
  10610. */
  10611. this.dollyingStep = 0;
  10612. this.maxDistance = Infinity;
  10613. this.minDistance = -Infinity;
  10614. /**
  10615. * zoom factor of the camera, default is 1
  10616. * eg. https://threejs.org/docs/#api/en/cameras/OrthographicCamera.zoom
  10617. */
  10618. this.zoom = 1;
  10619. /**
  10620. * invert the horizontal coordinate system HCS
  10621. */
  10622. this.rotateWorld = false;
  10623. /**
  10624. * 投影矩阵参数
  10625. */
  10626. /**
  10627. * field of view [0-360]
  10628. * @see http://en.wikipedia.org/wiki/Angle_of_view
  10629. */
  10630. this.fov = 30;
  10631. this.near = 0.1;
  10632. this.far = 1000;
  10633. this.aspect = 1;
  10634. this.left = void 0;
  10635. this.rright = void 0;
  10636. this.top = void 0;
  10637. this.bottom = void 0;
  10638. this.projectionMatrix = mat4.create();
  10639. this.projectionMatrixInverse = mat4.create();
  10640. this.jitteredProjectionMatrix = undefined;
  10641. this.view = void 0;
  10642. this.enableUpdate = true;
  10643. // protected following = undefined;
  10644. this.type = CameraType.EXPLORING;
  10645. this.trackingMode = CameraTrackingMode.DEFAULT;
  10646. this.projectionMode = CameraProjectionMode.PERSPECTIVE;
  10647. /**
  10648. * for culling use
  10649. */
  10650. this.frustum = new Frustum();
  10651. /**
  10652. * ortho matrix for Canvas2D & SVG
  10653. */
  10654. this.orthoMatrix = mat4.create();
  10655. }
  10656. var _proto = Camera.prototype;
  10657. // constructor(type = CameraType.EXPLORING, trackingMode = CameraTrackingMode.DEFAULT) {
  10658. // this.setType(type, trackingMode);
  10659. // }
  10660. _proto.isOrtho = function isOrtho() {
  10661. return this.projectionMode === CameraProjectionMode.ORTHOGRAPHIC;
  10662. };
  10663. _proto.getProjectionMode = function getProjectionMode() {
  10664. return this.projectionMode;
  10665. };
  10666. _proto.getPerspective = function getPerspective() {
  10667. // account for TAA
  10668. return this.jitteredProjectionMatrix || this.projectionMatrix;
  10669. };
  10670. _proto.getPerspectiveInverse = function getPerspectiveInverse() {
  10671. return this.projectionMatrixInverse;
  10672. };
  10673. _proto.getFrustum = function getFrustum() {
  10674. return this.frustum;
  10675. };
  10676. _proto.getPosition = function getPosition() {
  10677. return this.position;
  10678. };
  10679. _proto.getFocalPoint = function getFocalPoint() {
  10680. return this.focalPoint;
  10681. };
  10682. _proto.getDollyingStep = function getDollyingStep() {
  10683. return this.dollyingStep;
  10684. };
  10685. _proto.getNear = function getNear() {
  10686. return this.near;
  10687. };
  10688. _proto.getFar = function getFar() {
  10689. return this.far;
  10690. };
  10691. _proto.getZoom = function getZoom() {
  10692. return this.zoom;
  10693. };
  10694. _proto.getOrthoMatrix = function getOrthoMatrix() {
  10695. return this.orthoMatrix;
  10696. };
  10697. _proto.getView = function getView() {
  10698. return this.view;
  10699. };
  10700. _proto.setEnableUpdate = function setEnableUpdate(enabled) {
  10701. this.enableUpdate = enabled;
  10702. };
  10703. _proto.setType = function setType(type, trackingMode) {
  10704. this.type = type;
  10705. if (this.type === CameraType.EXPLORING) {
  10706. this.setWorldRotation(true);
  10707. } else {
  10708. this.setWorldRotation(false);
  10709. }
  10710. this._getAngles();
  10711. if (this.type === CameraType.TRACKING && trackingMode !== undefined) {
  10712. this.setTrackingMode(trackingMode);
  10713. }
  10714. return this;
  10715. };
  10716. _proto.setProjectionMode = function setProjectionMode(projectionMode) {
  10717. this.projectionMode = projectionMode;
  10718. return this;
  10719. };
  10720. _proto.setTrackingMode = function setTrackingMode(trackingMode) {
  10721. if (this.type !== CameraType.TRACKING) {
  10722. throw new Error('Impossible to set a tracking mode if the camera is not of tracking type');
  10723. }
  10724. this.trackingMode = trackingMode;
  10725. return this;
  10726. }
  10727. /**
  10728. * If flag is true, it reverses the azimuth and elevation angles.
  10729. * Subsequent calls to rotate, setAzimuth, setElevation,
  10730. * changeAzimuth or changeElevation will cause the inverted effect.
  10731. * setRoll or changeRoll is not affected by this method.
  10732. *
  10733. * This inversion is useful when one wants to simulate that the world
  10734. * is moving, instead of the camera.
  10735. *
  10736. * By default the camera angles are not reversed.
  10737. * @param {Boolean} flag the boolean flag to reverse the angles.
  10738. */;
  10739. _proto.setWorldRotation = function setWorldRotation(flag) {
  10740. this.rotateWorld = flag;
  10741. this._getAngles();
  10742. return this;
  10743. }
  10744. /**
  10745. * 计算 MV 矩阵,为相机矩阵的逆矩阵
  10746. */;
  10747. _proto.getViewTransform = function getViewTransform() {
  10748. return mat4.invert(mat4.create(), this.matrix);
  10749. };
  10750. _proto.getWorldTransform = function getWorldTransform() {
  10751. return this.matrix;
  10752. };
  10753. _proto.jitterProjectionMatrix = function jitterProjectionMatrix(x, y) {
  10754. var translation = mat4.fromTranslation(mat4.create(), [x, y, 0]);
  10755. this.jitteredProjectionMatrix = mat4.multiply(mat4.create(), translation, this.projectionMatrix);
  10756. };
  10757. _proto.clearJitterProjectionMatrix = function clearJitterProjectionMatrix() {
  10758. this.jitteredProjectionMatrix = undefined;
  10759. }
  10760. /**
  10761. * 设置相机矩阵
  10762. */;
  10763. _proto.setMatrix = function setMatrix(matrix) {
  10764. this.matrix = matrix;
  10765. this._update();
  10766. return this;
  10767. };
  10768. _proto.setFov = function setFov(fov) {
  10769. this.setPerspective(this.near, this.far, fov, this.aspect);
  10770. return this;
  10771. };
  10772. _proto.setAspect = function setAspect(aspect) {
  10773. this.setPerspective(this.near, this.far, this.fov, aspect);
  10774. return this;
  10775. };
  10776. _proto.setNear = function setNear(near) {
  10777. if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
  10778. this.setPerspective(near, this.far, this.fov, this.aspect);
  10779. } else {
  10780. this.setOrthographic(this.left, this.rright, this.top, this.bottom, near, this.far);
  10781. }
  10782. return this;
  10783. };
  10784. _proto.setFar = function setFar(far) {
  10785. if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
  10786. this.setPerspective(this.near, far, this.fov, this.aspect);
  10787. } else {
  10788. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, far);
  10789. }
  10790. return this;
  10791. }
  10792. /**
  10793. * Sets an offset in a larger frustum, used in PixelPicking
  10794. */;
  10795. _proto.setViewOffset = function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  10796. this.aspect = fullWidth / fullHeight;
  10797. if (this.view === undefined) {
  10798. this.view = {
  10799. enabled: true,
  10800. fullWidth: 1,
  10801. fullHeight: 1,
  10802. offsetX: 0,
  10803. offsetY: 0,
  10804. width: 1,
  10805. height: 1
  10806. };
  10807. }
  10808. this.view.enabled = true;
  10809. this.view.fullWidth = fullWidth;
  10810. this.view.fullHeight = fullHeight;
  10811. this.view.offsetX = x;
  10812. this.view.offsetY = y;
  10813. this.view.width = width;
  10814. this.view.height = height;
  10815. if (this.projectionMode === 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.clearViewOffset = function clearViewOffset() {
  10823. if (this.view !== undefined) {
  10824. this.view.enabled = false;
  10825. }
  10826. if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
  10827. this.setPerspective(this.near, this.far, this.fov, this.aspect);
  10828. } else {
  10829. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
  10830. }
  10831. return this;
  10832. };
  10833. _proto.setZoom = function setZoom(zoom) {
  10834. this.zoom = zoom;
  10835. if (this.projectionMode === CameraProjectionMode.ORTHOGRAPHIC) {
  10836. this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
  10837. } else if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
  10838. this.setPerspective(this.near, this.far, this.fov, this.aspect);
  10839. }
  10840. return this;
  10841. }
  10842. /**
  10843. * Zoom by specified point in viewport coordinates.
  10844. */;
  10845. _proto.setZoomByViewportPoint = function setZoomByViewportPoint(zoom, viewportPoint) {
  10846. var _this$canvas$viewport = this.canvas.viewport2Canvas({
  10847. x: viewportPoint[0],
  10848. y: viewportPoint[1]
  10849. }),
  10850. ox = _this$canvas$viewport.x,
  10851. oy = _this$canvas$viewport.y;
  10852. var roll = this.roll;
  10853. this.rotate(0, 0, -roll);
  10854. this.setPosition(ox, oy);
  10855. this.setFocalPoint(ox, oy);
  10856. this.setZoom(zoom);
  10857. this.rotate(0, 0, roll);
  10858. var _this$canvas$viewport2 = this.canvas.viewport2Canvas({
  10859. x: viewportPoint[0],
  10860. y: viewportPoint[1]
  10861. }),
  10862. cx = _this$canvas$viewport2.x,
  10863. cy = _this$canvas$viewport2.y;
  10864. // project to rotated axis
  10865. var dvec = vec3.fromValues(cx - ox, cy - oy, 0);
  10866. var dx = vec3.dot(dvec, this.right) / vec3.length(this.right);
  10867. var dy = vec3.dot(dvec, this.up) / vec3.length(this.up);
  10868. this.pan(-dx, -dy);
  10869. return this;
  10870. };
  10871. _proto.setPerspective = function setPerspective(near, far, fov, aspect) {
  10872. var _this$view;
  10873. this.projectionMode = CameraProjectionMode.PERSPECTIVE;
  10874. this.fov = fov;
  10875. this.near = near;
  10876. this.far = far;
  10877. this.aspect = aspect;
  10878. var top = this.near * Math.tan(deg2rad(0.5 * this.fov)) / this.zoom;
  10879. var height = 2 * top;
  10880. var width = this.aspect * height;
  10881. var left = -0.5 * width;
  10882. if ((_this$view = this.view) === null || _this$view === void 0 ? void 0 : _this$view.enabled) {
  10883. var fullWidth = this.view.fullWidth;
  10884. var fullHeight = this.view.fullHeight;
  10885. left += this.view.offsetX * width / fullWidth;
  10886. top -= this.view.offsetY * height / fullHeight;
  10887. width *= this.view.width / fullWidth;
  10888. height *= this.view.height / fullHeight;
  10889. }
  10890. makePerspective(this.projectionMatrix, left, left + width, top, top - height, near, this.far);
  10891. // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
  10892. mat4.scale(this.projectionMatrix, this.projectionMatrix, vec3.fromValues(1, -1, 1));
  10893. mat4.invert(this.projectionMatrixInverse, this.projectionMatrix);
  10894. this.triggerUpdate();
  10895. return this;
  10896. };
  10897. _proto.setOrthographic = function setOrthographic(l, r, t, b, near, far) {
  10898. var _this$view2;
  10899. this.projectionMode = CameraProjectionMode.ORTHOGRAPHIC;
  10900. this.rright = r;
  10901. this.left = l;
  10902. this.top = t;
  10903. this.bottom = b;
  10904. this.near = near;
  10905. this.far = far;
  10906. var dx = (this.rright - this.left) / (2 * this.zoom);
  10907. var dy = (this.top - this.bottom) / (2 * this.zoom);
  10908. var cx = (this.rright + this.left) / 2;
  10909. var cy = (this.top + this.bottom) / 2;
  10910. var left = cx - dx;
  10911. var right = cx + dx;
  10912. var top = cy + dy;
  10913. var bottom = cy - dy;
  10914. if ((_this$view2 = this.view) === null || _this$view2 === void 0 ? void 0 : _this$view2.enabled) {
  10915. var scaleW = (this.rright - this.left) / this.view.fullWidth / this.zoom;
  10916. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  10917. left += scaleW * this.view.offsetX;
  10918. right = left + scaleW * this.view.width;
  10919. top -= scaleH * this.view.offsetY;
  10920. bottom = top - scaleH * this.view.height;
  10921. }
  10922. mat4.ortho(this.projectionMatrix, left, right, bottom, top, near, far);
  10923. // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
  10924. mat4.scale(this.projectionMatrix, this.projectionMatrix, vec3.fromValues(1, -1, 1));
  10925. mat4.invert(this.projectionMatrixInverse, this.projectionMatrix);
  10926. this._getOrthoMatrix();
  10927. this.triggerUpdate();
  10928. return this;
  10929. }
  10930. /**
  10931. * Move the camera in world coordinates.
  10932. * It will keep looking at the current focal point.
  10933. *
  10934. * support scalars or vectors.
  10935. * @example
  10936. * setPosition(1, 2, 3);
  10937. * setPosition([1, 2, 3]);
  10938. */;
  10939. _proto.setPosition = function setPosition(x, y, z) {
  10940. if (y === void 0) {
  10941. y = this.position[1];
  10942. }
  10943. if (z === void 0) {
  10944. z = this.position[2];
  10945. }
  10946. var position = createVec3(x, y, z);
  10947. this._setPosition(position);
  10948. this.setFocalPoint(this.focalPoint);
  10949. this.triggerUpdate();
  10950. return this;
  10951. }
  10952. /**
  10953. * Sets the focal point of this camera in world coordinates.
  10954. *
  10955. * support scalars or vectors.
  10956. * @example
  10957. * setFocalPoint(1, 2, 3);
  10958. * setFocalPoint([1, 2, 3]);
  10959. */;
  10960. _proto.setFocalPoint = function setFocalPoint(x, y, z) {
  10961. if (y === void 0) {
  10962. y = this.focalPoint[1];
  10963. }
  10964. if (z === void 0) {
  10965. z = this.focalPoint[2];
  10966. }
  10967. var up = vec3.fromValues(0, 1, 0);
  10968. this.focalPoint = createVec3(x, y, z);
  10969. if (this.trackingMode === CameraTrackingMode.CINEMATIC) {
  10970. var d = vec3.subtract(vec3.create(), this.focalPoint, this.position);
  10971. x = d[0];
  10972. y = d[1];
  10973. z = d[2];
  10974. var r = vec3.length(d);
  10975. var el = rad2deg(Math.asin(y / r));
  10976. var az = 90 + rad2deg(Math.atan2(z, x));
  10977. var m = mat4.create();
  10978. mat4.rotateY(m, m, deg2rad(az));
  10979. mat4.rotateX(m, m, deg2rad(el));
  10980. up = vec3.transformMat4(vec3.create(), [0, 1, 0], m);
  10981. }
  10982. mat4.invert(this.matrix, mat4.lookAt(mat4.create(), this.position, this.focalPoint, up));
  10983. this._getAxes();
  10984. this._getDistance();
  10985. this._getAngles();
  10986. this.triggerUpdate();
  10987. return this;
  10988. };
  10989. _proto.getDistance = function getDistance() {
  10990. return this.distance;
  10991. };
  10992. _proto.getDistanceVector = function getDistanceVector() {
  10993. return this.distanceVector;
  10994. }
  10995. /**
  10996. * Moves the camera towards/from the focal point.
  10997. */;
  10998. _proto.setDistance = function setDistance(d) {
  10999. if (this.distance === d || d < 0) {
  11000. return this;
  11001. }
  11002. this.distance = d;
  11003. if (this.distance < MIN_DISTANCE) {
  11004. this.distance = MIN_DISTANCE;
  11005. }
  11006. this.dollyingStep = this.distance / 100;
  11007. var pos = vec3.create();
  11008. d = this.distance;
  11009. var n = this.forward;
  11010. var f = this.focalPoint;
  11011. pos[0] = d * n[0] + f[0];
  11012. pos[1] = d * n[1] + f[1];
  11013. pos[2] = d * n[2] + f[2];
  11014. this._setPosition(pos);
  11015. this.triggerUpdate();
  11016. return this;
  11017. };
  11018. _proto.setMaxDistance = function setMaxDistance(d) {
  11019. this.maxDistance = d;
  11020. return this;
  11021. };
  11022. _proto.setMinDistance = function setMinDistance(d) {
  11023. this.minDistance = d;
  11024. return this;
  11025. }
  11026. /**
  11027. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  11028. * the azimuth in degrees
  11029. */;
  11030. _proto.setAzimuth = function setAzimuth(az) {
  11031. this.azimuth = getAngle(az);
  11032. this.computeMatrix();
  11033. this._getAxes();
  11034. if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
  11035. this._getPosition();
  11036. } else if (this.type === CameraType.TRACKING) {
  11037. this._getFocalPoint();
  11038. }
  11039. this.triggerUpdate();
  11040. return this;
  11041. };
  11042. _proto.getAzimuth = function getAzimuth() {
  11043. return this.azimuth;
  11044. }
  11045. /**
  11046. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  11047. */;
  11048. _proto.setElevation = function setElevation(el) {
  11049. this.elevation = getAngle(el);
  11050. this.computeMatrix();
  11051. this._getAxes();
  11052. if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
  11053. this._getPosition();
  11054. } else if (this.type === CameraType.TRACKING) {
  11055. this._getFocalPoint();
  11056. }
  11057. this.triggerUpdate();
  11058. return this;
  11059. };
  11060. _proto.getElevation = function getElevation() {
  11061. return this.elevation;
  11062. }
  11063. /**
  11064. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  11065. */;
  11066. _proto.setRoll = function setRoll(angle) {
  11067. this.roll = getAngle(angle);
  11068. this.computeMatrix();
  11069. this._getAxes();
  11070. if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
  11071. this._getPosition();
  11072. } else if (this.type === CameraType.TRACKING) {
  11073. this._getFocalPoint();
  11074. }
  11075. this.triggerUpdate();
  11076. return this;
  11077. };
  11078. _proto.getRoll = function getRoll() {
  11079. return this.roll;
  11080. }
  11081. /**
  11082. * 根据相机矩阵重新计算各种相机参数
  11083. */;
  11084. _proto._update = function _update() {
  11085. this._getAxes();
  11086. this._getPosition();
  11087. this._getDistance();
  11088. this._getAngles();
  11089. this._getOrthoMatrix();
  11090. this.triggerUpdate();
  11091. }
  11092. /**
  11093. * 计算相机矩阵
  11094. */;
  11095. _proto.computeMatrix = function computeMatrix() {
  11096. // 使用四元数描述 3D 旋转
  11097. // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html
  11098. var rotZ = quat$1.setAxisAngle(quat$1.create(), [0, 0, 1], deg2rad(this.roll));
  11099. mat4.identity(this.matrix);
  11100. // only consider HCS for EXPLORING and ORBITING cameras
  11101. var rotX = quat$1.setAxisAngle(quat$1.create(), [1, 0, 0], deg2rad((this.rotateWorld && this.type !== CameraType.TRACKING || this.type === CameraType.TRACKING ? 1 : -1) * this.elevation));
  11102. var rotY = quat$1.setAxisAngle(quat$1.create(), [0, 1, 0], deg2rad((this.rotateWorld && this.type !== CameraType.TRACKING || this.type === CameraType.TRACKING ? 1 : -1) * this.azimuth));
  11103. var rotQ = quat$1.multiply(quat$1.create(), rotY, rotX);
  11104. rotQ = quat$1.multiply(quat$1.create(), rotQ, rotZ);
  11105. var rotMatrix = mat4.fromQuat(mat4.create(), rotQ);
  11106. if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
  11107. mat4.translate(this.matrix, this.matrix, this.focalPoint);
  11108. mat4.multiply(this.matrix, this.matrix, rotMatrix);
  11109. mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]);
  11110. } else if (this.type === CameraType.TRACKING) {
  11111. mat4.translate(this.matrix, this.matrix, this.position);
  11112. mat4.multiply(this.matrix, this.matrix, rotMatrix);
  11113. }
  11114. }
  11115. /**
  11116. * Sets the camera position in the camera matrix
  11117. */;
  11118. _proto._setPosition = function _setPosition(x, y, z) {
  11119. this.position = createVec3(x, y, z);
  11120. var m = this.matrix;
  11121. m[12] = this.position[0];
  11122. m[13] = this.position[1];
  11123. m[14] = this.position[2];
  11124. m[15] = 1;
  11125. this._getOrthoMatrix();
  11126. }
  11127. /**
  11128. * Recalculates axes based on the current matrix
  11129. */;
  11130. _proto._getAxes = function _getAxes() {
  11131. vec3.copy(this.right, createVec3(vec4.transformMat4(vec4.create(), [1, 0, 0, 0], this.matrix)));
  11132. vec3.copy(this.up, createVec3(vec4.transformMat4(vec4.create(), [0, 1, 0, 0], this.matrix)));
  11133. vec3.copy(this.forward, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 1, 0], this.matrix)));
  11134. vec3.normalize(this.right, this.right);
  11135. vec3.normalize(this.up, this.up);
  11136. vec3.normalize(this.forward, this.forward);
  11137. }
  11138. /**
  11139. * Recalculates euler angles based on the current state
  11140. */;
  11141. _proto._getAngles = function _getAngles() {
  11142. // Recalculates angles
  11143. var x = this.distanceVector[0];
  11144. var y = this.distanceVector[1];
  11145. var z = this.distanceVector[2];
  11146. var r = vec3.length(this.distanceVector);
  11147. // FAST FAIL: If there is no distance we cannot compute angles
  11148. if (r === 0) {
  11149. this.elevation = 0;
  11150. this.azimuth = 0;
  11151. return;
  11152. }
  11153. if (this.type === CameraType.TRACKING) {
  11154. this.elevation = rad2deg(Math.asin(y / r));
  11155. this.azimuth = rad2deg(Math.atan2(-x, -z));
  11156. } else {
  11157. if (this.rotateWorld) {
  11158. this.elevation = rad2deg(Math.asin(y / r));
  11159. this.azimuth = rad2deg(Math.atan2(-x, -z));
  11160. } else {
  11161. this.elevation = -rad2deg(Math.asin(y / r));
  11162. this.azimuth = -rad2deg(Math.atan2(-x, -z));
  11163. }
  11164. }
  11165. }
  11166. /**
  11167. * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化
  11168. */;
  11169. _proto._getPosition = function _getPosition() {
  11170. vec3.copy(this.position, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 0, 1], this.matrix)));
  11171. // 相机位置变化,需要重新计算视距
  11172. this._getDistance();
  11173. }
  11174. /**
  11175. * 重新计算视点,只有 TRACKING 模式视点才会发生变化
  11176. */;
  11177. _proto._getFocalPoint = function _getFocalPoint() {
  11178. vec3.transformMat3(this.distanceVector, [0, 0, -this.distance], mat3.fromMat4(mat3.create(), this.matrix));
  11179. vec3.add(this.focalPoint, this.position, this.distanceVector);
  11180. // 视点变化,需要重新计算视距
  11181. this._getDistance();
  11182. }
  11183. /**
  11184. * 重新计算视距
  11185. */;
  11186. _proto._getDistance = function _getDistance() {
  11187. this.distanceVector = vec3.subtract(vec3.create(), this.focalPoint, this.position);
  11188. this.distance = vec3.length(this.distanceVector);
  11189. this.dollyingStep = this.distance / 100;
  11190. };
  11191. _proto._getOrthoMatrix = function _getOrthoMatrix() {
  11192. if (this.projectionMode !== CameraProjectionMode.ORTHOGRAPHIC) {
  11193. return;
  11194. }
  11195. var position = this.position;
  11196. var rotZ = quat$1.setAxisAngle(quat$1.create(), [0, 0, 1], -this.roll * Math.PI / 180);
  11197. mat4.fromRotationTranslationScaleOrigin(this.orthoMatrix, rotZ, vec3.fromValues((this.rright - this.left) / 2 - position[0], (this.top - this.bottom) / 2 - position[1], 0), vec3.fromValues(this.zoom, this.zoom, 1), position);
  11198. };
  11199. _proto.triggerUpdate = function triggerUpdate() {
  11200. if (this.enableUpdate) {
  11201. // update frustum
  11202. var viewMatrix = this.getViewTransform();
  11203. var vpMatrix = mat4.multiply(mat4.create(), this.getPerspective(), viewMatrix);
  11204. this.getFrustum().extractFromVPMatrix(vpMatrix);
  11205. this.eventEmitter.emit(CameraEvent.UPDATED);
  11206. }
  11207. };
  11208. _proto.rotate = function rotate(azimuth, elevation, roll) {
  11209. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11210. };
  11211. _proto.pan = function pan(tx, ty) {
  11212. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11213. };
  11214. _proto.dolly = function dolly(value) {
  11215. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11216. };
  11217. _proto.createLandmark = function createLandmark(name, params) {
  11218. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11219. };
  11220. _proto.gotoLandmark = function gotoLandmark(name, options) {
  11221. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11222. };
  11223. _proto.cancelLandmarkAnimation = function cancelLandmarkAnimation() {
  11224. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  11225. };
  11226. return Camera;
  11227. }();
  11228. var CircleUpdater = /*#__PURE__*/function () {
  11229. function CircleUpdater() {}
  11230. var _proto = CircleUpdater.prototype;
  11231. _proto.update = function update(parsedStyle, object) {
  11232. var r = parsedStyle.r;
  11233. var width = r * 2;
  11234. var height = r * 2;
  11235. return {
  11236. width: width,
  11237. height: height
  11238. };
  11239. };
  11240. return CircleUpdater;
  11241. }();
  11242. var EllipseUpdater = /*#__PURE__*/function () {
  11243. function EllipseUpdater() {}
  11244. var _proto = EllipseUpdater.prototype;
  11245. _proto.update = function update(parsedStyle, object) {
  11246. var rx = parsedStyle.rx,
  11247. ry = parsedStyle.ry;
  11248. var width = rx * 2;
  11249. var height = ry * 2;
  11250. return {
  11251. width: width,
  11252. height: height
  11253. };
  11254. };
  11255. return EllipseUpdater;
  11256. }();
  11257. var LineUpdater = /*#__PURE__*/function () {
  11258. function LineUpdater() {}
  11259. var _proto = LineUpdater.prototype;
  11260. _proto.update = function update(parsedStyle) {
  11261. var x1 = parsedStyle.x1,
  11262. y1 = parsedStyle.y1,
  11263. x2 = parsedStyle.x2,
  11264. y2 = parsedStyle.y2;
  11265. var minX = Math.min(x1, x2);
  11266. var maxX = Math.max(x1, x2);
  11267. var minY = Math.min(y1, y2);
  11268. var maxY = Math.max(y1, y2);
  11269. var width = maxX - minX;
  11270. var height = maxY - minY;
  11271. return {
  11272. width: width,
  11273. height: height
  11274. };
  11275. };
  11276. return LineUpdater;
  11277. }();
  11278. var PathUpdater = /*#__PURE__*/function () {
  11279. function PathUpdater() {}
  11280. var _proto = PathUpdater.prototype;
  11281. _proto.update = function update(parsedStyle) {
  11282. var path = parsedStyle.path;
  11283. var _path$rect = path.rect,
  11284. width = _path$rect.width,
  11285. height = _path$rect.height;
  11286. return {
  11287. width: width,
  11288. height: height
  11289. };
  11290. };
  11291. return PathUpdater;
  11292. }();
  11293. var PolylineUpdater = /*#__PURE__*/function () {
  11294. function PolylineUpdater() {}
  11295. var _proto = PolylineUpdater.prototype;
  11296. _proto.update = function update(parsedStyle) {
  11297. var points = parsedStyle.points.points;
  11298. // FIXME: account for miter lineJoin
  11299. var minX = Math.min.apply(Math, points.map(function (point) {
  11300. return point[0];
  11301. }));
  11302. var maxX = Math.max.apply(Math, points.map(function (point) {
  11303. return point[0];
  11304. }));
  11305. var minY = Math.min.apply(Math, points.map(function (point) {
  11306. return point[1];
  11307. }));
  11308. var maxY = Math.max.apply(Math, points.map(function (point) {
  11309. return point[1];
  11310. }));
  11311. var width = maxX - minX;
  11312. var height = maxY - minY;
  11313. return {
  11314. width: width,
  11315. height: height
  11316. };
  11317. };
  11318. return PolylineUpdater;
  11319. }();
  11320. var RectUpdater = /*#__PURE__*/function () {
  11321. function RectUpdater() {}
  11322. var _proto = RectUpdater.prototype;
  11323. _proto.update = function update(parsedStyle, object) {
  11324. var img = parsedStyle.img,
  11325. _parsedStyle$width = parsedStyle.width,
  11326. width = _parsedStyle$width === void 0 ? 0 : _parsedStyle$width,
  11327. _parsedStyle$height = parsedStyle.height,
  11328. height = _parsedStyle$height === void 0 ? 0 : _parsedStyle$height;
  11329. var contentWidth = width;
  11330. var contentHeight = height;
  11331. // resize with HTMLImageElement's size
  11332. if (img && !isString(img)) {
  11333. if (!contentWidth) {
  11334. contentWidth = img.width;
  11335. parsedStyle.width = contentWidth;
  11336. }
  11337. if (!contentHeight) {
  11338. contentHeight = img.height;
  11339. parsedStyle.height = contentHeight;
  11340. }
  11341. }
  11342. return {
  11343. width: contentWidth,
  11344. height: contentHeight
  11345. };
  11346. };
  11347. return RectUpdater;
  11348. }();
  11349. var TextUpdater = /*#__PURE__*/function () {
  11350. function TextUpdater(globalRuntime) {
  11351. this.globalRuntime = void 0;
  11352. this.globalRuntime = globalRuntime;
  11353. }
  11354. var _proto = TextUpdater.prototype;
  11355. _proto.isReadyToMeasure = function isReadyToMeasure(parsedStyle, object) {
  11356. var text = parsedStyle.text,
  11357. textAlign = parsedStyle.textAlign,
  11358. textBaseline = parsedStyle.textBaseline,
  11359. fontSize = parsedStyle.fontSize,
  11360. fontStyle = parsedStyle.fontStyle,
  11361. fontWeight = parsedStyle.fontWeight,
  11362. fontVariant = parsedStyle.fontVariant,
  11363. lineWidth = parsedStyle.lineWidth;
  11364. return text && fontSize && fontStyle && fontWeight && fontVariant && textAlign && textBaseline && !isNil(lineWidth);
  11365. };
  11366. _proto.update = function update(parsedStyle, object) {
  11367. var _object$ownerDocument, _object$ownerDocument2;
  11368. var text = parsedStyle.text,
  11369. textAlign = parsedStyle.textAlign,
  11370. lineWidth = parsedStyle.lineWidth,
  11371. textBaseline = parsedStyle.textBaseline,
  11372. dx = parsedStyle.dx,
  11373. dy = parsedStyle.dy;
  11374. 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()) || {},
  11375. offscreenCanvas = _ref.offscreenCanvas;
  11376. if (!this.isReadyToMeasure(parsedStyle, object)) {
  11377. parsedStyle.metrics = {
  11378. font: '',
  11379. width: 0,
  11380. height: 0,
  11381. lines: [],
  11382. lineWidths: [],
  11383. lineHeight: 0,
  11384. maxLineWidth: 0,
  11385. fontProperties: {
  11386. ascent: 0,
  11387. descent: 0,
  11388. fontSize: 0
  11389. },
  11390. lineMetrics: []
  11391. };
  11392. return {
  11393. width: 0,
  11394. height: 0,
  11395. x: 0,
  11396. y: 0,
  11397. offsetX: 0,
  11398. offsetY: 0
  11399. };
  11400. }
  11401. var metrics = this.globalRuntime.textService.measureText(text, parsedStyle, offscreenCanvas);
  11402. parsedStyle.metrics = metrics;
  11403. var width = metrics.width,
  11404. height = metrics.height,
  11405. lineHeight = metrics.lineHeight,
  11406. fontProperties = metrics.fontProperties;
  11407. // anchor is left-top by default
  11408. var halfExtents = [width / 2, height / 2, 0];
  11409. // default 'left'
  11410. var anchor = [0, 1];
  11411. var lineXOffset = 0;
  11412. if (textAlign === 'center' || textAlign === 'middle') {
  11413. lineXOffset = lineWidth / 2;
  11414. anchor = [0.5, 1];
  11415. } else if (textAlign === 'right' || textAlign === 'end') {
  11416. lineXOffset = lineWidth;
  11417. anchor = [1, 1];
  11418. }
  11419. var lineYOffset = 0;
  11420. if (textBaseline === 'middle') {
  11421. // eslint-disable-next-line prefer-destructuring
  11422. lineYOffset = halfExtents[1];
  11423. } else if (textBaseline === 'top' || textBaseline === 'hanging') {
  11424. lineYOffset = halfExtents[1] * 2;
  11425. } else if (textBaseline === 'alphabetic') {
  11426. // prevent calling getImageData for ascent metrics
  11427. lineYOffset = runtime.enableCSSParsing ? lineHeight - fontProperties.ascent : 0;
  11428. } else if (textBaseline === 'bottom' || textBaseline === 'ideographic') {
  11429. lineYOffset = 0;
  11430. }
  11431. // TODO: ideographic & bottom
  11432. if (dx) {
  11433. lineXOffset += dx;
  11434. }
  11435. if (dy) {
  11436. lineYOffset += dy;
  11437. }
  11438. // update anchor
  11439. parsedStyle.anchor = [anchor[0], anchor[1], 0];
  11440. return {
  11441. width: halfExtents[0] * 2,
  11442. height: halfExtents[1] * 2,
  11443. offsetX: lineXOffset,
  11444. offsetY: lineYOffset
  11445. };
  11446. };
  11447. return TextUpdater;
  11448. }();
  11449. var PROPAGATION_LIMIT = 2048;
  11450. var EventService = /*#__PURE__*/function () {
  11451. function EventService(globalRuntime, context) {
  11452. var _this = this;
  11453. this.globalRuntime = void 0;
  11454. this.context = void 0;
  11455. this.rootTarget = void 0;
  11456. this.emitter = new EventEmitter();
  11457. this.cursor = 'default';
  11458. this.mappingTable = {};
  11459. this.mappingState = {
  11460. trackingData: {}
  11461. };
  11462. this.eventPool = new Map();
  11463. this.pickHandler = void 0;
  11464. this.tmpMatrix = mat4.create();
  11465. this.tmpVec3 = vec3.create();
  11466. this.onPointerDown = function (from) {
  11467. // if (!(from instanceof FederatedPointerEvent)) {
  11468. // return;
  11469. // }
  11470. var e = _this.createPointerEvent(from);
  11471. _this.dispatchEvent(e, 'pointerdown');
  11472. if (e.pointerType === 'touch') {
  11473. _this.dispatchEvent(e, 'touchstart');
  11474. } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11475. var isRightButton = e.button === 2;
  11476. _this.dispatchEvent(e, isRightButton ? 'rightdown' : 'mousedown');
  11477. }
  11478. var trackingData = _this.trackingData(from.pointerId);
  11479. trackingData.pressTargetsByButton[from.button] = e.composedPath();
  11480. _this.freeEvent(e);
  11481. };
  11482. this.onPointerUp = function (from) {
  11483. // if (!(from instanceof FederatedPointerEvent)) {
  11484. // return;
  11485. // }
  11486. var now = performance.now();
  11487. var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
  11488. _this.dispatchEvent(e, 'pointerup');
  11489. if (e.pointerType === 'touch') {
  11490. _this.dispatchEvent(e, 'touchend');
  11491. } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11492. var isRightButton = e.button === 2;
  11493. _this.dispatchEvent(e, isRightButton ? 'rightup' : 'mouseup');
  11494. }
  11495. var trackingData = _this.trackingData(from.pointerId);
  11496. var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
  11497. var clickTarget = pressTarget;
  11498. // pointerupoutside only bubbles. It only bubbles upto the parent that doesn't contain
  11499. // the pointerup location.
  11500. if (pressTarget && !e.composedPath().includes(pressTarget)) {
  11501. var currentTarget = pressTarget;
  11502. while (currentTarget && !e.composedPath().includes(currentTarget)) {
  11503. e.currentTarget = currentTarget;
  11504. _this.notifyTarget(e, 'pointerupoutside');
  11505. if (e.pointerType === 'touch') {
  11506. _this.notifyTarget(e, 'touchendoutside');
  11507. } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11508. var _isRightButton = e.button === 2;
  11509. _this.notifyTarget(e, _isRightButton ? 'rightupoutside' : 'mouseupoutside');
  11510. }
  11511. if (Node.isNode(currentTarget)) {
  11512. currentTarget = currentTarget.parentNode;
  11513. }
  11514. }
  11515. delete trackingData.pressTargetsByButton[from.button];
  11516. // currentTarget is the most specific ancestor holding both the pointerdown and pointerup
  11517. // targets. That is - it's our click target!
  11518. clickTarget = currentTarget;
  11519. }
  11520. if (clickTarget) {
  11521. var _e$detail;
  11522. var clickEvent = _this.clonePointerEvent(e, 'click');
  11523. clickEvent.target = clickTarget;
  11524. clickEvent.path = [];
  11525. if (!trackingData.clicksByButton[from.button]) {
  11526. trackingData.clicksByButton[from.button] = {
  11527. clickCount: 0,
  11528. target: clickEvent.target,
  11529. timeStamp: now
  11530. };
  11531. }
  11532. var clickHistory = trackingData.clicksByButton[from.button];
  11533. if (clickHistory.target === clickEvent.target && now - clickHistory.timeStamp < 200) {
  11534. ++clickHistory.clickCount;
  11535. } else {
  11536. clickHistory.clickCount = 1;
  11537. }
  11538. clickHistory.target = clickEvent.target;
  11539. clickHistory.timeStamp = now;
  11540. clickEvent.detail = clickHistory.clickCount;
  11541. // @see https://github.com/antvis/G/issues/1091
  11542. if (!((_e$detail = e.detail) === null || _e$detail === void 0 ? void 0 : _e$detail.preventClick)) {
  11543. if (!_this.context.config.useNativeClickEvent && (clickEvent.pointerType === 'mouse' || clickEvent.pointerType === 'touch')) {
  11544. _this.dispatchEvent(clickEvent, 'click');
  11545. }
  11546. _this.dispatchEvent(clickEvent, 'pointertap');
  11547. }
  11548. _this.freeEvent(clickEvent);
  11549. }
  11550. _this.freeEvent(e);
  11551. };
  11552. this.onPointerMove = function (from) {
  11553. // if (!(from instanceof FederatedPointerEvent)) {
  11554. // return;
  11555. // }
  11556. var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
  11557. var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
  11558. var trackingData = _this.trackingData(from.pointerId);
  11559. var outTarget = _this.findMountedTarget(trackingData.overTargets);
  11560. // First pointerout/pointerleave
  11561. if (trackingData.overTargets && outTarget !== e.target) {
  11562. // pointerout always occurs on the overTarget when the pointer hovers over another element.
  11563. var outType = from.type === 'mousemove' ? 'mouseout' : 'pointerout';
  11564. var outEvent = _this.createPointerEvent(from, outType, outTarget || undefined);
  11565. _this.dispatchEvent(outEvent, 'pointerout');
  11566. if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
  11567. // If the pointer exits overTarget and its descendants, then a pointerleave event is also fired. This event
  11568. // is dispatched to all ancestors that no longer capture the pointer.
  11569. if (!e.composedPath().includes(outTarget)) {
  11570. var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
  11571. leaveEvent.eventPhase = leaveEvent.AT_TARGET;
  11572. while (leaveEvent.target && !e.composedPath().includes(leaveEvent.target)) {
  11573. leaveEvent.currentTarget = leaveEvent.target;
  11574. _this.notifyTarget(leaveEvent);
  11575. if (isMouse) {
  11576. _this.notifyTarget(leaveEvent, 'mouseleave');
  11577. }
  11578. if (Node.isNode(leaveEvent.target)) {
  11579. leaveEvent.target = leaveEvent.target.parentNode;
  11580. }
  11581. }
  11582. _this.freeEvent(leaveEvent);
  11583. }
  11584. _this.freeEvent(outEvent);
  11585. }
  11586. // Then pointerover
  11587. if (outTarget !== e.target) {
  11588. // pointerover always occurs on the new overTarget
  11589. var overType = from.type === 'mousemove' ? 'mouseover' : 'pointerover';
  11590. var overEvent = _this.clonePointerEvent(e, overType); // clone faster
  11591. _this.dispatchEvent(overEvent, 'pointerover');
  11592. if (isMouse) _this.dispatchEvent(overEvent, 'mouseover');
  11593. // Probe whether the newly hovered Node is an ancestor of the original overTarget.
  11594. var overTargetAncestor = outTarget && Node.isNode(outTarget) && outTarget.parentNode;
  11595. while (overTargetAncestor && overTargetAncestor !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11596. if (overTargetAncestor === e.target) break;
  11597. overTargetAncestor = overTargetAncestor.parentNode;
  11598. }
  11599. // The pointer has entered a non-ancestor of the original overTarget. This means we need a pointerentered
  11600. // event.
  11601. var didPointerEnter = !overTargetAncestor || overTargetAncestor === (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode);
  11602. if (didPointerEnter) {
  11603. var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
  11604. enterEvent.eventPhase = enterEvent.AT_TARGET;
  11605. while (enterEvent.target && enterEvent.target !== outTarget && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11606. enterEvent.currentTarget = enterEvent.target;
  11607. _this.notifyTarget(enterEvent);
  11608. if (isMouse) _this.notifyTarget(enterEvent, 'mouseenter');
  11609. if (Node.isNode(enterEvent.target)) {
  11610. enterEvent.target = enterEvent.target.parentNode;
  11611. }
  11612. }
  11613. _this.freeEvent(enterEvent);
  11614. }
  11615. _this.freeEvent(overEvent);
  11616. }
  11617. // Then pointermove
  11618. _this.dispatchEvent(e, 'pointermove');
  11619. if (e.pointerType === 'touch') _this.dispatchEvent(e, 'touchmove');
  11620. if (isMouse) {
  11621. _this.dispatchEvent(e, 'mousemove');
  11622. _this.cursor = _this.getCursor(e.target);
  11623. }
  11624. trackingData.overTargets = e.composedPath();
  11625. _this.freeEvent(e);
  11626. };
  11627. this.onPointerOut = function (from) {
  11628. // if (!(from instanceof FederatedPointerEvent)) {
  11629. // return;
  11630. // }
  11631. var trackingData = _this.trackingData(from.pointerId);
  11632. if (trackingData.overTargets) {
  11633. var isMouse = from.pointerType === 'mouse' || from.pointerType === 'pen';
  11634. var outTarget = _this.findMountedTarget(trackingData.overTargets);
  11635. // pointerout first
  11636. var outEvent = _this.createPointerEvent(from, 'pointerout', outTarget || undefined);
  11637. _this.dispatchEvent(outEvent);
  11638. if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
  11639. // pointerleave(s) are also dispatched b/c the pointer must've left rootTarget and its descendants to
  11640. // get an upstream pointerout event (upstream events do not know rootTarget has descendants).
  11641. var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
  11642. leaveEvent.eventPhase = leaveEvent.AT_TARGET;
  11643. while (leaveEvent.target && leaveEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11644. leaveEvent.currentTarget = leaveEvent.target;
  11645. _this.notifyTarget(leaveEvent);
  11646. if (isMouse) {
  11647. _this.notifyTarget(leaveEvent, 'mouseleave');
  11648. }
  11649. if (Node.isNode(leaveEvent.target)) {
  11650. leaveEvent.target = leaveEvent.target.parentNode;
  11651. }
  11652. }
  11653. trackingData.overTargets = null;
  11654. _this.freeEvent(outEvent);
  11655. _this.freeEvent(leaveEvent);
  11656. }
  11657. _this.cursor = null;
  11658. };
  11659. this.onPointerOver = function (from) {
  11660. // if (!(from instanceof FederatedPointerEvent)) {
  11661. // return;
  11662. // }
  11663. var trackingData = _this.trackingData(from.pointerId);
  11664. var e = _this.createPointerEvent(from);
  11665. var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
  11666. _this.dispatchEvent(e, 'pointerover');
  11667. if (isMouse) _this.dispatchEvent(e, 'mouseover');
  11668. if (e.pointerType === 'mouse') _this.cursor = _this.getCursor(e.target);
  11669. // pointerenter events must be fired since the pointer entered from upstream.
  11670. var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
  11671. enterEvent.eventPhase = enterEvent.AT_TARGET;
  11672. while (enterEvent.target && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
  11673. enterEvent.currentTarget = enterEvent.target;
  11674. _this.notifyTarget(enterEvent);
  11675. if (isMouse) {
  11676. // mouseenter should not bubble
  11677. // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event#usage_notes
  11678. _this.notifyTarget(enterEvent, 'mouseenter');
  11679. }
  11680. if (Node.isNode(enterEvent.target)) {
  11681. enterEvent.target = enterEvent.target.parentNode;
  11682. }
  11683. }
  11684. trackingData.overTargets = e.composedPath();
  11685. _this.freeEvent(e);
  11686. _this.freeEvent(enterEvent);
  11687. };
  11688. this.onPointerUpOutside = function (from) {
  11689. // if (!(from instanceof FederatedPointerEvent)) {
  11690. // return;
  11691. // }
  11692. var trackingData = _this.trackingData(from.pointerId);
  11693. var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
  11694. var e = _this.createPointerEvent(from);
  11695. if (pressTarget) {
  11696. var currentTarget = pressTarget;
  11697. while (currentTarget) {
  11698. e.currentTarget = currentTarget;
  11699. _this.notifyTarget(e, 'pointerupoutside');
  11700. if (e.pointerType === 'touch') ; else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
  11701. _this.notifyTarget(e, e.button === 2 ? 'rightupoutside' : 'mouseupoutside');
  11702. }
  11703. if (Node.isNode(currentTarget)) {
  11704. currentTarget = currentTarget.parentNode;
  11705. }
  11706. }
  11707. delete trackingData.pressTargetsByButton[from.button];
  11708. }
  11709. _this.freeEvent(e);
  11710. };
  11711. this.onWheel = function (from) {
  11712. // if (!(from instanceof FederatedWheelEvent)) {
  11713. // return;
  11714. // }
  11715. var wheelEvent = _this.createWheelEvent(from);
  11716. _this.dispatchEvent(wheelEvent);
  11717. _this.freeEvent(wheelEvent);
  11718. };
  11719. this.onClick = function (from) {
  11720. if (_this.context.config.useNativeClickEvent) {
  11721. var e = _this.createPointerEvent(from);
  11722. _this.dispatchEvent(e);
  11723. _this.freeEvent(e);
  11724. }
  11725. };
  11726. this.onPointerCancel = function (from) {
  11727. var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
  11728. _this.dispatchEvent(e);
  11729. _this.freeEvent(e);
  11730. };
  11731. this.globalRuntime = globalRuntime;
  11732. this.context = context;
  11733. }
  11734. var _proto = EventService.prototype;
  11735. _proto.init = function init() {
  11736. this.rootTarget = this.context.renderingContext.root.parentNode; // document
  11737. this.addEventMapping('pointerdown', this.onPointerDown);
  11738. this.addEventMapping('pointerup', this.onPointerUp);
  11739. this.addEventMapping('pointermove', this.onPointerMove);
  11740. this.addEventMapping('pointerout', this.onPointerOut);
  11741. this.addEventMapping('pointerleave', this.onPointerOut);
  11742. this.addEventMapping('pointercancel', this.onPointerCancel);
  11743. this.addEventMapping('pointerover', this.onPointerOver);
  11744. this.addEventMapping('pointerupoutside', this.onPointerUpOutside);
  11745. this.addEventMapping('wheel', this.onWheel);
  11746. this.addEventMapping('click', this.onClick);
  11747. };
  11748. _proto.destroy = function destroy() {
  11749. this.emitter.removeAllListeners();
  11750. this.mappingTable = {};
  11751. this.mappingState = {};
  11752. this.eventPool.clear();
  11753. };
  11754. _proto.client2Viewport = function client2Viewport(client) {
  11755. var bbox = this.context.contextService.getBoundingClientRect();
  11756. 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));
  11757. };
  11758. _proto.viewport2Client = function viewport2Client(canvas) {
  11759. var bbox = this.context.contextService.getBoundingClientRect();
  11760. 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));
  11761. };
  11762. _proto.viewport2Canvas = function viewport2Canvas(_ref) {
  11763. var x = _ref.x,
  11764. y = _ref.y;
  11765. var canvas = this.rootTarget.defaultView;
  11766. var camera = canvas.getCamera();
  11767. var _this$context$config = this.context.config,
  11768. width = _this$context$config.width,
  11769. height = _this$context$config.height;
  11770. var projectionMatrixInverse = camera.getPerspectiveInverse();
  11771. var worldMatrix = camera.getWorldTransform();
  11772. var vpMatrix = mat4.multiply(this.tmpMatrix, worldMatrix, projectionMatrixInverse);
  11773. var viewport = vec3.set(this.tmpVec3, x / width * 2 - 1, (1 - y / height) * 2 - 1, 0);
  11774. vec3.transformMat4(viewport, viewport, vpMatrix);
  11775. return new Point(viewport[0], viewport[1]);
  11776. };
  11777. _proto.canvas2Viewport = function canvas2Viewport(canvasP) {
  11778. var canvas = this.rootTarget.defaultView;
  11779. var camera = canvas.getCamera();
  11780. // World -> Clip
  11781. var projectionMatrix = camera.getPerspective();
  11782. var viewMatrix = camera.getViewTransform();
  11783. var vpMatrix = mat4.multiply(this.tmpMatrix, projectionMatrix, viewMatrix);
  11784. var clip = vec3.set(this.tmpVec3, canvasP.x, canvasP.y, 0);
  11785. vec3.transformMat4(this.tmpVec3, this.tmpVec3, vpMatrix);
  11786. // Clip -> NDC -> Viewport, flip Y
  11787. var _this$context$config2 = this.context.config,
  11788. width = _this$context$config2.width,
  11789. height = _this$context$config2.height;
  11790. return new Point((clip[0] + 1) / 2 * width, (1 - (clip[1] + 1) / 2) * height);
  11791. };
  11792. _proto.setPickHandler = function setPickHandler(pickHandler) {
  11793. this.pickHandler = pickHandler;
  11794. };
  11795. _proto.addEventMapping = function addEventMapping(type, fn) {
  11796. if (!this.mappingTable[type]) {
  11797. this.mappingTable[type] = [];
  11798. }
  11799. this.mappingTable[type].push({
  11800. fn: fn,
  11801. priority: 0
  11802. });
  11803. this.mappingTable[type].sort(function (a, b) {
  11804. return a.priority - b.priority;
  11805. });
  11806. };
  11807. _proto.mapEvent = function mapEvent(e) {
  11808. if (!this.rootTarget) {
  11809. return;
  11810. }
  11811. var mappers = this.mappingTable[e.type];
  11812. if (mappers) {
  11813. for (var i = 0, j = mappers.length; i < j; i++) {
  11814. mappers[i].fn(e);
  11815. }
  11816. } else {
  11817. console.warn("[EventService]: Event mapping not defined for " + e.type);
  11818. }
  11819. };
  11820. _proto.dispatchEvent = function dispatchEvent(e, type, skipPropagate) {
  11821. // Canvas should skip
  11822. if (!skipPropagate) {
  11823. e.propagationStopped = false;
  11824. e.propagationImmediatelyStopped = false;
  11825. this.propagate(e, type);
  11826. } else {
  11827. // target phase
  11828. e.eventPhase = e.AT_TARGET;
  11829. var canvas = this.rootTarget.defaultView || null;
  11830. e.currentTarget = canvas;
  11831. this.notifyListeners(e, type);
  11832. }
  11833. this.emitter.emit(type || e.type, e);
  11834. };
  11835. _proto.propagate = function propagate(e, type) {
  11836. if (!e.target) {
  11837. return;
  11838. }
  11839. // [target, parent, root, Canvas]
  11840. var composedPath = e.composedPath();
  11841. // event flow: capture -> target -> bubbling
  11842. // capture phase
  11843. e.eventPhase = e.CAPTURING_PHASE;
  11844. for (var i = composedPath.length - 1; i >= 1; i--) {
  11845. e.currentTarget = composedPath[i];
  11846. this.notifyTarget(e, type);
  11847. if (e.propagationStopped || e.propagationImmediatelyStopped) return;
  11848. }
  11849. // target phase
  11850. e.eventPhase = e.AT_TARGET;
  11851. e.currentTarget = e.target;
  11852. this.notifyTarget(e, type);
  11853. if (e.propagationStopped || e.propagationImmediatelyStopped) return;
  11854. // find current target in composed path
  11855. var index = composedPath.indexOf(e.currentTarget);
  11856. // bubbling phase
  11857. e.eventPhase = e.BUBBLING_PHASE;
  11858. for (var _i = index + 1; _i < composedPath.length; _i++) {
  11859. e.currentTarget = composedPath[_i];
  11860. this.notifyTarget(e, type);
  11861. if (e.propagationStopped || e.propagationImmediatelyStopped) return;
  11862. }
  11863. };
  11864. _proto.propagationPath = function propagationPath(target) {
  11865. var propagationPath = [target];
  11866. var canvas = this.rootTarget.defaultView || null;
  11867. if (canvas && canvas === target) {
  11868. propagationPath.unshift(canvas.document);
  11869. return propagationPath;
  11870. }
  11871. for (var i = 0; i < PROPAGATION_LIMIT && target !== this.rootTarget; i++) {
  11872. // if (Node.isNode(target) && !target.parentNode) {
  11873. // throw new Error('Cannot find propagation path to disconnected target');
  11874. // }
  11875. if (Node.isNode(target) && target.parentNode) {
  11876. // [target, parent, parent, root]
  11877. propagationPath.push(target.parentNode);
  11878. target = target.parentNode;
  11879. }
  11880. }
  11881. if (canvas) {
  11882. // @ts-ignore
  11883. propagationPath.push(canvas);
  11884. }
  11885. return propagationPath;
  11886. };
  11887. _proto.hitTest = function hitTest(position) {
  11888. var viewportX = position.viewportX,
  11889. viewportY = position.viewportY;
  11890. var _this$context$config3 = this.context.config,
  11891. width = _this$context$config3.width,
  11892. height = _this$context$config3.height;
  11893. // outside canvas
  11894. if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
  11895. return null;
  11896. }
  11897. return this.pickHandler(position) || this.rootTarget ||
  11898. // return Document
  11899. null;
  11900. }
  11901. /**
  11902. * whether the native event trigger came from Canvas,
  11903. * should account for HTML shape
  11904. */;
  11905. _proto.isNativeEventFromCanvas = function isNativeEventFromCanvas(event) {
  11906. var _event$nativeEvent;
  11907. var $el = this.context.contextService.getDomElement();
  11908. var target = (_event$nativeEvent = event.nativeEvent) === null || _event$nativeEvent === void 0 ? void 0 : _event$nativeEvent.target;
  11909. if (target) {
  11910. // from <canvas>
  11911. if (target === $el) {
  11912. return true;
  11913. }
  11914. // from <svg>
  11915. if ($el && $el.contains) {
  11916. return $el.contains(target);
  11917. }
  11918. }
  11919. if (event.nativeEvent.composedPath) {
  11920. return event.nativeEvent.composedPath().indexOf($el) > -1;
  11921. }
  11922. // account for Touch
  11923. return false;
  11924. }
  11925. /**
  11926. * Find HTML from composed path in native UI event.
  11927. */;
  11928. _proto.getExistedHTML = function getExistedHTML(event) {
  11929. if (event.nativeEvent.composedPath) {
  11930. for (var _iterator = _createForOfIteratorHelperLoose(event.nativeEvent.composedPath()), _step; !(_step = _iterator()).done;) {
  11931. var eventTarget = _step.value;
  11932. var existed = runtime.nativeHTMLMap.get(eventTarget);
  11933. if (existed) {
  11934. return existed;
  11935. }
  11936. }
  11937. }
  11938. return null;
  11939. };
  11940. _proto.pickTarget = function pickTarget(event) {
  11941. return this.hitTest({
  11942. clientX: event.clientX,
  11943. clientY: event.clientY,
  11944. viewportX: event.viewportX,
  11945. viewportY: event.viewportY,
  11946. x: event.canvasX,
  11947. y: event.canvasY
  11948. });
  11949. };
  11950. _proto.createPointerEvent = function createPointerEvent(from, type, target, fallbackTarget) {
  11951. var event = this.allocateEvent(FederatedPointerEvent);
  11952. this.copyPointerData(from, event);
  11953. this.copyMouseData(from, event);
  11954. this.copyData(from, event);
  11955. event.nativeEvent = from.nativeEvent;
  11956. event.originalEvent = from;
  11957. var existedHTML = this.getExistedHTML(event);
  11958. event.target = target !== null && target !== void 0 ? target : existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event) || fallbackTarget;
  11959. if (typeof type === 'string') {
  11960. event.type = type;
  11961. }
  11962. return event;
  11963. };
  11964. _proto.createWheelEvent = function createWheelEvent(from) {
  11965. var event = this.allocateEvent(FederatedWheelEvent);
  11966. this.copyWheelData(from, event);
  11967. this.copyMouseData(from, event);
  11968. this.copyData(from, event);
  11969. event.nativeEvent = from.nativeEvent;
  11970. event.originalEvent = from;
  11971. var existedHTML = this.getExistedHTML(event);
  11972. event.target = existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event);
  11973. return event;
  11974. };
  11975. _proto.trackingData = function trackingData(id) {
  11976. if (!this.mappingState.trackingData[id]) {
  11977. this.mappingState.trackingData[id] = {
  11978. pressTargetsByButton: {},
  11979. clicksByButton: {},
  11980. overTarget: null
  11981. };
  11982. }
  11983. return this.mappingState.trackingData[id];
  11984. };
  11985. _proto.cloneWheelEvent = function cloneWheelEvent(from) {
  11986. var event = this.allocateEvent(FederatedWheelEvent);
  11987. event.nativeEvent = from.nativeEvent;
  11988. event.originalEvent = from.originalEvent;
  11989. this.copyWheelData(from, event);
  11990. this.copyMouseData(from, event);
  11991. this.copyData(from, event);
  11992. event.target = from.target;
  11993. event.path = from.composedPath().slice();
  11994. event.type = from.type;
  11995. return event;
  11996. };
  11997. _proto.clonePointerEvent = function clonePointerEvent(from, type) {
  11998. var event = this.allocateEvent(FederatedPointerEvent);
  11999. event.nativeEvent = from.nativeEvent;
  12000. event.originalEvent = from.originalEvent;
  12001. this.copyPointerData(from, event);
  12002. this.copyMouseData(from, event);
  12003. this.copyData(from, event);
  12004. event.target = from.target;
  12005. event.path = from.composedPath().slice();
  12006. event.type = type !== null && type !== void 0 ? type : event.type;
  12007. return event;
  12008. };
  12009. _proto.copyPointerData = function copyPointerData(from, to) {
  12010. // if (
  12011. // !(
  12012. // from instanceof FederatedPointerEvent &&
  12013. // to instanceof FederatedPointerEvent
  12014. // )
  12015. // )
  12016. // return;
  12017. to.pointerId = from.pointerId;
  12018. to.width = from.width;
  12019. to.height = from.height;
  12020. to.isPrimary = from.isPrimary;
  12021. to.pointerType = from.pointerType;
  12022. to.pressure = from.pressure;
  12023. to.tangentialPressure = from.tangentialPressure;
  12024. to.tiltX = from.tiltX;
  12025. to.tiltY = from.tiltY;
  12026. to.twist = from.twist;
  12027. };
  12028. _proto.copyMouseData = function copyMouseData(from, to) {
  12029. // if (
  12030. // !(
  12031. // from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent
  12032. // )
  12033. // )
  12034. // return;
  12035. to.altKey = from.altKey;
  12036. to.button = from.button;
  12037. to.buttons = from.buttons;
  12038. to.ctrlKey = from.ctrlKey;
  12039. to.metaKey = from.metaKey;
  12040. to.shiftKey = from.shiftKey;
  12041. to.client.copyFrom(from.client);
  12042. to.movement.copyFrom(from.movement);
  12043. to.canvas.copyFrom(from.canvas);
  12044. to.screen.copyFrom(from.screen);
  12045. to.global.copyFrom(from.global);
  12046. to.offset.copyFrom(from.offset);
  12047. };
  12048. _proto.copyWheelData = function copyWheelData(from, to) {
  12049. to.deltaMode = from.deltaMode;
  12050. to.deltaX = from.deltaX;
  12051. to.deltaY = from.deltaY;
  12052. to.deltaZ = from.deltaZ;
  12053. };
  12054. _proto.copyData = function copyData(from, to) {
  12055. to.isTrusted = from.isTrusted;
  12056. to.timeStamp = performance.now();
  12057. to.type = from.type;
  12058. to.detail = from.detail;
  12059. to.view = from.view;
  12060. to.page.copyFrom(from.page);
  12061. to.viewport.copyFrom(from.viewport);
  12062. };
  12063. _proto.allocateEvent = function allocateEvent(constructor) {
  12064. if (!this.eventPool.has(constructor)) {
  12065. this.eventPool.set(constructor, []);
  12066. }
  12067. // @ts-ignore
  12068. var event = this.eventPool.get(constructor).pop() || new constructor(this);
  12069. event.eventPhase = event.NONE;
  12070. event.currentTarget = null;
  12071. event.path = [];
  12072. event.target = null;
  12073. return event;
  12074. };
  12075. _proto.freeEvent = function freeEvent(event) {
  12076. if (event.manager !== this) throw new Error('It is illegal to free an event not managed by this EventBoundary!');
  12077. var constructor = event.constructor;
  12078. if (!this.eventPool.has(constructor)) {
  12079. this.eventPool.set(constructor, []);
  12080. }
  12081. // @ts-ignore
  12082. this.eventPool.get(constructor).push(event);
  12083. };
  12084. _proto.notifyTarget = function notifyTarget(e, type) {
  12085. var _type;
  12086. type = (_type = type) !== null && _type !== void 0 ? _type : e.type;
  12087. var key = e.eventPhase === e.CAPTURING_PHASE || e.eventPhase === e.AT_TARGET ? type + "capture" : type;
  12088. this.notifyListeners(e, key);
  12089. if (e.eventPhase === e.AT_TARGET) {
  12090. this.notifyListeners(e, type);
  12091. }
  12092. };
  12093. _proto.notifyListeners = function notifyListeners(e, type) {
  12094. // hack EventEmitter, stops if the `propagationImmediatelyStopped` flag is set
  12095. // @ts-ignore
  12096. var emitter = e.currentTarget.emitter;
  12097. // @ts-ignore
  12098. var listeners = emitter._events[type];
  12099. if (!listeners) return;
  12100. if ('fn' in listeners) {
  12101. if (listeners.once) {
  12102. emitter.removeListener(type, listeners.fn, undefined, true);
  12103. }
  12104. listeners.fn.call(e.currentTarget || listeners.context, e);
  12105. // listeners.fn.call(listeners.context, e);
  12106. } else {
  12107. for (var i = 0; i < listeners.length && !e.propagationImmediatelyStopped; i++) {
  12108. if (listeners[i].once) {
  12109. emitter.removeListener(type, listeners[i].fn, undefined, true);
  12110. }
  12111. listeners[i].fn.call(e.currentTarget || listeners[i].context, e);
  12112. // listeners[i].fn.call(listeners[i].context, e);
  12113. }
  12114. }
  12115. }
  12116. /**
  12117. * some detached nodes may exist in propagation path, need to skip them
  12118. */;
  12119. _proto.findMountedTarget = function findMountedTarget(propagationPath) {
  12120. if (!propagationPath) {
  12121. return null;
  12122. }
  12123. var currentTarget = propagationPath[propagationPath.length - 1];
  12124. for (var i = propagationPath.length - 2; i >= 0; i--) {
  12125. var target = propagationPath[i];
  12126. if (target === this.rootTarget || Node.isNode(target) && target.parentNode === currentTarget) {
  12127. currentTarget = propagationPath[i];
  12128. } else {
  12129. break;
  12130. }
  12131. }
  12132. return currentTarget;
  12133. };
  12134. _proto.getCursor = function getCursor(target) {
  12135. var tmp = target;
  12136. while (tmp) {
  12137. var cursor = Element.isElement(tmp) && tmp.getAttribute('cursor');
  12138. if (cursor) {
  12139. return cursor;
  12140. }
  12141. tmp = Node.isNode(tmp) && tmp.parentNode;
  12142. }
  12143. };
  12144. return EventService;
  12145. }();
  12146. /**
  12147. * used in following scenes:
  12148. * - g `ctx.measureText`
  12149. * - g-plugin-canvas-picker `ctx.isPointInPath`
  12150. * - g-plugin-device-renderer `ctx.createLinearGradient` and generate texture
  12151. *
  12152. * @see https://blog.scottlogic.com/2020/03/19/offscreen-canvas.html
  12153. */
  12154. var OffscreenCanvasCreator = /*#__PURE__*/function () {
  12155. function OffscreenCanvasCreator() {
  12156. this.canvas = void 0;
  12157. this.context = void 0;
  12158. }
  12159. var _proto = OffscreenCanvasCreator.prototype;
  12160. _proto.getOrCreateCanvas = function getOrCreateCanvas(offscreenCanvas, contextAttributes) {
  12161. if (this.canvas) {
  12162. return this.canvas;
  12163. }
  12164. // user-defined offscreen canvas
  12165. if (offscreenCanvas) {
  12166. this.canvas = offscreenCanvas;
  12167. this.context = this.canvas.getContext('2d', contextAttributes);
  12168. } else {
  12169. try {
  12170. // OffscreenCanvas2D measureText can be up to 40% faster.
  12171. this.canvas = new window.OffscreenCanvas(0, 0);
  12172. this.context = this.canvas.getContext('2d', contextAttributes);
  12173. if (!this.context || !this.context.measureText) {
  12174. this.canvas = document.createElement('canvas');
  12175. this.context = this.canvas.getContext('2d');
  12176. }
  12177. } catch (ex) {
  12178. this.canvas = document.createElement('canvas');
  12179. this.context = this.canvas.getContext('2d', contextAttributes);
  12180. }
  12181. }
  12182. this.canvas.width = 10;
  12183. this.canvas.height = 10;
  12184. return this.canvas;
  12185. };
  12186. _proto.getOrCreateContext = function getOrCreateContext(offscreenCanvas, contextAttributes) {
  12187. if (this.context) {
  12188. return this.context;
  12189. }
  12190. this.getOrCreateCanvas(offscreenCanvas, contextAttributes);
  12191. return this.context;
  12192. };
  12193. return OffscreenCanvasCreator;
  12194. }();
  12195. /**
  12196. * why we need re-render
  12197. */
  12198. var RenderReason;
  12199. (function (RenderReason) {
  12200. RenderReason[RenderReason["CAMERA_CHANGED"] = 0] = "CAMERA_CHANGED";
  12201. RenderReason[RenderReason["DISPLAY_OBJECT_CHANGED"] = 1] = "DISPLAY_OBJECT_CHANGED";
  12202. RenderReason[RenderReason["NONE"] = 2] = "NONE";
  12203. })(RenderReason || (RenderReason = {}));
  12204. /**
  12205. * Use frame renderer implemented by `g-canvas/svg/webgl`, in every frame we do followings:
  12206. * * update & merge dirty rectangles
  12207. * * begin frame
  12208. * * filter by visible
  12209. * * sort by z-index in scene graph
  12210. * * culling with strategies registered in `g-canvas/webgl`
  12211. * * end frame
  12212. */
  12213. var RenderingService = /*#__PURE__*/function () {
  12214. function RenderingService(globalRuntime, context) {
  12215. this.globalRuntime = void 0;
  12216. this.context = void 0;
  12217. this.inited = false;
  12218. this.stats = {
  12219. /**
  12220. * total display objects in scenegraph
  12221. */
  12222. total: 0,
  12223. /**
  12224. * number of display objects need to render in current frame
  12225. */
  12226. rendered: 0
  12227. };
  12228. this.zIndexCounter = 0;
  12229. this.hooks = {
  12230. /**
  12231. * called before any frame rendered
  12232. */
  12233. init: new SyncHook(),
  12234. initAsync: new AsyncParallelHook(),
  12235. /**
  12236. * only dirty object which has sth changed will be rendered
  12237. */
  12238. dirtycheck: new SyncWaterfallHook(),
  12239. /**
  12240. * do culling
  12241. */
  12242. cull: new SyncWaterfallHook(),
  12243. /**
  12244. * called at beginning of each frame, won't get called if nothing to re-render
  12245. */
  12246. beginFrame: new SyncHook(),
  12247. /**
  12248. * called before every dirty object get rendered
  12249. */
  12250. beforeRender: new SyncHook(),
  12251. /**
  12252. * called when every dirty object rendering even it's culled
  12253. */
  12254. render: new SyncHook(),
  12255. /**
  12256. * called after every dirty object get rendered
  12257. */
  12258. afterRender: new SyncHook(),
  12259. endFrame: new SyncHook(),
  12260. destroy: new SyncHook(),
  12261. /**
  12262. * use async but faster method such as GPU-based picking in `g-plugin-device-renderer`
  12263. */
  12264. pick: new AsyncSeriesWaterfallHook(),
  12265. /**
  12266. * Unsafe but sync version of pick.
  12267. */
  12268. pickSync: new SyncWaterfallHook(),
  12269. /**
  12270. * used in event system
  12271. */
  12272. pointerDown: new SyncHook(),
  12273. pointerUp: new SyncHook(),
  12274. pointerMove: new SyncHook(),
  12275. pointerOut: new SyncHook(),
  12276. pointerOver: new SyncHook(),
  12277. pointerWheel: new SyncHook(),
  12278. pointerCancel: new SyncHook(),
  12279. click: new SyncHook()
  12280. };
  12281. this.globalRuntime = globalRuntime;
  12282. this.context = context;
  12283. }
  12284. var _proto = RenderingService.prototype;
  12285. _proto.init = function init(callback) {
  12286. var _this = this;
  12287. var context = _extends({}, this.globalRuntime, this.context);
  12288. // register rendering plugins
  12289. this.context.renderingPlugins.forEach(function (plugin) {
  12290. plugin.apply(context, runtime);
  12291. });
  12292. this.hooks.init.call();
  12293. if (this.hooks.initAsync.getCallbacksNum() === 0) {
  12294. this.inited = true;
  12295. callback();
  12296. } else {
  12297. this.hooks.initAsync.promise().then(function () {
  12298. _this.inited = true;
  12299. callback();
  12300. });
  12301. }
  12302. };
  12303. _proto.getStats = function getStats() {
  12304. return this.stats;
  12305. }
  12306. /**
  12307. * Meet the following conditions:
  12308. * * disable DirtyRectangleRendering
  12309. * * camera changed
  12310. */;
  12311. _proto.disableDirtyRectangleRendering = function disableDirtyRectangleRendering() {
  12312. var renderer = this.context.config.renderer;
  12313. var _renderer$getConfig = renderer.getConfig(),
  12314. enableDirtyRectangleRendering = _renderer$getConfig.enableDirtyRectangleRendering;
  12315. return !enableDirtyRectangleRendering || this.context.renderingContext.renderReasons.has(RenderReason.CAMERA_CHANGED);
  12316. };
  12317. _proto.render = function render(canvasConfig, rerenderCallback) {
  12318. var _this2 = this;
  12319. this.stats.total = 0;
  12320. this.stats.rendered = 0;
  12321. this.zIndexCounter = 0;
  12322. var renderingContext = this.context.renderingContext;
  12323. this.globalRuntime.sceneGraphService.syncHierarchy(renderingContext.root);
  12324. this.globalRuntime.sceneGraphService.triggerPendingEvents();
  12325. if (renderingContext.renderReasons.size && this.inited) {
  12326. this.renderDisplayObject(renderingContext.root, canvasConfig, renderingContext);
  12327. this.hooks.beginFrame.call();
  12328. renderingContext.renderListCurrentFrame.forEach(function (object) {
  12329. _this2.hooks.beforeRender.call(object);
  12330. _this2.hooks.render.call(object);
  12331. _this2.hooks.afterRender.call(object);
  12332. });
  12333. this.hooks.endFrame.call();
  12334. renderingContext.renderListCurrentFrame = [];
  12335. renderingContext.renderReasons.clear();
  12336. rerenderCallback();
  12337. }
  12338. // console.log('stats', this.stats);
  12339. };
  12340. _proto.renderDisplayObject = function renderDisplayObject(displayObject, canvasConfig, renderingContext) {
  12341. var _this3 = this;
  12342. var _canvasConfig$rendere = canvasConfig.renderer.getConfig(),
  12343. enableDirtyCheck = _canvasConfig$rendere.enableDirtyCheck,
  12344. enableCulling = _canvasConfig$rendere.enableCulling;
  12345. // recalc style values
  12346. if (this.globalRuntime.enableCSSParsing) {
  12347. this.globalRuntime.styleValueRegistry.recalc(displayObject);
  12348. }
  12349. // TODO: relayout
  12350. // dirtycheck first
  12351. var objectChanged = enableDirtyCheck ? this.hooks.dirtycheck.call(displayObject) : displayObject;
  12352. if (objectChanged) {
  12353. var objectToRender = enableCulling ? this.hooks.cull.call(objectChanged, this.context.camera) : objectChanged;
  12354. if (objectToRender) {
  12355. this.stats.rendered++;
  12356. renderingContext.renderListCurrentFrame.push(objectToRender);
  12357. }
  12358. }
  12359. displayObject.renderable.dirty = false;
  12360. displayObject.sortable.renderOrder = this.zIndexCounter++;
  12361. this.stats.total++;
  12362. // sort is very expensive, use cached result if possible
  12363. var sortable = displayObject.sortable;
  12364. if (sortable.dirty) {
  12365. this.sort(displayObject, sortable);
  12366. sortable.dirty = false;
  12367. sortable.dirtyChildren = [];
  12368. sortable.dirtyReason = undefined;
  12369. }
  12370. // recursive rendering its children
  12371. (sortable.sorted || displayObject.childNodes).forEach(function (child) {
  12372. _this3.renderDisplayObject(child, canvasConfig, renderingContext);
  12373. });
  12374. };
  12375. _proto.sort = function sort(displayObject, sortable) {
  12376. if (sortable.sorted && sortable.dirtyReason !== SortReason.Z_INDEX_CHANGED) {
  12377. // avoid re-sorting the whole children list
  12378. sortable.dirtyChildren.forEach(function (child) {
  12379. var index = displayObject.childNodes.indexOf(child);
  12380. if (index === -1) {
  12381. // remove from sorted list
  12382. var _index = sortable.sorted.indexOf(child);
  12383. if (_index >= 0) {
  12384. sortable.sorted.splice(_index, 1);
  12385. }
  12386. } else {
  12387. if (sortable.sorted.length === 0) {
  12388. sortable.sorted.push(child);
  12389. } else {
  12390. var _index2 = sortedIndex(sortable.sorted, child);
  12391. sortable.sorted.splice(_index2, 0, child);
  12392. }
  12393. }
  12394. });
  12395. } else {
  12396. sortable.sorted = displayObject.childNodes.slice().sort(sortByZIndex);
  12397. }
  12398. };
  12399. _proto.destroy = function destroy() {
  12400. this.inited = false;
  12401. this.hooks.destroy.call();
  12402. this.globalRuntime.sceneGraphService.clearPendingEvents();
  12403. };
  12404. _proto.dirtify = function dirtify() {
  12405. // need re-render
  12406. this.context.renderingContext.renderReasons.add(RenderReason.DISPLAY_OBJECT_CHANGED);
  12407. };
  12408. return RenderingService;
  12409. }();
  12410. var ATTRIBUTE_REGEXP = /\[\s*(.*)=(.*)\s*\]/;
  12411. /**
  12412. * support the following DOM API:
  12413. * * getElementById
  12414. * * getElementsByClassName
  12415. * * getElementsByName
  12416. * * getElementsByTag
  12417. * * querySelector
  12418. * * querySelectorAll
  12419. */
  12420. var DefaultSceneGraphSelector = /*#__PURE__*/function () {
  12421. function DefaultSceneGraphSelector() {}
  12422. var _proto = DefaultSceneGraphSelector.prototype;
  12423. _proto.selectOne = function selectOne(query, root) {
  12424. var _this = this;
  12425. if (query.startsWith('.')) {
  12426. return root.find(function (node) {
  12427. // return !node.shadow && node.id === query.substring(1);
  12428. return ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this.getIdOrClassname(query)) > -1;
  12429. });
  12430. } else if (query.startsWith('#')) {
  12431. // getElementById('id')
  12432. return root.find(function (node) {
  12433. // return !node.shadow && node.id === query.substring(1);
  12434. return node.id === _this.getIdOrClassname(query);
  12435. });
  12436. } else if (query.startsWith('[')) {
  12437. var _this$getAttribute = this.getAttribute(query),
  12438. name = _this$getAttribute.name,
  12439. value = _this$getAttribute.value;
  12440. if (name) {
  12441. // getElementByName();
  12442. return root.find(function (node) {
  12443. return root !== node && (name === 'name' ? node.name === value : _this.attributeToString(node, name) === value);
  12444. });
  12445. } else {
  12446. return null;
  12447. }
  12448. } else {
  12449. // getElementsByTag('circle');
  12450. return root.find(function (node) {
  12451. return root !== node && node.nodeName === query;
  12452. });
  12453. }
  12454. };
  12455. _proto.selectAll = function selectAll(query, root) {
  12456. var _this2 = this;
  12457. // only support `[name="${name}"]` `.className` `#id`
  12458. if (query.startsWith('.')) {
  12459. // getElementsByClassName('className');
  12460. // should not include itself
  12461. return root.findAll(function (node) {
  12462. return root !== node && ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this2.getIdOrClassname(query)) > -1;
  12463. });
  12464. } else if (query.startsWith('#')) {
  12465. return root.findAll(function (node) {
  12466. return root !== node && node.id === _this2.getIdOrClassname(query);
  12467. });
  12468. } else if (query.startsWith('[')) {
  12469. var _this$getAttribute2 = this.getAttribute(query),
  12470. name = _this$getAttribute2.name,
  12471. value = _this$getAttribute2.value;
  12472. if (name) {
  12473. // getElementsByName();
  12474. return root.findAll(function (node) {
  12475. return root !== node && (name === 'name' ? node.name === value : _this2.attributeToString(node, name) === value);
  12476. });
  12477. } else {
  12478. return [];
  12479. }
  12480. } else {
  12481. // getElementsByTag('circle');
  12482. return root.findAll(function (node) {
  12483. return root !== node && node.nodeName === query;
  12484. });
  12485. }
  12486. };
  12487. _proto.is = function is(query, node) {
  12488. // a simple `matches` implementation
  12489. if (query.startsWith('.')) {
  12490. return node.className === this.getIdOrClassname(query);
  12491. } else if (query.startsWith('#')) {
  12492. return node.id === this.getIdOrClassname(query);
  12493. } else if (query.startsWith('[')) {
  12494. var _this$getAttribute3 = this.getAttribute(query),
  12495. name = _this$getAttribute3.name,
  12496. value = _this$getAttribute3.value;
  12497. return name === 'name' ? node.name === value : this.attributeToString(node, name) === value;
  12498. } else {
  12499. return node.nodeName === query;
  12500. }
  12501. };
  12502. _proto.getIdOrClassname = function getIdOrClassname(query) {
  12503. return query.substring(1);
  12504. };
  12505. _proto.getAttribute = function getAttribute(query) {
  12506. var matches = query.match(ATTRIBUTE_REGEXP);
  12507. var name = '';
  12508. var value = '';
  12509. if (matches && matches.length > 2) {
  12510. name = matches[1].replace(/"/g, '');
  12511. value = matches[2].replace(/"/g, '');
  12512. }
  12513. return {
  12514. name: name,
  12515. value: value
  12516. };
  12517. };
  12518. _proto.attributeToString = function attributeToString(node, name) {
  12519. if (!node.getAttribute) {
  12520. return '';
  12521. }
  12522. var value = node.getAttribute(name);
  12523. if (isNil(value)) {
  12524. return '';
  12525. }
  12526. if (value.toString) {
  12527. return value.toString();
  12528. }
  12529. return '';
  12530. };
  12531. return DefaultSceneGraphSelector;
  12532. }();
  12533. function markRenderableDirty(e) {
  12534. var renderable = e.renderable;
  12535. if (renderable) {
  12536. renderable.renderBoundsDirty = true;
  12537. renderable.boundsDirty = true;
  12538. }
  12539. }
  12540. var reparentEvent = new MutationEvent(ElementEvent.REPARENT, null, '', '', '', 0, '', '');
  12541. /**
  12542. * update transform in scene graph
  12543. *
  12544. * @see https://community.khronos.org/t/scene-graphs/50542/7
  12545. */
  12546. var DefaultSceneGraphService = /*#__PURE__*/function () {
  12547. function DefaultSceneGraphService(runtime) {
  12548. var _this = this;
  12549. this.runtime = void 0;
  12550. this.pendingEvents = [];
  12551. this.boundsChangedEvent = new CustomEvent(ElementEvent.BOUNDS_CHANGED);
  12552. /**
  12553. * rotate in world space
  12554. */
  12555. this.rotate = function () {
  12556. var parentInvertRotation = quat$1.create();
  12557. return function (element, degrees, y, z) {
  12558. if (y === void 0) {
  12559. y = 0;
  12560. }
  12561. if (z === void 0) {
  12562. z = 0;
  12563. }
  12564. if (typeof degrees === 'number') {
  12565. degrees = vec3.fromValues(degrees, y, z);
  12566. }
  12567. var transform = element.transformable;
  12568. if (element.parentNode === null || !element.parentNode.transformable) {
  12569. _this.rotateLocal(element, degrees);
  12570. } else {
  12571. var rotation = quat$1.create();
  12572. quat$1.fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
  12573. var rot = _this.getRotation(element);
  12574. var parentRot = _this.getRotation(element.parentNode);
  12575. quat$1.copy(parentInvertRotation, parentRot);
  12576. quat$1.invert(parentInvertRotation, parentInvertRotation);
  12577. quat$1.multiply(rotation, parentInvertRotation, rotation);
  12578. quat$1.multiply(transform.localRotation, rotation, rot);
  12579. quat$1.normalize(transform.localRotation, transform.localRotation);
  12580. _this.dirtifyLocal(element, transform);
  12581. }
  12582. };
  12583. }();
  12584. /**
  12585. * rotate in local space
  12586. * @see @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw
  12587. */
  12588. this.rotateLocal = function () {
  12589. var rotation = quat$1.create();
  12590. return function (element, degrees, y, z) {
  12591. if (y === void 0) {
  12592. y = 0;
  12593. }
  12594. if (z === void 0) {
  12595. z = 0;
  12596. }
  12597. if (typeof degrees === 'number') {
  12598. degrees = vec3.fromValues(degrees, y, z);
  12599. }
  12600. var transform = element.transformable;
  12601. quat$1.fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
  12602. quat$1.mul(transform.localRotation, transform.localRotation, rotation);
  12603. _this.dirtifyLocal(element, transform);
  12604. };
  12605. }();
  12606. /**
  12607. * set euler angles(degrees) in world space
  12608. */
  12609. this.setEulerAngles = function () {
  12610. var invParentRot = quat$1.create();
  12611. return function (element, degrees, y, z) {
  12612. if (y === void 0) {
  12613. y = 0;
  12614. }
  12615. if (z === void 0) {
  12616. z = 0;
  12617. }
  12618. if (typeof degrees === 'number') {
  12619. degrees = vec3.fromValues(degrees, y, z);
  12620. }
  12621. var transform = element.transformable;
  12622. if (element.parentNode === null || !element.parentNode.transformable) {
  12623. _this.setLocalEulerAngles(element, degrees);
  12624. } else {
  12625. quat$1.fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
  12626. var parentRotation = _this.getRotation(element.parentNode);
  12627. quat$1.copy(invParentRot, quat$1.invert(quat$1.create(), parentRotation));
  12628. quat$1.mul(transform.localRotation, transform.localRotation, invParentRot);
  12629. _this.dirtifyLocal(element, transform);
  12630. }
  12631. };
  12632. }();
  12633. /**
  12634. * translate in local space
  12635. *
  12636. * @example
  12637. * ```
  12638. * translateLocal(x, y, z)
  12639. * translateLocal(vec3(x, y, z))
  12640. * ```
  12641. */
  12642. this.translateLocal = function () {
  12643. return function (element, translation, y, z) {
  12644. if (y === void 0) {
  12645. y = 0;
  12646. }
  12647. if (z === void 0) {
  12648. z = 0;
  12649. }
  12650. if (typeof translation === 'number') {
  12651. translation = vec3.fromValues(translation, y, z);
  12652. }
  12653. var transform = element.transformable;
  12654. if (vec3.equals(translation, vec3.create())) {
  12655. return;
  12656. }
  12657. vec3.transformQuat(translation, translation, transform.localRotation);
  12658. vec3.add(transform.localPosition, transform.localPosition, translation);
  12659. _this.dirtifyLocal(element, transform);
  12660. };
  12661. }();
  12662. /**
  12663. * move to position in world space
  12664. *
  12665. * 对应 g 原版的 move/moveTo
  12666. * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L684-L689
  12667. */
  12668. this.setPosition = function () {
  12669. var parentInvertMatrix = mat4.create();
  12670. var tmpPosition = vec3.create();
  12671. return function (element, position) {
  12672. var transform = element.transformable;
  12673. tmpPosition[0] = position[0];
  12674. tmpPosition[1] = position[1];
  12675. tmpPosition[2] = position[2] || 0;
  12676. if (vec3.equals(_this.getPosition(element), tmpPosition)) {
  12677. return;
  12678. }
  12679. vec3.copy(transform.position, tmpPosition);
  12680. if (element.parentNode === null || !element.parentNode.transformable) {
  12681. vec3.copy(transform.localPosition, tmpPosition);
  12682. } else {
  12683. var parentTransform = element.parentNode.transformable;
  12684. mat4.copy(parentInvertMatrix, parentTransform.worldTransform);
  12685. mat4.invert(parentInvertMatrix, parentInvertMatrix);
  12686. vec3.transformMat4(transform.localPosition, tmpPosition, parentInvertMatrix);
  12687. }
  12688. _this.dirtifyLocal(element, transform);
  12689. };
  12690. }();
  12691. /**
  12692. * move to position in local space
  12693. */
  12694. this.setLocalPosition = function () {
  12695. var tmpPosition = vec3.create();
  12696. return function (element, position) {
  12697. var transform = element.transformable;
  12698. tmpPosition[0] = position[0];
  12699. tmpPosition[1] = position[1];
  12700. tmpPosition[2] = position[2] || 0;
  12701. if (vec3.equals(transform.localPosition, tmpPosition)) {
  12702. return;
  12703. }
  12704. vec3.copy(transform.localPosition, tmpPosition);
  12705. _this.dirtifyLocal(element, transform);
  12706. };
  12707. }();
  12708. /**
  12709. * translate in world space
  12710. *
  12711. * @example
  12712. * ```
  12713. * translate(x, y, z)
  12714. * translate(vec3(x, y, z))
  12715. * ```
  12716. *
  12717. * 对应 g 原版的 translate 2D
  12718. * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L665-L676
  12719. */
  12720. this.translate = function () {
  12721. var zeroVec3 = vec3.create();
  12722. var tmpVec3 = vec3.create();
  12723. var tr = vec3.create();
  12724. return function (element, translation, y, z) {
  12725. if (y === void 0) {
  12726. y = 0;
  12727. }
  12728. if (z === void 0) {
  12729. z = 0;
  12730. }
  12731. if (typeof translation === 'number') {
  12732. translation = vec3.set(tmpVec3, translation, y, z);
  12733. }
  12734. if (vec3.equals(translation, zeroVec3)) {
  12735. return;
  12736. }
  12737. vec3.add(tr, _this.getPosition(element), translation);
  12738. _this.setPosition(element, tr);
  12739. };
  12740. }();
  12741. this.setRotation = function () {
  12742. var parentInvertRotation = quat$1.create();
  12743. return function (element, rotation, y, z, w) {
  12744. var transform = element.transformable;
  12745. if (typeof rotation === 'number') {
  12746. rotation = quat$1.fromValues(rotation, y, z, w);
  12747. }
  12748. if (element.parentNode === null || !element.parentNode.transformable) {
  12749. _this.setLocalRotation(element, rotation);
  12750. } else {
  12751. var parentRot = _this.getRotation(element.parentNode);
  12752. quat$1.copy(parentInvertRotation, parentRot);
  12753. quat$1.invert(parentInvertRotation, parentInvertRotation);
  12754. quat$1.multiply(transform.localRotation, parentInvertRotation, rotation);
  12755. quat$1.normalize(transform.localRotation, transform.localRotation);
  12756. _this.dirtifyLocal(element, transform);
  12757. }
  12758. };
  12759. };
  12760. this.displayObjectDependencyMap = new WeakMap();
  12761. this.calcLocalTransform = function () {
  12762. var tmpMat = mat4.create();
  12763. var tmpPosition = vec3.create();
  12764. var tmpQuat = quat$1.fromValues(0, 0, 0, 1);
  12765. return function (transform) {
  12766. var hasSkew = transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0;
  12767. if (hasSkew) {
  12768. mat4.fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, vec3.fromValues(1, 1, 1), transform.origin);
  12769. // apply skew2D
  12770. if (transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0) {
  12771. var tmpMat4 = mat4.identity(tmpMat);
  12772. tmpMat4[4] = Math.tan(transform.localSkew[0]);
  12773. tmpMat4[1] = Math.tan(transform.localSkew[1]);
  12774. mat4.multiply(transform.localTransform, transform.localTransform, tmpMat4);
  12775. }
  12776. var scaling = mat4.fromRotationTranslationScaleOrigin(tmpMat, tmpQuat, tmpPosition, transform.localScale, transform.origin);
  12777. mat4.multiply(transform.localTransform, transform.localTransform, scaling);
  12778. } else {
  12779. // @see https://github.com/mattdesl/css-mat4/blob/master/index.js
  12780. mat4.fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, transform.localScale, transform.origin);
  12781. }
  12782. };
  12783. }();
  12784. this.runtime = runtime;
  12785. }
  12786. var _proto = DefaultSceneGraphService.prototype;
  12787. _proto.matches = function matches(query, root) {
  12788. return this.runtime.sceneGraphSelector.is(query, root);
  12789. };
  12790. _proto.querySelector = function querySelector(query, root) {
  12791. return this.runtime.sceneGraphSelector.selectOne(query, root);
  12792. };
  12793. _proto.querySelectorAll = function querySelectorAll(query, root) {
  12794. return this.runtime.sceneGraphSelector.selectAll(query, root);
  12795. // .filter((node) => !node.shadow);
  12796. };
  12797. _proto.attach = function attach(child, parent, index) {
  12798. var _sortable$sorted, _child$style;
  12799. var detached = false;
  12800. if (child.parentNode) {
  12801. detached = child.parentNode !== parent;
  12802. this.detach(child);
  12803. }
  12804. child.parentNode = parent;
  12805. if (!isNil(index)) {
  12806. child.parentNode.childNodes.splice(index, 0, child);
  12807. } else {
  12808. child.parentNode.childNodes.push(child);
  12809. }
  12810. // parent needs re-sort
  12811. var sortable = parent.sortable;
  12812. 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)) {
  12813. if (sortable.dirtyChildren.indexOf(child) === -1) {
  12814. sortable.dirtyChildren.push(child);
  12815. }
  12816. // if (sortable) {
  12817. // only child has z-Index
  12818. sortable.dirty = true;
  12819. sortable.dirtyReason = SortReason.ADDED;
  12820. }
  12821. // this.updateGraphDepth(child);
  12822. var transform = child.transformable;
  12823. if (transform) {
  12824. this.dirtifyWorld(child, transform);
  12825. }
  12826. if (transform.frozen) {
  12827. this.unfreezeParentToRoot(child);
  12828. }
  12829. if (detached) {
  12830. child.dispatchEvent(reparentEvent);
  12831. }
  12832. };
  12833. _proto.detach = function detach(child) {
  12834. if (child.parentNode) {
  12835. var _sortable$sorted2, _child$style2;
  12836. var transform = child.transformable;
  12837. // if (transform) {
  12838. // const worldTransform = this.getWorldTransform(child, transform);
  12839. // mat4.getScaling(transform.localScale, worldTransform);
  12840. // mat4.getTranslation(transform.localPosition, worldTransform);
  12841. // mat4.getRotation(transform.localRotation, worldTransform);
  12842. // transform.localDirtyFlag = true;
  12843. // }
  12844. // parent needs re-sort
  12845. var sortable = child.parentNode.sortable;
  12846. // if (sortable) {
  12847. 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)) {
  12848. if (sortable.dirtyChildren.indexOf(child) === -1) {
  12849. sortable.dirtyChildren.push(child);
  12850. }
  12851. sortable.dirty = true;
  12852. sortable.dirtyReason = SortReason.REMOVED;
  12853. }
  12854. var index = child.parentNode.childNodes.indexOf(child);
  12855. if (index > -1) {
  12856. child.parentNode.childNodes.splice(index, 1);
  12857. }
  12858. if (transform) {
  12859. this.dirtifyWorld(child, transform);
  12860. }
  12861. child.parentNode = null;
  12862. }
  12863. };
  12864. _proto.getOrigin = function getOrigin(element) {
  12865. return element.transformable.origin;
  12866. }
  12867. /**
  12868. * same as pivot in Pixi.js
  12869. *
  12870. * @see https://stackoverflow.com/questions/40748452/how-to-change-css-transform-origin-but-preserve-transformation
  12871. */;
  12872. _proto.setOrigin = function setOrigin(element, origin, y, z) {
  12873. if (y === void 0) {
  12874. y = 0;
  12875. }
  12876. if (z === void 0) {
  12877. z = 0;
  12878. }
  12879. if (typeof origin === 'number') {
  12880. origin = [origin, y, z];
  12881. }
  12882. var transform = element.transformable;
  12883. if (origin[0] === transform.origin[0] && origin[1] === transform.origin[1] && origin[2] === transform.origin[2]) {
  12884. return;
  12885. }
  12886. var originVec = transform.origin;
  12887. // const delta = vec3.subtract(vec3.create(), origin, originVec);
  12888. // vec3.add(transform.localPosition, transform.localPosition, delta);
  12889. // update origin
  12890. originVec[0] = origin[0];
  12891. originVec[1] = origin[1];
  12892. originVec[2] = origin[2] || 0;
  12893. this.dirtifyLocal(element, transform);
  12894. };
  12895. /**
  12896. * set euler angles(degrees) in local space
  12897. */
  12898. _proto.setLocalEulerAngles = function setLocalEulerAngles(element, degrees, y, z) {
  12899. if (y === void 0) {
  12900. y = 0;
  12901. }
  12902. if (z === void 0) {
  12903. z = 0;
  12904. }
  12905. if (typeof degrees === 'number') {
  12906. degrees = vec3.fromValues(degrees, y, z);
  12907. }
  12908. var transform = element.transformable;
  12909. quat$1.fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
  12910. this.dirtifyLocal(element, transform);
  12911. };
  12912. /**
  12913. * scale in local space
  12914. */
  12915. _proto.scaleLocal = function scaleLocal(element, scaling) {
  12916. var transform = element.transformable;
  12917. vec3.multiply(transform.localScale, transform.localScale, vec3.fromValues(scaling[0], scaling[1], scaling[2] || 1));
  12918. this.dirtifyLocal(element, transform);
  12919. };
  12920. _proto.setLocalScale = function setLocalScale(element, scaling) {
  12921. var transform = element.transformable;
  12922. var updatedScaling = vec3.fromValues(scaling[0], scaling[1], scaling[2] || transform.localScale[2]);
  12923. if (vec3.equals(updatedScaling, transform.localScale)) {
  12924. return;
  12925. }
  12926. vec3.copy(transform.localScale, updatedScaling);
  12927. this.dirtifyLocal(element, transform);
  12928. };
  12929. _proto.setLocalRotation = function setLocalRotation(element, rotation, y, z, w) {
  12930. if (typeof rotation === 'number') {
  12931. rotation = quat$1.fromValues(rotation, y, z, w);
  12932. }
  12933. var transform = element.transformable;
  12934. quat$1.copy(transform.localRotation, rotation);
  12935. this.dirtifyLocal(element, transform);
  12936. };
  12937. _proto.setLocalSkew = function setLocalSkew(element, skew, y) {
  12938. if (typeof skew === 'number') {
  12939. skew = vec2.fromValues(skew, y);
  12940. }
  12941. var transform = element.transformable;
  12942. vec2.copy(transform.localSkew, skew);
  12943. this.dirtifyLocal(element, transform);
  12944. };
  12945. _proto.dirtifyLocal = function dirtifyLocal(element, transform) {
  12946. if (!transform.localDirtyFlag) {
  12947. transform.localDirtyFlag = true;
  12948. if (!transform.dirtyFlag) {
  12949. this.dirtifyWorld(element, transform);
  12950. }
  12951. }
  12952. };
  12953. _proto.dirtifyWorld = function dirtifyWorld(element, transform) {
  12954. if (!transform.dirtyFlag) {
  12955. this.unfreezeParentToRoot(element);
  12956. }
  12957. this.dirtifyWorldInternal(element, transform);
  12958. this.dirtifyToRoot(element, true);
  12959. };
  12960. _proto.triggerPendingEvents = function triggerPendingEvents() {
  12961. var _this2 = this;
  12962. var set = new Set();
  12963. var trigger = function trigger(element, detail) {
  12964. if (element.isConnected && !set.has(element.entity)) {
  12965. _this2.boundsChangedEvent.detail = detail;
  12966. _this2.boundsChangedEvent.target = element;
  12967. if (element.isMutationObserved) {
  12968. element.dispatchEvent(_this2.boundsChangedEvent);
  12969. } else {
  12970. element.ownerDocument.defaultView.dispatchEvent(_this2.boundsChangedEvent, true);
  12971. }
  12972. set.add(element.entity);
  12973. }
  12974. };
  12975. this.pendingEvents.forEach(function (_ref) {
  12976. var element = _ref[0],
  12977. detail = _ref[1];
  12978. if (detail.affectChildren) {
  12979. element.forEach(function (e) {
  12980. trigger(e, detail);
  12981. });
  12982. } else {
  12983. trigger(element, detail);
  12984. }
  12985. });
  12986. this.clearPendingEvents();
  12987. set.clear();
  12988. };
  12989. _proto.clearPendingEvents = function clearPendingEvents() {
  12990. this.pendingEvents = [];
  12991. };
  12992. _proto.dirtifyToRoot = function dirtifyToRoot(element, affectChildren) {
  12993. if (affectChildren === void 0) {
  12994. affectChildren = false;
  12995. }
  12996. var p = element;
  12997. // only need to re-render itself
  12998. if (p.renderable) {
  12999. p.renderable.dirty = true;
  13000. }
  13001. while (p) {
  13002. markRenderableDirty(p);
  13003. p = p.parentNode;
  13004. }
  13005. if (affectChildren) {
  13006. element.forEach(function (e) {
  13007. markRenderableDirty(e);
  13008. });
  13009. }
  13010. // inform dependencies
  13011. this.informDependentDisplayObjects(element);
  13012. // reuse the same custom event
  13013. this.pendingEvents.push([element, {
  13014. affectChildren: affectChildren
  13015. }]);
  13016. };
  13017. _proto.updateDisplayObjectDependency = function updateDisplayObjectDependency(name, oldPath, newPath, object) {
  13018. // clear ref to old clip path
  13019. if (oldPath && oldPath !== newPath) {
  13020. var oldDependencyMap = this.displayObjectDependencyMap.get(oldPath);
  13021. if (oldDependencyMap && oldDependencyMap[name]) {
  13022. var index = oldDependencyMap[name].indexOf(object);
  13023. oldDependencyMap[name].splice(index, 1);
  13024. }
  13025. }
  13026. if (newPath) {
  13027. var newDependencyMap = this.displayObjectDependencyMap.get(newPath);
  13028. if (!newDependencyMap) {
  13029. this.displayObjectDependencyMap.set(newPath, {});
  13030. newDependencyMap = this.displayObjectDependencyMap.get(newPath);
  13031. }
  13032. if (!newDependencyMap[name]) {
  13033. newDependencyMap[name] = [];
  13034. }
  13035. newDependencyMap[name].push(object);
  13036. }
  13037. };
  13038. _proto.informDependentDisplayObjects = function informDependentDisplayObjects(object) {
  13039. var _this3 = this;
  13040. var dependencyMap = this.displayObjectDependencyMap.get(object);
  13041. if (dependencyMap) {
  13042. Object.keys(dependencyMap).forEach(function (name) {
  13043. dependencyMap[name].forEach(function (target) {
  13044. _this3.dirtifyToRoot(target, true);
  13045. target.dispatchEvent(new MutationEvent(ElementEvent.ATTR_MODIFIED, target, _this3, _this3, name, MutationEvent.MODIFICATION, _this3, _this3));
  13046. if (target.isCustomElement && target.isConnected) {
  13047. if (target.attributeChangedCallback) {
  13048. target.attributeChangedCallback(name, _this3, _this3);
  13049. }
  13050. }
  13051. });
  13052. });
  13053. }
  13054. };
  13055. _proto.getPosition = function getPosition(element) {
  13056. var transform = element.transformable;
  13057. return mat4.getTranslation(transform.position, this.getWorldTransform(element, transform));
  13058. };
  13059. _proto.getRotation = function getRotation(element) {
  13060. var transform = element.transformable;
  13061. return mat4.getRotation(transform.rotation, this.getWorldTransform(element, transform));
  13062. };
  13063. _proto.getScale = function getScale(element) {
  13064. var transform = element.transformable;
  13065. return mat4.getScaling(transform.scaling, this.getWorldTransform(element, transform));
  13066. };
  13067. _proto.getWorldTransform = function getWorldTransform(element, transform) {
  13068. if (transform === void 0) {
  13069. transform = element.transformable;
  13070. }
  13071. if (!transform.localDirtyFlag && !transform.dirtyFlag) {
  13072. return transform.worldTransform;
  13073. }
  13074. if (element.parentNode && element.parentNode.transformable) {
  13075. this.getWorldTransform(element.parentNode);
  13076. }
  13077. this.sync(element, transform);
  13078. return transform.worldTransform;
  13079. };
  13080. _proto.getLocalPosition = function getLocalPosition(element) {
  13081. return element.transformable.localPosition;
  13082. };
  13083. _proto.getLocalRotation = function getLocalRotation(element) {
  13084. return element.transformable.localRotation;
  13085. };
  13086. _proto.getLocalScale = function getLocalScale(element) {
  13087. return element.transformable.localScale;
  13088. };
  13089. _proto.getLocalSkew = function getLocalSkew(element) {
  13090. return element.transformable.localSkew;
  13091. };
  13092. _proto.getLocalTransform = function getLocalTransform(element) {
  13093. var transform = element.transformable;
  13094. if (transform.localDirtyFlag) {
  13095. this.calcLocalTransform(transform);
  13096. transform.localDirtyFlag = false;
  13097. }
  13098. return transform.localTransform;
  13099. };
  13100. _proto.setLocalTransform = function setLocalTransform(element, transform) {
  13101. var t = mat4.getTranslation(vec3.create(), transform);
  13102. var r = mat4.getRotation(quat$1.create(), transform);
  13103. var s = mat4.getScaling(vec3.create(), transform);
  13104. this.setLocalScale(element, s);
  13105. this.setLocalPosition(element, t);
  13106. this.setLocalRotation(element, r);
  13107. };
  13108. _proto.resetLocalTransform = function resetLocalTransform(element) {
  13109. this.setLocalScale(element, [1, 1, 1]);
  13110. this.setLocalPosition(element, [0, 0, 0]);
  13111. this.setLocalEulerAngles(element, [0, 0, 0]);
  13112. this.setLocalSkew(element, [0, 0]);
  13113. };
  13114. _proto.getTransformedGeometryBounds = function getTransformedGeometryBounds(element, render, existedAABB) {
  13115. if (render === void 0) {
  13116. render = false;
  13117. }
  13118. var bounds = this.getGeometryBounds(element, render);
  13119. if (!AABB.isEmpty(bounds)) {
  13120. var aabb = existedAABB || new AABB();
  13121. aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
  13122. return aabb;
  13123. } else {
  13124. return null;
  13125. }
  13126. }
  13127. /**
  13128. * won't account for children
  13129. */;
  13130. _proto.getGeometryBounds = function getGeometryBounds(element, render) {
  13131. if (render === void 0) {
  13132. render = false;
  13133. }
  13134. var geometry = element.geometry;
  13135. var bounds = render ? geometry.renderBounds : geometry.contentBounds || null;
  13136. // return (bounds && new AABB(bounds.center, bounds.halfExtents)) || new AABB();
  13137. return bounds || new AABB();
  13138. }
  13139. /**
  13140. * account for children in world space
  13141. */;
  13142. _proto.getBounds = function getBounds(element, render) {
  13143. var _this4 = this;
  13144. if (render === void 0) {
  13145. render = false;
  13146. }
  13147. var renderable = element.renderable;
  13148. if (!renderable.boundsDirty && !render && renderable.bounds) {
  13149. return renderable.bounds;
  13150. }
  13151. if (!renderable.renderBoundsDirty && render && renderable.renderBounds) {
  13152. return renderable.renderBounds;
  13153. }
  13154. // reuse existed if possible
  13155. var existedAABB = render ? renderable.renderBounds : renderable.bounds;
  13156. // reset with geometry's aabb
  13157. var aabb = this.getTransformedGeometryBounds(element, render, existedAABB);
  13158. // merge children's aabbs
  13159. var children = element.childNodes;
  13160. children.forEach(function (child) {
  13161. var childBounds = _this4.getBounds(child, render);
  13162. if (childBounds) {
  13163. if (!aabb) {
  13164. aabb = existedAABB || new AABB();
  13165. aabb.update(childBounds.center, childBounds.halfExtents);
  13166. } else {
  13167. aabb.add(childBounds);
  13168. }
  13169. }
  13170. });
  13171. if (render) {
  13172. // FIXME: account for clip path
  13173. var clipped = findClosestClipPathTarget(element);
  13174. if (clipped) {
  13175. // use bounds under world space
  13176. var clipPathBounds = clipped.parsedStyle.clipPath.getBounds(render);
  13177. if (!aabb) {
  13178. aabb = clipPathBounds;
  13179. } else if (clipPathBounds) {
  13180. aabb = clipPathBounds.intersection(aabb);
  13181. }
  13182. }
  13183. }
  13184. if (!aabb) {
  13185. aabb = new AABB();
  13186. }
  13187. if (aabb) {
  13188. if (render) {
  13189. renderable.renderBounds = aabb;
  13190. } else {
  13191. renderable.bounds = aabb;
  13192. }
  13193. }
  13194. if (render) {
  13195. renderable.renderBoundsDirty = false;
  13196. } else {
  13197. renderable.boundsDirty = false;
  13198. }
  13199. return aabb;
  13200. }
  13201. /**
  13202. * account for children in local space
  13203. */;
  13204. _proto.getLocalBounds = function getLocalBounds(element) {
  13205. if (element.parentNode) {
  13206. var parentInvert = mat4.create();
  13207. if (element.parentNode.transformable) {
  13208. parentInvert = mat4.invert(mat4.create(), this.getWorldTransform(element.parentNode));
  13209. }
  13210. var bounds = this.getBounds(element);
  13211. if (!AABB.isEmpty(bounds)) {
  13212. var localBounds = new AABB();
  13213. localBounds.setFromTransformedAABB(bounds, parentInvert);
  13214. return localBounds;
  13215. }
  13216. }
  13217. return this.getBounds(element);
  13218. };
  13219. _proto.getBoundingClientRect = function getBoundingClientRect(element) {
  13220. var _element$ownerDocumen, _element$ownerDocumen2;
  13221. var aabb;
  13222. var bounds = this.getGeometryBounds(element);
  13223. if (!AABB.isEmpty(bounds)) {
  13224. aabb = new AABB();
  13225. // apply transformation to aabb
  13226. aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
  13227. }
  13228. // calc context's offset
  13229. 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();
  13230. if (aabb) {
  13231. var _aabb$getMin = aabb.getMin(),
  13232. left = _aabb$getMin[0],
  13233. top = _aabb$getMin[1];
  13234. var _aabb$getMax = aabb.getMax(),
  13235. right = _aabb$getMax[0],
  13236. bottom = _aabb$getMax[1];
  13237. 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);
  13238. }
  13239. 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);
  13240. };
  13241. _proto.dirtifyWorldInternal = function dirtifyWorldInternal(element, transform) {
  13242. var _this5 = this;
  13243. if (!transform.dirtyFlag) {
  13244. transform.dirtyFlag = true;
  13245. transform.frozen = false;
  13246. element.childNodes.forEach(function (child) {
  13247. var childTransform = child.transformable;
  13248. if (!childTransform.dirtyFlag) {
  13249. _this5.dirtifyWorldInternal(child, childTransform);
  13250. }
  13251. });
  13252. var renderable = element.renderable;
  13253. if (renderable) {
  13254. renderable.renderBoundsDirty = true;
  13255. renderable.boundsDirty = true;
  13256. renderable.dirty = true;
  13257. }
  13258. }
  13259. };
  13260. _proto.syncHierarchy = function syncHierarchy(element) {
  13261. var transform = element.transformable;
  13262. if (transform.frozen) {
  13263. return;
  13264. }
  13265. transform.frozen = true;
  13266. if (transform.localDirtyFlag || transform.dirtyFlag) {
  13267. this.sync(element, transform);
  13268. }
  13269. var children = element.childNodes;
  13270. for (var i = 0; i < children.length; i++) {
  13271. this.syncHierarchy(children[i]);
  13272. }
  13273. };
  13274. _proto.sync = function sync(element, transform) {
  13275. if (transform.localDirtyFlag) {
  13276. this.calcLocalTransform(transform);
  13277. transform.localDirtyFlag = false;
  13278. }
  13279. if (transform.dirtyFlag) {
  13280. var parent = element.parentNode;
  13281. var parentTransform = parent && parent.transformable;
  13282. if (parent === null || !parentTransform) {
  13283. mat4.copy(transform.worldTransform, transform.localTransform);
  13284. } else {
  13285. // TODO: should we support scale compensation?
  13286. // @see https://github.com/playcanvas/engine/issues/1077#issuecomment-359765557
  13287. mat4.multiply(transform.worldTransform, parentTransform.worldTransform, transform.localTransform);
  13288. }
  13289. transform.dirtyFlag = false;
  13290. }
  13291. };
  13292. _proto.unfreezeParentToRoot = function unfreezeParentToRoot(child) {
  13293. var p = child.parentNode;
  13294. while (p) {
  13295. var transform = p.transformable;
  13296. if (transform) {
  13297. transform.frozen = false;
  13298. }
  13299. p = p.parentNode;
  13300. }
  13301. };
  13302. return DefaultSceneGraphService;
  13303. }();
  13304. var TEXT_METRICS = {
  13305. MetricsString: '|ÉqÅ',
  13306. BaselineSymbol: 'M',
  13307. BaselineMultiplier: 1.4,
  13308. HeightMultiplier: 2,
  13309. Newlines: [0x000a, 0x000d // carriage return
  13310. ],
  13311. BreakingSpaces: [0x0009, 0x0020, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2008, 0x2009, 0x200a, 0x205f, 0x3000 // ideographic space
  13312. ]
  13313. };
  13314. var LATIN_REGEX = /[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00f6\u00f8-\u00ff!"#$%&'()*+,-./:;]/;
  13315. // Line breaking rules in CJK (Kinsoku Shori)
  13316. // Refer from https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
  13317. var regexCannotStartZhCn = /[!%),.:;?\]}¢°·'""†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~]/;
  13318. var regexCannotEndZhCn = /[$(£¥·'"〈《「『【〔〖〝﹙﹛$(.[{£¥]/;
  13319. var regexCannotStartZhTw = /[!),.:;?\]}¢·–—'"•"、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、]/;
  13320. var regexCannotEndZhTw = /[([{£¥'"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏]/;
  13321. var regexCannotStartJaJp = /[)\]}〕〉》」』】〙〗〟'"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.]/;
  13322. var regexCannotEndJaJp = /[([{〔〈《「『【〘〖〝'"⦅«—...‥〳〴〵]/;
  13323. var regexCannotStartKoKr = /[!%),.:;?\]}¢°'"†‡℃〆〈《「『〕!%),.:;?]}]/;
  13324. var regexCannotEndKoKr = /[$([{£¥'"々〇〉》」〔$([{⦆¥₩#]/;
  13325. var regexCannotStart = new RegExp(regexCannotStartZhCn.source + "|" + regexCannotStartZhTw.source + "|" + regexCannotStartJaJp.source + "|" + regexCannotStartKoKr.source);
  13326. var regexCannotEnd = new RegExp(regexCannotEndZhCn.source + "|" + regexCannotEndZhTw.source + "|" + regexCannotEndJaJp.source + "|" + regexCannotEndKoKr.source);
  13327. /**
  13328. * Borrow from pixi/packages/text/src/TextMetrics.ts
  13329. */
  13330. var TextService = /*#__PURE__*/function () {
  13331. function TextService(runtime) {
  13332. var _this = this;
  13333. this.runtime = void 0;
  13334. /**
  13335. * font metrics cache
  13336. */
  13337. this.fontMetricsCache = {};
  13338. this.shouldBreakByKinsokuShorui = function (char, nextChar) {
  13339. if (_this.isBreakingSpace(nextChar)) return false;
  13340. if (char) {
  13341. // Line breaking rules in CJK (Kinsoku Shori)
  13342. if (regexCannotEnd.exec(nextChar) || regexCannotStart.exec(char)) {
  13343. return true;
  13344. }
  13345. }
  13346. return false;
  13347. };
  13348. this.trimByKinsokuShorui = function (prev) {
  13349. var next = [].concat(prev);
  13350. var prevLine = next[next.length - 2];
  13351. if (!prevLine) {
  13352. return prev;
  13353. }
  13354. var lastChar = prevLine[prevLine.length - 1];
  13355. next[next.length - 2] = prevLine.slice(0, -1);
  13356. next[next.length - 1] = lastChar + next[next.length - 1];
  13357. return next;
  13358. };
  13359. this.runtime = runtime;
  13360. }
  13361. var _proto = TextService.prototype;
  13362. /**
  13363. * Calculates the ascent, descent and fontSize of a given font-style.
  13364. */
  13365. _proto.measureFont = function measureFont(font, offscreenCanvas) {
  13366. // as this method is used for preparing assets, don't recalculate things if we don't need to
  13367. if (this.fontMetricsCache[font]) {
  13368. return this.fontMetricsCache[font];
  13369. }
  13370. var properties = {
  13371. ascent: 0,
  13372. descent: 0,
  13373. fontSize: 0
  13374. };
  13375. var canvas = this.runtime.offscreenCanvas.getOrCreateCanvas(offscreenCanvas);
  13376. var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas, {
  13377. willReadFrequently: true
  13378. });
  13379. context.font = font;
  13380. var metricsString = TEXT_METRICS.MetricsString + TEXT_METRICS.BaselineSymbol;
  13381. var width = Math.ceil(context.measureText(metricsString).width);
  13382. var baseline = Math.ceil(context.measureText(TEXT_METRICS.BaselineSymbol).width);
  13383. var height = TEXT_METRICS.HeightMultiplier * baseline;
  13384. baseline = baseline * TEXT_METRICS.BaselineMultiplier | 0;
  13385. // @ts-ignore
  13386. canvas.width = width;
  13387. // @ts-ignore
  13388. canvas.height = height;
  13389. context.fillStyle = '#f00';
  13390. context.fillRect(0, 0, width, height);
  13391. context.font = font;
  13392. context.textBaseline = 'alphabetic';
  13393. context.fillStyle = '#000';
  13394. context.fillText(metricsString, 0, baseline);
  13395. var imagedata = context.getImageData(0, 0, width || 1, height || 1).data;
  13396. var pixels = imagedata.length;
  13397. var line = width * 4;
  13398. var i = 0;
  13399. var idx = 0;
  13400. var stop = false;
  13401. // ascent. scan from top to bottom until we find a non red pixel
  13402. for (i = 0; i < baseline; ++i) {
  13403. for (var j = 0; j < line; j += 4) {
  13404. if (imagedata[idx + j] !== 255) {
  13405. stop = true;
  13406. break;
  13407. }
  13408. }
  13409. if (!stop) {
  13410. idx += line;
  13411. } else {
  13412. break;
  13413. }
  13414. }
  13415. properties.ascent = baseline - i;
  13416. idx = pixels - line;
  13417. stop = false;
  13418. // descent. scan from bottom to top until we find a non red pixel
  13419. for (i = height; i > baseline; --i) {
  13420. for (var _j = 0; _j < line; _j += 4) {
  13421. if (imagedata[idx + _j] !== 255) {
  13422. stop = true;
  13423. break;
  13424. }
  13425. }
  13426. if (!stop) {
  13427. idx -= line;
  13428. } else {
  13429. break;
  13430. }
  13431. }
  13432. properties.descent = i - baseline;
  13433. properties.fontSize = properties.ascent + properties.descent;
  13434. this.fontMetricsCache[font] = properties;
  13435. return properties;
  13436. };
  13437. _proto.measureText = function measureText(text, parsedStyle, offscreenCanvas) {
  13438. var fontSize = parsedStyle.fontSize,
  13439. wordWrap = parsedStyle.wordWrap,
  13440. strokeHeight = parsedStyle.lineHeight,
  13441. lineWidth = parsedStyle.lineWidth,
  13442. textBaseline = parsedStyle.textBaseline,
  13443. textAlign = parsedStyle.textAlign,
  13444. letterSpacing = parsedStyle.letterSpacing,
  13445. textPath = parsedStyle.textPath,
  13446. textPathSide = parsedStyle.textPathSide,
  13447. textPathStartOffset = parsedStyle.textPathStartOffset,
  13448. _parsedStyle$leading = parsedStyle.leading,
  13449. leading = _parsedStyle$leading === void 0 ? 0 : _parsedStyle$leading;
  13450. var font = toFontString(parsedStyle);
  13451. // if (runtime.enableCSSParsing) {
  13452. var fontProperties = this.measureFont(font, offscreenCanvas);
  13453. // fallback in case UA disallow canvas data extraction
  13454. // (toDataURI, getImageData functions)
  13455. if (fontProperties.fontSize === 0) {
  13456. fontProperties.fontSize = fontSize;
  13457. fontProperties.ascent = fontSize;
  13458. }
  13459. // } else {
  13460. // fontProperties = {
  13461. // fontSize,
  13462. // };
  13463. // }
  13464. var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
  13465. context.font = font;
  13466. // no overflowing by default
  13467. parsedStyle.isOverflowing = false;
  13468. var outputText = wordWrap ? this.wordWrap(text, parsedStyle, offscreenCanvas) : text;
  13469. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  13470. var lineWidths = new Array(lines.length);
  13471. var maxLineWidth = 0;
  13472. // account for textPath
  13473. if (textPath) {
  13474. var totalPathLength = textPath.getTotalLength();
  13475. // const startingPoint = textPath.getPoint(0);
  13476. for (var i = 0; i < lines.length; i++) {
  13477. var width = context.measureText(lines[i]).width + (lines[i].length - 1) * letterSpacing;
  13478. // for (
  13479. // let i = reverse ? lines[0].length - 1 : 0;
  13480. // reverse ? i >= 0 : i < lines[0].length;
  13481. // reverse ? i-- : i++
  13482. // ) {
  13483. // graphemeInfo = lineBounds[i];
  13484. // if (positionInPath > totalPathLength) {
  13485. // positionInPath %= totalPathLength;
  13486. // } else if (positionInPath < 0) {
  13487. // positionInPath += totalPathLength;
  13488. // }
  13489. // // it would probably much faster to send all the grapheme position for a line
  13490. // // and calculate path position/angle at once.
  13491. // this.setGraphemeOnPath(
  13492. // positionInPath,
  13493. // graphemeInfo,
  13494. // startingPoint
  13495. // );
  13496. // positionInPath += graphemeInfo.kernedWidth;
  13497. // }
  13498. }
  13499. } else {
  13500. for (var _i = 0; _i < lines.length; _i++) {
  13501. // char width + letterSpacing
  13502. var _lineWidth = context.measureText(lines[_i]).width + (lines[_i].length - 1) * letterSpacing;
  13503. lineWidths[_i] = _lineWidth;
  13504. maxLineWidth = Math.max(maxLineWidth, _lineWidth);
  13505. }
  13506. var _width = maxLineWidth + lineWidth;
  13507. // if (dropShadow) {
  13508. // width += dropShadowDistance;
  13509. // }
  13510. var lineHeight = strokeHeight || fontProperties.fontSize + lineWidth;
  13511. var height = Math.max(lineHeight, fontProperties.fontSize + lineWidth) + (lines.length - 1) * (lineHeight + leading);
  13512. // if (dropShadow) {
  13513. // height += dropShadowDistance;
  13514. // }
  13515. lineHeight += leading;
  13516. // handle vertical text baseline
  13517. var offsetY = 0;
  13518. if (textBaseline === 'middle') {
  13519. offsetY = -height / 2;
  13520. } else if (textBaseline === 'bottom' || textBaseline === 'alphabetic' || textBaseline === 'ideographic') {
  13521. offsetY = -height;
  13522. } else if (textBaseline === 'top' || textBaseline === 'hanging') {
  13523. offsetY = 0;
  13524. }
  13525. return {
  13526. font: font,
  13527. width: _width,
  13528. height: height,
  13529. lines: lines,
  13530. lineWidths: lineWidths,
  13531. lineHeight: lineHeight,
  13532. maxLineWidth: maxLineWidth,
  13533. fontProperties: fontProperties,
  13534. lineMetrics: lineWidths.map(function (width, i) {
  13535. var offsetX = 0;
  13536. // handle horizontal text align
  13537. if (textAlign === 'center' || textAlign === 'middle') {
  13538. offsetX -= width / 2;
  13539. } else if (textAlign === 'right' || textAlign === 'end') {
  13540. offsetX -= width;
  13541. }
  13542. return new Rectangle(offsetX - lineWidth / 2, offsetY + i * lineHeight, width + lineWidth, lineHeight);
  13543. })
  13544. };
  13545. }
  13546. };
  13547. _proto.setGraphemeOnPath = function setGraphemeOnPath() {};
  13548. _proto.wordWrap = function wordWrap(text, parsedStyle, offscreenCanvas) {
  13549. var _this2 = this;
  13550. var _parsedStyle$wordWrap = parsedStyle.wordWrapWidth,
  13551. wordWrapWidth = _parsedStyle$wordWrap === void 0 ? 0 : _parsedStyle$wordWrap,
  13552. letterSpacing = parsedStyle.letterSpacing,
  13553. _parsedStyle$maxLines = parsedStyle.maxLines,
  13554. maxLines = _parsedStyle$maxLines === void 0 ? Infinity : _parsedStyle$maxLines,
  13555. textOverflow = parsedStyle.textOverflow;
  13556. var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
  13557. var maxWidth = wordWrapWidth + letterSpacing;
  13558. var ellipsis = '';
  13559. if (textOverflow === 'ellipsis') {
  13560. ellipsis = '...';
  13561. } else if (textOverflow && textOverflow !== 'clip') {
  13562. ellipsis = textOverflow;
  13563. }
  13564. var lines = [];
  13565. var currentIndex = 0;
  13566. var currentWidth = 0;
  13567. var cache = {};
  13568. var calcWidth = function calcWidth(char) {
  13569. return _this2.getFromCache(char, letterSpacing, cache, context);
  13570. };
  13571. var ellipsisWidth = Array.from(ellipsis).reduce(function (prev, cur) {
  13572. return prev + calcWidth(cur);
  13573. }, 0);
  13574. var chars = Array.from(text);
  13575. for (var i = 0; i < chars.length; i++) {
  13576. var char = chars[i];
  13577. var prevChar = text[i - 1];
  13578. var nextChar = text[i + 1];
  13579. var charWidth = calcWidth(char);
  13580. if (this.isNewline(char)) {
  13581. currentIndex++;
  13582. // exceed maxLines, break immediately
  13583. if (currentIndex >= maxLines) {
  13584. parsedStyle.isOverflowing = true;
  13585. break;
  13586. }
  13587. currentWidth = 0;
  13588. lines[currentIndex] = '';
  13589. continue;
  13590. }
  13591. if (currentWidth > 0 && currentWidth + charWidth > maxWidth) {
  13592. if (currentIndex + 1 >= maxLines) {
  13593. parsedStyle.isOverflowing = true;
  13594. // If there is not enough space to display the string itself, it is clipped.
  13595. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#values
  13596. if (ellipsisWidth > 0 && ellipsisWidth <= maxWidth) {
  13597. // Backspace from line's end.
  13598. var currentLineLength = lines[currentIndex].length;
  13599. var lastLineWidth = 0;
  13600. var lastLineIndex = currentLineLength;
  13601. for (var _i2 = 0; _i2 < currentLineLength; _i2++) {
  13602. var width = calcWidth(lines[currentIndex][_i2]);
  13603. if (lastLineWidth + width + ellipsisWidth > maxWidth) {
  13604. lastLineIndex = _i2;
  13605. break;
  13606. }
  13607. lastLineWidth += width;
  13608. }
  13609. lines[currentIndex] = (lines[currentIndex] || '').slice(0, lastLineIndex) + ellipsis;
  13610. }
  13611. break;
  13612. }
  13613. currentIndex++;
  13614. currentWidth = 0;
  13615. lines[currentIndex] = '';
  13616. if (this.isBreakingSpace(char)) {
  13617. continue;
  13618. }
  13619. if (!this.canBreakInLastChar(char)) {
  13620. lines = this.trimToBreakable(lines);
  13621. currentWidth = this.sumTextWidthByCache(lines[currentIndex] || '', cache);
  13622. }
  13623. if (this.shouldBreakByKinsokuShorui(char, nextChar)) {
  13624. lines = this.trimByKinsokuShorui(lines);
  13625. currentWidth += calcWidth(prevChar || '');
  13626. }
  13627. }
  13628. currentWidth += charWidth;
  13629. lines[currentIndex] = (lines[currentIndex] || '') + char;
  13630. }
  13631. return lines.join('\n');
  13632. };
  13633. _proto.isBreakingSpace = function isBreakingSpace(char) {
  13634. if (typeof char !== 'string') {
  13635. return false;
  13636. }
  13637. return TEXT_METRICS.BreakingSpaces.indexOf(char.charCodeAt(0)) >= 0;
  13638. };
  13639. _proto.isNewline = function isNewline(char) {
  13640. if (typeof char !== 'string') {
  13641. return false;
  13642. }
  13643. return TEXT_METRICS.Newlines.indexOf(char.charCodeAt(0)) >= 0;
  13644. };
  13645. _proto.trimToBreakable = function trimToBreakable(prev) {
  13646. var next = [].concat(prev);
  13647. var prevLine = next[next.length - 2];
  13648. var index = this.findBreakableIndex(prevLine);
  13649. if (index === -1 || !prevLine) return next;
  13650. var trimmedChar = prevLine.slice(index, index + 1);
  13651. var isTrimmedWithSpace = this.isBreakingSpace(trimmedChar);
  13652. var trimFrom = index + 1;
  13653. var trimTo = index + (isTrimmedWithSpace ? 0 : 1);
  13654. next[next.length - 1] += prevLine.slice(trimFrom, prevLine.length);
  13655. next[next.length - 2] = prevLine.slice(0, trimTo);
  13656. return next;
  13657. };
  13658. _proto.canBreakInLastChar = function canBreakInLastChar(char) {
  13659. if (char && LATIN_REGEX.test(char)) return false;
  13660. return true;
  13661. };
  13662. _proto.sumTextWidthByCache = function sumTextWidthByCache(text, cache) {
  13663. return text.split('').reduce(function (sum, c) {
  13664. if (!cache[c]) throw Error('cannot count the word without cache');
  13665. return sum + cache[c];
  13666. }, 0);
  13667. };
  13668. _proto.findBreakableIndex = function findBreakableIndex(line) {
  13669. for (var i = line.length - 1; i >= 0; i--) {
  13670. if (!LATIN_REGEX.test(line[i])) return i;
  13671. }
  13672. return -1;
  13673. };
  13674. _proto.getFromCache = function getFromCache(key, letterSpacing, cache, context) {
  13675. var width = cache[key];
  13676. if (typeof width !== 'number') {
  13677. var spacing = key.length * letterSpacing;
  13678. width = context.measureText(key).width + spacing;
  13679. cache[key] = width;
  13680. }
  13681. return width;
  13682. };
  13683. return TextService;
  13684. }();
  13685. var _this = undefined;
  13686. var runtime = {};
  13687. /**
  13688. * Replace with IoC container
  13689. */
  13690. var geometryUpdaterFactory = function () {
  13691. var _ref;
  13692. var rectUpdater = new RectUpdater();
  13693. var polylineUpdater = new PolylineUpdater();
  13694. return _ref = {}, _ref[Shape.CIRCLE] = new CircleUpdater(), _ref[Shape.ELLIPSE] = new EllipseUpdater(), _ref[Shape.RECT] = rectUpdater, _ref[Shape.IMAGE] = rectUpdater, _ref[Shape.GROUP] = rectUpdater, _ref[Shape.LINE] = new LineUpdater(), _ref[Shape.TEXT] = new TextUpdater(runtime), _ref[Shape.POLYLINE] = polylineUpdater, _ref[Shape.POLYGON] = polylineUpdater, _ref[Shape.PATH] = new PathUpdater(), _ref[Shape.HTML] = null, _ref[Shape.MESH] = null, _ref;
  13695. }();
  13696. var CSSPropertySyntaxFactory = function () {
  13697. var _ref2;
  13698. var color = new CSSPropertyColor();
  13699. var length = new CSSPropertyLengthOrPercentage();
  13700. return _ref2 = {}, _ref2[PropertySyntax.PERCENTAGE] = null, _ref2[PropertySyntax.NUMBER] = new CSSPropertyNumber(), _ref2[PropertySyntax.ANGLE] = new CSSPropertyAngle(), _ref2[PropertySyntax.DEFINED_PATH] = new CSSPropertyClipPath(), _ref2[PropertySyntax.PAINT] = color, _ref2[PropertySyntax.COLOR] = color, _ref2[PropertySyntax.FILTER] = new CSSPropertyFilter(), _ref2[PropertySyntax.LENGTH] = length, _ref2[PropertySyntax.LENGTH_PERCENTAGE] = length, _ref2[PropertySyntax.LENGTH_PERCENTAGE_12] = new CSSPropertyLengthOrPercentage12(), _ref2[PropertySyntax.LENGTH_PERCENTAGE_14] = new CSSPropertyLengthOrPercentage14(), _ref2[PropertySyntax.COORDINATE] = new CSSPropertyLocalPosition(), _ref2[PropertySyntax.OFFSET_DISTANCE] = new CSSPropertyOffsetDistance(), _ref2[PropertySyntax.OPACITY_VALUE] = new CSSPropertyOpacity(), _ref2[PropertySyntax.PATH] = new CSSPropertyPath(), _ref2[PropertySyntax.LIST_OF_POINTS] = new CSSPropertyPoints(), _ref2[PropertySyntax.SHADOW_BLUR] = new CSSPropertyShadowBlur(), _ref2[PropertySyntax.TEXT] = new CSSPropertyText(), _ref2[PropertySyntax.TEXT_TRANSFORM] = new CSSPropertyTextTransform(), _ref2[PropertySyntax.TRANSFORM] = new CSSPropertyTransform(), _ref2[PropertySyntax.TRANSFORM_ORIGIN] = new CSSPropertyTransformOrigin(), _ref2[PropertySyntax.Z_INDEX] = new CSSPropertyZIndex(), _ref2[PropertySyntax.MARKER] = new CSSPropertyMarker(), _ref2;
  13701. }();
  13702. var getGlobalThis = function getGlobalThis() {
  13703. if (typeof globalThis !== 'undefined') return globalThis;
  13704. if (typeof self !== 'undefined') return self;
  13705. if (typeof window !== 'undefined') return window;
  13706. // @ts-ignore
  13707. if (typeof global !== 'undefined') return global;
  13708. if (typeof _this !== 'undefined') return _this;
  13709. throw new Error('Unable to locate global `this`');
  13710. };
  13711. /**
  13712. * Camera
  13713. * `g-camera-api` will provide an advanced implementation
  13714. */
  13715. runtime.CameraContribution = Camera;
  13716. /**
  13717. * `g-web-animations-api` will provide an AnimationTimeline
  13718. */
  13719. runtime.AnimationTimeline = null;
  13720. runtime.EasingFunction = null;
  13721. runtime.offscreenCanvas = new OffscreenCanvasCreator();
  13722. runtime.nativeHTMLMap = new WeakMap();
  13723. runtime.sceneGraphSelector = new DefaultSceneGraphSelector();
  13724. runtime.sceneGraphService = new DefaultSceneGraphService(runtime);
  13725. runtime.textService = new TextService(runtime);
  13726. runtime.geometryUpdaterFactory = geometryUpdaterFactory;
  13727. runtime.CSSPropertySyntaxFactory = CSSPropertySyntaxFactory;
  13728. runtime.styleValueRegistry = new DefaultStyleValueRegistry();
  13729. runtime.layoutRegistry = null;
  13730. runtime.globalThis = getGlobalThis();
  13731. runtime.enableCSSParsing = true;
  13732. runtime.enableDataset = false;
  13733. runtime.enableStyleSyntax = true;
  13734. var AbstractRendererPlugin = /*#__PURE__*/function () {
  13735. function AbstractRendererPlugin() {
  13736. this.context = void 0;
  13737. this.plugins = [];
  13738. }
  13739. var _proto = AbstractRendererPlugin.prototype;
  13740. _proto.addRenderingPlugin = function addRenderingPlugin(plugin) {
  13741. this.plugins.push(plugin);
  13742. this.context.renderingPlugins.push(plugin);
  13743. };
  13744. _proto.removeAllRenderingPlugins = function removeAllRenderingPlugins() {
  13745. var _this = this;
  13746. this.plugins.forEach(function (plugin) {
  13747. var index = _this.context.renderingPlugins.indexOf(plugin);
  13748. if (index >= 0) {
  13749. _this.context.renderingPlugins.splice(index, 1);
  13750. }
  13751. });
  13752. };
  13753. return AbstractRendererPlugin;
  13754. }();
  13755. var AbstractRenderer = /*#__PURE__*/function () {
  13756. function AbstractRenderer(config) {
  13757. this.plugins = [];
  13758. this.config = void 0;
  13759. this.config = _extends({
  13760. /**
  13761. * only dirty object will cause re-render
  13762. */
  13763. enableDirtyCheck: true,
  13764. enableCulling: false,
  13765. /**
  13766. * enable auto rendering by default
  13767. */
  13768. enableAutoRendering: true,
  13769. /**
  13770. * enable dirty rectangle rendering by default
  13771. */
  13772. enableDirtyRectangleRendering: true,
  13773. enableDirtyRectangleRenderingDebug: false
  13774. }, config);
  13775. }
  13776. var _proto2 = AbstractRenderer.prototype;
  13777. _proto2.registerPlugin = function registerPlugin(plugin) {
  13778. var index = this.plugins.findIndex(function (p) {
  13779. return p === plugin;
  13780. });
  13781. if (index === -1) {
  13782. this.plugins.push(plugin);
  13783. }
  13784. };
  13785. _proto2.unregisterPlugin = function unregisterPlugin(plugin) {
  13786. var index = this.plugins.findIndex(function (p) {
  13787. return p === plugin;
  13788. });
  13789. if (index > -1) {
  13790. this.plugins.splice(index, 1);
  13791. }
  13792. };
  13793. _proto2.getPlugins = function getPlugins() {
  13794. return this.plugins;
  13795. };
  13796. _proto2.getPlugin = function getPlugin(name) {
  13797. return this.plugins.find(function (plugin) {
  13798. return plugin.name === name;
  13799. });
  13800. };
  13801. _proto2.getConfig = function getConfig() {
  13802. return this.config;
  13803. };
  13804. _proto2.setConfig = function setConfig(config) {
  13805. Object.assign(this.config, config);
  13806. };
  13807. return AbstractRenderer;
  13808. }();
  13809. /**
  13810. * apply following rules:
  13811. * 1. `visibility` in scenegraph node
  13812. * 2. other custom culling strategies, eg. frustum culling
  13813. */
  13814. var CullingPlugin = /*#__PURE__*/function () {
  13815. function CullingPlugin(strategies) {
  13816. this.strategies = void 0;
  13817. this.strategies = strategies;
  13818. }
  13819. var _proto = CullingPlugin.prototype;
  13820. _proto.apply = function apply(context) {
  13821. var camera = context.camera,
  13822. renderingService = context.renderingService,
  13823. renderingContext = context.renderingContext;
  13824. var strategies = this.strategies;
  13825. renderingService.hooks.cull.tap(CullingPlugin.tag, function (object) {
  13826. if (object) {
  13827. var cullable = object.cullable;
  13828. // cullable.visible = true;
  13829. // const renderBounds = object.getRenderBounds();
  13830. // if (AABB.isEmpty(renderBounds)) {
  13831. // cullable.visible = false;
  13832. // } else {
  13833. // const isShape2D = shape2D.indexOf(object.nodeName as Shape) > -1;
  13834. // const [p0, p1, p2, p3] = camera.getFrustum().planes;
  13835. // tmpAABB.setMinMax([-p1.distance, -p3.distance, 0], [p0.distance, p2.distance, 0]);
  13836. // cullable.visible = isShape2D ? renderBounds.intersects(tmpAABB) : true;
  13837. // }
  13838. if (strategies.length === 0) {
  13839. cullable.visible = renderingContext.unculledEntities.indexOf(object.entity) > -1;
  13840. } else {
  13841. // eg. implemented by g-webgl(frustum culling)
  13842. cullable.visible = strategies.every(function (strategy) {
  13843. return strategy.isVisible(camera, object);
  13844. });
  13845. }
  13846. if (!object.isCulled() && object.isVisible()) {
  13847. return object;
  13848. } else {
  13849. // if (this.renderingContext.renderListLastFrame.indexOf(object) > -1) {
  13850. object.dispatchEvent(new CustomEvent(ElementEvent.CULLED));
  13851. // }
  13852. }
  13853. return null;
  13854. }
  13855. return object;
  13856. });
  13857. renderingService.hooks.afterRender.tap(CullingPlugin.tag, function (object) {
  13858. object.cullable.visibilityPlaneMask = -1;
  13859. });
  13860. };
  13861. return CullingPlugin;
  13862. }();
  13863. CullingPlugin.tag = 'Culling';
  13864. /**
  13865. * Filter dirty renderables and calculate the "dirty rectangle" which will be clear when frame began
  13866. */
  13867. var DirtyCheckPlugin = /*#__PURE__*/function () {
  13868. function DirtyCheckPlugin() {}
  13869. var _proto = DirtyCheckPlugin.prototype;
  13870. _proto.apply = function apply(context) {
  13871. var renderingService = context.renderingService;
  13872. renderingService.hooks.dirtycheck.tap(DirtyCheckPlugin.tag, function (object) {
  13873. if (object) {
  13874. var renderable = object.renderable;
  13875. var isDirty = renderable.dirty || renderingService.disableDirtyRectangleRendering();
  13876. if (isDirty) {
  13877. return object;
  13878. } else {
  13879. return null;
  13880. }
  13881. }
  13882. return object;
  13883. });
  13884. };
  13885. return DirtyCheckPlugin;
  13886. }();
  13887. DirtyCheckPlugin.tag = 'DirtyCheck';
  13888. /**
  13889. * support mouse & touch events
  13890. * @see https://github.com/pixijs/pixi.js/blob/dev/packages/interaction/README.md
  13891. *
  13892. * also provide some extra events such as `drag`
  13893. */
  13894. var EventPlugin = /*#__PURE__*/function () {
  13895. function EventPlugin() {
  13896. var _this = this;
  13897. this.autoPreventDefault = false;
  13898. this.rootPointerEvent = new FederatedPointerEvent(null);
  13899. this.rootWheelEvent = new FederatedWheelEvent(null);
  13900. this.context = void 0;
  13901. this.onPointerMove = function (nativeEvent) {
  13902. var _this$context$renderi, _this$context$renderi2;
  13903. 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;
  13904. if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
  13905. var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
  13906. for (var _iterator = _createForOfIteratorHelperLoose(normalizedEvents), _step; !(_step = _iterator()).done;) {
  13907. var normalizedEvent = _step.value;
  13908. var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13909. _this.context.eventService.mapEvent(event);
  13910. }
  13911. _this.setCursor(_this.context.eventService.cursor);
  13912. };
  13913. this.onClick = function (nativeEvent) {
  13914. var _this$context$renderi3, _this$context$renderi4;
  13915. 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;
  13916. var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
  13917. for (var _iterator2 = _createForOfIteratorHelperLoose(normalizedEvents), _step2; !(_step2 = _iterator2()).done;) {
  13918. var normalizedEvent = _step2.value;
  13919. var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13920. _this.context.eventService.mapEvent(event);
  13921. }
  13922. _this.setCursor(_this.context.eventService.cursor);
  13923. };
  13924. }
  13925. var _proto = EventPlugin.prototype;
  13926. _proto.apply = function apply(context) {
  13927. var _this2 = this;
  13928. this.context = context;
  13929. var renderingService = context.renderingService;
  13930. var canvas = this.context.renderingContext.root.ownerDocument.defaultView;
  13931. this.context.eventService.setPickHandler(function (position) {
  13932. var _this2$context$render = _this2.context.renderingService.hooks.pickSync.call({
  13933. position: position,
  13934. picked: [],
  13935. topmost: true // we only concern the topmost element
  13936. }),
  13937. picked = _this2$context$render.picked;
  13938. return picked[0] || null;
  13939. });
  13940. renderingService.hooks.pointerWheel.tap(EventPlugin.tag, function (nativeEvent) {
  13941. var wheelEvent = _this2.normalizeWheelEvent(nativeEvent);
  13942. _this2.context.eventService.mapEvent(wheelEvent);
  13943. });
  13944. renderingService.hooks.pointerDown.tap(EventPlugin.tag, function (nativeEvent) {
  13945. if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
  13946. var events = _this2.normalizeToPointerEvent(nativeEvent, canvas);
  13947. if (_this2.autoPreventDefault && events[0].isNormalized) {
  13948. var cancelable = nativeEvent.cancelable || !('cancelable' in nativeEvent);
  13949. if (cancelable) {
  13950. nativeEvent.preventDefault();
  13951. }
  13952. }
  13953. for (var _iterator3 = _createForOfIteratorHelperLoose(events), _step3; !(_step3 = _iterator3()).done;) {
  13954. var event = _step3.value;
  13955. var federatedEvent = _this2.bootstrapEvent(_this2.rootPointerEvent, event, canvas, nativeEvent);
  13956. _this2.context.eventService.mapEvent(federatedEvent);
  13957. }
  13958. _this2.setCursor(_this2.context.eventService.cursor);
  13959. });
  13960. renderingService.hooks.pointerUp.tap(EventPlugin.tag, function (nativeEvent) {
  13961. if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
  13962. // account for element in SVG
  13963. var $element = _this2.context.contextService.getDomElement();
  13964. var outside = 'outside';
  13965. try {
  13966. outside = $element && nativeEvent.target && nativeEvent.target !== $element && $element.contains && !$element.contains(nativeEvent.target) ? 'outside' : '';
  13967. } catch (e) {
  13968. // nativeEvent.target maybe not Node, such as Window
  13969. // @see https://github.com/antvis/G/issues/1235
  13970. }
  13971. var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
  13972. for (var _iterator4 = _createForOfIteratorHelperLoose(normalizedEvents), _step4; !(_step4 = _iterator4()).done;) {
  13973. var normalizedEvent = _step4.value;
  13974. var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13975. event.type += outside;
  13976. _this2.context.eventService.mapEvent(event);
  13977. }
  13978. _this2.setCursor(_this2.context.eventService.cursor);
  13979. });
  13980. renderingService.hooks.pointerMove.tap(EventPlugin.tag, this.onPointerMove);
  13981. renderingService.hooks.pointerOver.tap(EventPlugin.tag, this.onPointerMove);
  13982. renderingService.hooks.pointerOut.tap(EventPlugin.tag, this.onPointerMove);
  13983. renderingService.hooks.click.tap(EventPlugin.tag, this.onClick);
  13984. renderingService.hooks.pointerCancel.tap(EventPlugin.tag, function (nativeEvent) {
  13985. var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
  13986. for (var _iterator5 = _createForOfIteratorHelperLoose(normalizedEvents), _step5; !(_step5 = _iterator5()).done;) {
  13987. var normalizedEvent = _step5.value;
  13988. var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
  13989. _this2.context.eventService.mapEvent(event);
  13990. }
  13991. _this2.setCursor(_this2.context.eventService.cursor);
  13992. });
  13993. };
  13994. _proto.getViewportXY = function getViewportXY(nativeEvent) {
  13995. var x;
  13996. var y;
  13997. /**
  13998. * Should account for CSS Transform applied on container.
  13999. * @see https://github.com/antvis/G/issues/1161
  14000. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/offsetX
  14001. */
  14002. var offsetX = nativeEvent.offsetX,
  14003. offsetY = nativeEvent.offsetY,
  14004. clientX = nativeEvent.clientX,
  14005. clientY = nativeEvent.clientY;
  14006. if (this.context.config.supportsCSSTransform && !isNil(offsetX) && !isNil(offsetY)) {
  14007. x = offsetX;
  14008. y = offsetY;
  14009. } else {
  14010. var point = this.context.eventService.client2Viewport(new Point(clientX, clientY));
  14011. x = point.x;
  14012. y = point.y;
  14013. }
  14014. return {
  14015. x: x,
  14016. y: y
  14017. };
  14018. };
  14019. _proto.bootstrapEvent = function bootstrapEvent(event, normalizedEvent, view, nativeEvent) {
  14020. event.view = view;
  14021. event.originalEvent = null;
  14022. event.nativeEvent = nativeEvent;
  14023. event.pointerId = normalizedEvent.pointerId;
  14024. event.width = normalizedEvent.width;
  14025. event.height = normalizedEvent.height;
  14026. event.isPrimary = normalizedEvent.isPrimary;
  14027. event.pointerType = normalizedEvent.pointerType;
  14028. event.pressure = normalizedEvent.pressure;
  14029. event.tangentialPressure = normalizedEvent.tangentialPressure;
  14030. event.tiltX = normalizedEvent.tiltX;
  14031. event.tiltY = normalizedEvent.tiltY;
  14032. event.twist = normalizedEvent.twist;
  14033. this.transferMouseData(event, normalizedEvent);
  14034. var _this$getViewportXY = this.getViewportXY(normalizedEvent),
  14035. x = _this$getViewportXY.x,
  14036. y = _this$getViewportXY.y;
  14037. event.viewport.x = x;
  14038. event.viewport.y = y;
  14039. var _this$context$eventSe = this.context.eventService.viewport2Canvas(event.viewport),
  14040. canvasX = _this$context$eventSe.x,
  14041. canvasY = _this$context$eventSe.y;
  14042. event.canvas.x = canvasX;
  14043. event.canvas.y = canvasY;
  14044. event.global.copyFrom(event.canvas);
  14045. event.offset.copyFrom(event.canvas);
  14046. event.isTrusted = nativeEvent.isTrusted;
  14047. if (event.type === 'pointerleave') {
  14048. event.type = 'pointerout';
  14049. }
  14050. if (event.type.startsWith('mouse')) {
  14051. event.type = event.type.replace('mouse', 'pointer');
  14052. }
  14053. if (event.type.startsWith('touch')) {
  14054. event.type = TOUCH_TO_POINTER[event.type] || event.type;
  14055. }
  14056. return event;
  14057. };
  14058. _proto.normalizeWheelEvent = function normalizeWheelEvent(nativeEvent) {
  14059. var event = this.rootWheelEvent;
  14060. this.transferMouseData(event, nativeEvent);
  14061. event.deltaMode = nativeEvent.deltaMode;
  14062. event.deltaX = nativeEvent.deltaX;
  14063. event.deltaY = nativeEvent.deltaY;
  14064. event.deltaZ = nativeEvent.deltaZ;
  14065. var _this$getViewportXY2 = this.getViewportXY(nativeEvent),
  14066. x = _this$getViewportXY2.x,
  14067. y = _this$getViewportXY2.y;
  14068. event.viewport.x = x;
  14069. event.viewport.y = y;
  14070. var _this$context$eventSe2 = this.context.eventService.viewport2Canvas(event.viewport),
  14071. canvasX = _this$context$eventSe2.x,
  14072. canvasY = _this$context$eventSe2.y;
  14073. event.canvas.x = canvasX;
  14074. event.canvas.y = canvasY;
  14075. event.global.copyFrom(event.canvas);
  14076. event.offset.copyFrom(event.canvas);
  14077. event.nativeEvent = nativeEvent;
  14078. event.type = nativeEvent.type;
  14079. return event;
  14080. }
  14081. /**
  14082. * Transfers base & mouse event data from the nativeEvent to the federated event.
  14083. */;
  14084. _proto.transferMouseData = function transferMouseData(event, nativeEvent) {
  14085. event.isTrusted = nativeEvent.isTrusted;
  14086. event.srcElement = nativeEvent.srcElement;
  14087. event.timeStamp = performance.now();
  14088. event.type = nativeEvent.type;
  14089. event.altKey = nativeEvent.altKey;
  14090. event.metaKey = nativeEvent.metaKey;
  14091. event.shiftKey = nativeEvent.shiftKey;
  14092. event.ctrlKey = nativeEvent.ctrlKey;
  14093. event.button = nativeEvent.button;
  14094. event.buttons = nativeEvent.buttons;
  14095. event.client.x = nativeEvent.clientX;
  14096. event.client.y = nativeEvent.clientY;
  14097. event.movement.x = nativeEvent.movementX;
  14098. event.movement.y = nativeEvent.movementY;
  14099. event.page.x = nativeEvent.pageX;
  14100. event.page.y = nativeEvent.pageY;
  14101. event.screen.x = nativeEvent.screenX;
  14102. event.screen.y = nativeEvent.screenY;
  14103. event.relatedTarget = null;
  14104. };
  14105. _proto.setCursor = function setCursor(cursor) {
  14106. this.context.contextService.applyCursorStyle(cursor || this.context.config.cursor || 'default');
  14107. };
  14108. _proto.normalizeToPointerEvent = function normalizeToPointerEvent(event, canvas) {
  14109. var normalizedEvents = [];
  14110. if (canvas.isTouchEvent(event)) {
  14111. for (var i = 0; i < event.changedTouches.length; i++) {
  14112. var touch = event.changedTouches[i];
  14113. // use changedTouches instead of touches since touchend has no touches
  14114. // @see https://stackoverflow.com/a/10079076
  14115. if (isUndefined(touch.button)) touch.button = 0;
  14116. if (isUndefined(touch.buttons)) touch.buttons = 1;
  14117. if (isUndefined(touch.isPrimary)) {
  14118. touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
  14119. }
  14120. if (isUndefined(touch.width)) touch.width = touch.radiusX || 1;
  14121. if (isUndefined(touch.height)) touch.height = touch.radiusY || 1;
  14122. if (isUndefined(touch.tiltX)) touch.tiltX = 0;
  14123. if (isUndefined(touch.tiltY)) touch.tiltY = 0;
  14124. if (isUndefined(touch.pointerType)) touch.pointerType = 'touch';
  14125. // @see https://developer.mozilla.org/zh-CN/docs/Web/API/Touch/identifier
  14126. if (isUndefined(touch.pointerId)) touch.pointerId = touch.identifier || 0;
  14127. if (isUndefined(touch.pressure)) touch.pressure = touch.force || 0.5;
  14128. if (isUndefined(touch.twist)) touch.twist = 0;
  14129. if (isUndefined(touch.tangentialPressure)) touch.tangentialPressure = 0;
  14130. touch.isNormalized = true;
  14131. touch.type = event.type;
  14132. normalizedEvents.push(touch);
  14133. }
  14134. } else if (canvas.isMouseEvent(event)) {
  14135. var tempEvent = event;
  14136. if (isUndefined(tempEvent.isPrimary)) tempEvent.isPrimary = true;
  14137. if (isUndefined(tempEvent.width)) tempEvent.width = 1;
  14138. if (isUndefined(tempEvent.height)) tempEvent.height = 1;
  14139. if (isUndefined(tempEvent.tiltX)) tempEvent.tiltX = 0;
  14140. if (isUndefined(tempEvent.tiltY)) tempEvent.tiltY = 0;
  14141. if (isUndefined(tempEvent.pointerType)) tempEvent.pointerType = 'mouse';
  14142. if (isUndefined(tempEvent.pointerId)) tempEvent.pointerId = MOUSE_POINTER_ID;
  14143. if (isUndefined(tempEvent.pressure)) tempEvent.pressure = 0.5;
  14144. if (isUndefined(tempEvent.twist)) tempEvent.twist = 0;
  14145. if (isUndefined(tempEvent.tangentialPressure)) tempEvent.tangentialPressure = 0;
  14146. tempEvent.isNormalized = true;
  14147. normalizedEvents.push(tempEvent);
  14148. } else {
  14149. normalizedEvents.push(event);
  14150. }
  14151. return normalizedEvents;
  14152. };
  14153. return EventPlugin;
  14154. }();
  14155. EventPlugin.tag = 'Event';
  14156. // group is not a 2d shape
  14157. var shape2D = [Shape.CIRCLE, Shape.ELLIPSE, Shape.IMAGE, Shape.RECT, Shape.LINE, Shape.POLYLINE, Shape.POLYGON, Shape.TEXT, Shape.PATH, Shape.HTML];
  14158. var FrustumCullingStrategy = /*#__PURE__*/function () {
  14159. function FrustumCullingStrategy() {}
  14160. var _proto = FrustumCullingStrategy.prototype;
  14161. _proto.isVisible = function isVisible(camera, object) {
  14162. var _object$parentNode, _object$parentNode$cu;
  14163. // return true;
  14164. var cullable = object.cullable;
  14165. if (!cullable.enable) {
  14166. return true;
  14167. }
  14168. var renderBounds = object.getRenderBounds();
  14169. if (AABB.isEmpty(renderBounds)) {
  14170. return false;
  14171. }
  14172. // get VP matrix from camera
  14173. var frustum = camera.getFrustum();
  14174. 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;
  14175. cullable.visibilityPlaneMask = this.computeVisibilityWithPlaneMask(object, renderBounds, parentVisibilityPlaneMask || Mask.INDETERMINATE, frustum.planes);
  14176. cullable.visible = cullable.visibilityPlaneMask !== Mask.OUTSIDE;
  14177. return cullable.visible;
  14178. }
  14179. /**
  14180. *
  14181. * @see「Optimized View Frustum Culling Algorithms for Bounding Boxes」
  14182. * @see https://github.com/antvis/GWebGPUEngine/issues/3
  14183. *
  14184. * * 基础相交测试 the basic intersection test
  14185. * * 标记 masking @see https://cesium.com/blog/2015/08/04/fast-hierarchical-culling/
  14186. * * TODO: 平面一致性测试 the plane-coherency test
  14187. * * TODO: 支持 mesh 指定自身的剔除策略,参考 Babylon.js @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
  14188. *
  14189. * @param aabb aabb
  14190. * @param parentPlaneMask mask of parent
  14191. * @param planes planes of frustum
  14192. */;
  14193. _proto.computeVisibilityWithPlaneMask = function computeVisibilityWithPlaneMask(object, aabb, parentPlaneMask, planes) {
  14194. if (parentPlaneMask === Mask.OUTSIDE || parentPlaneMask === Mask.INSIDE) {
  14195. // 父节点完全位于视锥内或者外部,直接返回
  14196. return parentPlaneMask;
  14197. }
  14198. // Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
  14199. // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
  14200. var mask = Mask.INSIDE;
  14201. var isShape2D = shape2D.indexOf(object.nodeName) > -1;
  14202. // Use viewport culling for 2D shapes
  14203. // @see https://github.com/antvis/g/issues/914
  14204. for (var k = 0, len = planes.length; k < len; ++k) {
  14205. // For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.
  14206. var flag = 1 << k;
  14207. if ((parentPlaneMask & flag) === 0) {
  14208. // 父节点处于当前面内部,可以跳过
  14209. continue;
  14210. }
  14211. // skip near & far planes when testing 2D shapes
  14212. if (isShape2D && (k === 4 || k === 5)) {
  14213. continue;
  14214. }
  14215. // p-vertex n-vertex <-|plane p-vertex n-vertex
  14216. // 使用 p-vertex 和 n-vertex 加速,避免进行平面和 aabb 全部顶点的相交检测
  14217. var _planes$k = planes[k],
  14218. normal = _planes$k.normal,
  14219. distance = _planes$k.distance;
  14220. if (vec3.dot(normal, aabb.getPositiveFarPoint(planes[k])) + distance < 0) {
  14221. return Mask.OUTSIDE;
  14222. }
  14223. if (vec3.dot(normal, aabb.getNegativeFarPoint(planes[k])) + distance < 0) {
  14224. // 和当前面相交,对应位置为1,继续检测下一个面
  14225. mask |= flag;
  14226. }
  14227. }
  14228. return mask;
  14229. };
  14230. return FrustumCullingStrategy;
  14231. }();
  14232. var PrepareRendererPlugin = /*#__PURE__*/function () {
  14233. function PrepareRendererPlugin() {
  14234. this.rBush = void 0;
  14235. /**
  14236. * sync to RBush later
  14237. */
  14238. this.toSync = new Set();
  14239. }
  14240. var _proto = PrepareRendererPlugin.prototype;
  14241. // private isFirstTimeRendering = true;
  14242. // private syncing = false;
  14243. _proto.apply = function apply(context) {
  14244. var _this = this;
  14245. var renderingService = context.renderingService,
  14246. renderingContext = context.renderingContext,
  14247. rBushRoot = context.rBushRoot;
  14248. var canvas = renderingContext.root.ownerDocument.defaultView;
  14249. this.rBush = rBushRoot;
  14250. var handleAttributeChanged = function handleAttributeChanged(e) {
  14251. var object = e.target;
  14252. object.renderable.dirty = true;
  14253. renderingService.dirtify();
  14254. };
  14255. var handleBoundsChanged = function handleBoundsChanged(e) {
  14256. var affectChildren = e.detail.affectChildren;
  14257. var object = e.target;
  14258. if (affectChildren) {
  14259. object.forEach(function (node) {
  14260. _this.toSync.add(node);
  14261. });
  14262. }
  14263. var p = object;
  14264. while (p) {
  14265. if (p.renderable) {
  14266. _this.toSync.add(p);
  14267. }
  14268. p = p.parentElement;
  14269. }
  14270. // this.pushToSync(e.composedPath().slice(0, -2) as DisplayObject[]);
  14271. renderingService.dirtify();
  14272. };
  14273. var handleMounted = function handleMounted(e) {
  14274. var object = e.target;
  14275. if (runtime.enableCSSParsing) {
  14276. // recalc style values
  14277. runtime.styleValueRegistry.recalc(object);
  14278. }
  14279. runtime.sceneGraphService.dirtifyToRoot(object);
  14280. renderingService.dirtify();
  14281. };
  14282. var handleUnmounted = function handleUnmounted(e) {
  14283. var object = e.target;
  14284. var rBushNode = object.rBushNode;
  14285. if (rBushNode.aabb) {
  14286. _this.rBush.remove(rBushNode.aabb);
  14287. }
  14288. _this.toSync.delete(object);
  14289. runtime.sceneGraphService.dirtifyToRoot(object);
  14290. renderingService.dirtify();
  14291. };
  14292. renderingService.hooks.init.tap(PrepareRendererPlugin.tag, function () {
  14293. canvas.addEventListener(ElementEvent.MOUNTED, handleMounted);
  14294. canvas.addEventListener(ElementEvent.UNMOUNTED, handleUnmounted);
  14295. canvas.addEventListener(ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
  14296. canvas.addEventListener(ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
  14297. });
  14298. renderingService.hooks.destroy.tap(PrepareRendererPlugin.tag, function () {
  14299. canvas.removeEventListener(ElementEvent.MOUNTED, handleMounted);
  14300. canvas.removeEventListener(ElementEvent.UNMOUNTED, handleUnmounted);
  14301. canvas.removeEventListener(ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
  14302. canvas.removeEventListener(ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
  14303. _this.toSync.clear();
  14304. });
  14305. renderingService.hooks.endFrame.tap(PrepareRendererPlugin.tag, function () {
  14306. // if (this.isFirstTimeRendering) {
  14307. // this.isFirstTimeRendering = false;
  14308. // this.syncing = true;
  14309. // // @see https://github.com/antvis/G/issues/1117
  14310. // setTimeout(() => {
  14311. // this.syncRTree();
  14312. // console.log('fcp...');
  14313. // });
  14314. // } else {
  14315. // console.log('next...');
  14316. _this.syncRTree();
  14317. // }
  14318. });
  14319. };
  14320. _proto.syncRTree = function syncRTree() {
  14321. var _this2 = this;
  14322. // if (this.syncing) {
  14323. // return;
  14324. // }
  14325. // bounds changed, need re-inserting its children
  14326. var bulk = [];
  14327. Array.from(this.toSync)
  14328. // some objects may be removed since last frame
  14329. .filter(function (object) {
  14330. return object.isConnected;
  14331. }).forEach(function (node) {
  14332. var rBushNode = node.rBushNode;
  14333. // clear dirty node
  14334. if (rBushNode && rBushNode.aabb) {
  14335. _this2.rBush.remove(rBushNode.aabb);
  14336. }
  14337. var renderBounds = node.getRenderBounds();
  14338. if (renderBounds) {
  14339. var _renderBounds$getMin = renderBounds.getMin(),
  14340. minX = _renderBounds$getMin[0],
  14341. minY = _renderBounds$getMin[1];
  14342. var _renderBounds$getMax = renderBounds.getMax(),
  14343. maxX = _renderBounds$getMax[0],
  14344. maxY = _renderBounds$getMax[1];
  14345. if (!rBushNode.aabb) {
  14346. rBushNode.aabb = {};
  14347. }
  14348. rBushNode.aabb.displayObject = node;
  14349. rBushNode.aabb.minX = minX;
  14350. rBushNode.aabb.minY = minY;
  14351. rBushNode.aabb.maxX = maxX;
  14352. rBushNode.aabb.maxY = maxY;
  14353. }
  14354. if (rBushNode.aabb) {
  14355. // TODO: NaN occurs when width/height of Rect is 0
  14356. if (!isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.minX) && !isNaN(rBushNode.aabb.minY)) {
  14357. bulk.push(rBushNode.aabb);
  14358. }
  14359. }
  14360. });
  14361. // use bulk inserting, which is ~2-3 times faster
  14362. // @see https://github.com/mourner/rbush#bulk-inserting-data
  14363. this.rBush.load(bulk);
  14364. bulk.length = 0;
  14365. this.toSync.clear();
  14366. // this.syncing = false;
  14367. };
  14368. return PrepareRendererPlugin;
  14369. }();
  14370. PrepareRendererPlugin.tag = 'Prepare';
  14371. function isCanvas(value) {
  14372. return !!value.document;
  14373. }
  14374. var CanvasEvent;
  14375. (function (CanvasEvent) {
  14376. CanvasEvent["READY"] = "ready";
  14377. CanvasEvent["BEFORE_RENDER"] = "beforerender";
  14378. CanvasEvent["RERENDER"] = "rerender";
  14379. CanvasEvent["AFTER_RENDER"] = "afterrender";
  14380. CanvasEvent["BEFORE_DESTROY"] = "beforedestroy";
  14381. CanvasEvent["AFTER_DESTROY"] = "afterdestroy";
  14382. CanvasEvent["RESIZE"] = "resize";
  14383. CanvasEvent["DIRTY_RECTANGLE"] = "dirtyrectangle";
  14384. CanvasEvent["RENDERER_CHANGED"] = "rendererchanged";
  14385. })(CanvasEvent || (CanvasEvent = {}));
  14386. var DEFAULT_CAMERA_Z = 500;
  14387. var DEFAULT_CAMERA_NEAR = 0.1;
  14388. var DEFAULT_CAMERA_FAR = 1000;
  14389. /**
  14390. * reuse custom event preventing from re-create them in every frame
  14391. */
  14392. var mountedEvent = new CustomEvent(ElementEvent.MOUNTED);
  14393. var unmountedEvent = new CustomEvent(ElementEvent.UNMOUNTED);
  14394. var beforeRenderEvent = new CustomEvent(CanvasEvent.BEFORE_RENDER);
  14395. var rerenderEvent = new CustomEvent(CanvasEvent.RERENDER);
  14396. var afterRenderEvent = new CustomEvent(CanvasEvent.AFTER_RENDER);
  14397. /**
  14398. * can be treated like Window in DOM
  14399. * provide some extra methods like `window`, such as:
  14400. * * `window.requestAnimationFrame`
  14401. * * `window.devicePixelRatio`
  14402. *
  14403. * prototype chains: Canvas(Window) -> EventTarget
  14404. */
  14405. var Canvas = /*#__PURE__*/function (_EventTarget) {
  14406. _inheritsLoose(Canvas, _EventTarget);
  14407. function Canvas(config) {
  14408. var _this;
  14409. _this = _EventTarget.call(this) || this;
  14410. // create document
  14411. /**
  14412. * window.document
  14413. */
  14414. _this.document = void 0;
  14415. /**
  14416. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
  14417. */
  14418. _this.customElements = void 0;
  14419. /**
  14420. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
  14421. */
  14422. _this.requestAnimationFrame = void 0;
  14423. /**
  14424. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
  14425. */
  14426. _this.cancelAnimationFrame = void 0;
  14427. /**
  14428. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  14429. */
  14430. _this.devicePixelRatio = void 0;
  14431. /**
  14432. * whether the runtime supports PointerEvent?
  14433. * if not, the event system won't trigger pointer events like `pointerdown`
  14434. */
  14435. _this.supportsPointerEvents = void 0;
  14436. /**
  14437. * whether the runtime supports TouchEvent?
  14438. * if not, the event system won't trigger touch events like `touchstart`
  14439. */
  14440. _this.supportsTouchEvents = void 0;
  14441. /**
  14442. * is this native event a TouchEvent?
  14443. */
  14444. _this.isTouchEvent = void 0;
  14445. /**
  14446. * is this native event a MouseEvent?
  14447. */
  14448. _this.isMouseEvent = void 0;
  14449. /**
  14450. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element
  14451. */
  14452. _this.Element = DisplayObject;
  14453. /**
  14454. * rAF in auto rendering
  14455. */
  14456. _this.frameId = void 0;
  14457. _this.inited = false;
  14458. _this.readyPromise = void 0;
  14459. _this.resolveReadyPromise = void 0;
  14460. _this.context = {};
  14461. _this.document = new Document();
  14462. _this.document.defaultView = _assertThisInitialized(_this);
  14463. // create registry of custom elements
  14464. _this.customElements = new CustomElementRegistry();
  14465. var container = config.container,
  14466. canvas = config.canvas,
  14467. offscreenCanvas = config.offscreenCanvas,
  14468. width = config.width,
  14469. height = config.height,
  14470. devicePixelRatio = config.devicePixelRatio,
  14471. renderer = config.renderer,
  14472. background = config.background,
  14473. cursor = config.cursor,
  14474. document = config.document,
  14475. requestAnimationFrame = config.requestAnimationFrame,
  14476. cancelAnimationFrame = config.cancelAnimationFrame,
  14477. createImage = config.createImage,
  14478. supportsPointerEvents = config.supportsPointerEvents,
  14479. supportsTouchEvents = config.supportsTouchEvents,
  14480. supportsCSSTransform = config.supportsCSSTransform,
  14481. useNativeClickEvent = config.useNativeClickEvent,
  14482. alwaysTriggerPointerEventOnCanvas = config.alwaysTriggerPointerEventOnCanvas,
  14483. isTouchEvent = config.isTouchEvent,
  14484. isMouseEvent = config.isMouseEvent;
  14485. cleanExistedCanvas(container, _assertThisInitialized(_this));
  14486. var canvasWidth = width;
  14487. var canvasHeight = height;
  14488. var dpr = devicePixelRatio;
  14489. // use user-defined <canvas> or OffscreenCanvas
  14490. if (canvas) {
  14491. // infer width & height with dpr
  14492. dpr = devicePixelRatio || isBrowser && window.devicePixelRatio || 1;
  14493. dpr = dpr >= 1 ? Math.ceil(dpr) : 1;
  14494. canvasWidth = width || getWidth(canvas) || canvas.width / dpr;
  14495. canvasHeight = height || getHeight(canvas) || canvas.height / dpr;
  14496. }
  14497. /**
  14498. * implements `Window` interface
  14499. */
  14500. _this.devicePixelRatio = dpr;
  14501. _this.requestAnimationFrame = requestAnimationFrame !== null && requestAnimationFrame !== void 0 ? requestAnimationFrame : raf.bind(runtime.globalThis);
  14502. _this.cancelAnimationFrame = cancelAnimationFrame !== null && cancelAnimationFrame !== void 0 ? cancelAnimationFrame : caf.bind(runtime.globalThis);
  14503. /**
  14504. * limits query
  14505. */
  14506. // the following feature-detect from hammer.js
  14507. // @see https://github.com/hammerjs/hammer.js/blob/master/src/inputjs/input-consts.js#L5
  14508. _this.supportsTouchEvents = supportsTouchEvents !== null && supportsTouchEvents !== void 0 ? supportsTouchEvents : 'ontouchstart' in runtime.globalThis;
  14509. _this.supportsPointerEvents = supportsPointerEvents !== null && supportsPointerEvents !== void 0 ? supportsPointerEvents : !!runtime.globalThis.PointerEvent;
  14510. _this.isTouchEvent = isTouchEvent !== null && isTouchEvent !== void 0 ? isTouchEvent : function (event) {
  14511. return _this.supportsTouchEvents && event instanceof runtime.globalThis.TouchEvent;
  14512. };
  14513. _this.isMouseEvent = isMouseEvent !== null && isMouseEvent !== void 0 ? isMouseEvent : function (event) {
  14514. return !runtime.globalThis.MouseEvent || event instanceof runtime.globalThis.MouseEvent && (!_this.supportsPointerEvents || !(event instanceof runtime.globalThis.PointerEvent));
  14515. };
  14516. _this.initRenderingContext({
  14517. container: container,
  14518. canvas: canvas,
  14519. width: canvasWidth,
  14520. height: canvasHeight,
  14521. renderer: renderer,
  14522. offscreenCanvas: offscreenCanvas,
  14523. devicePixelRatio: dpr,
  14524. cursor: cursor || 'default',
  14525. background: background || 'transparent',
  14526. createImage: createImage,
  14527. document: document,
  14528. supportsCSSTransform: supportsCSSTransform,
  14529. useNativeClickEvent: useNativeClickEvent,
  14530. alwaysTriggerPointerEventOnCanvas: alwaysTriggerPointerEventOnCanvas
  14531. });
  14532. _this.initDefaultCamera(canvasWidth, canvasHeight);
  14533. _this.initRenderer(renderer, true);
  14534. return _this;
  14535. }
  14536. var _proto = Canvas.prototype;
  14537. _proto.initRenderingContext = function initRenderingContext(mergedConfig) {
  14538. this.context.config = mergedConfig;
  14539. // bind rendering context, shared by all renderers
  14540. this.context.renderingContext = {
  14541. /**
  14542. * the root node in scene graph
  14543. */
  14544. root: this.document.documentElement,
  14545. renderListCurrentFrame: [],
  14546. unculledEntities: [],
  14547. renderReasons: new Set(),
  14548. force: false,
  14549. dirty: false
  14550. };
  14551. };
  14552. _proto.initDefaultCamera = function initDefaultCamera(width, height) {
  14553. var _this2 = this;
  14554. // set a default ortho camera
  14555. var camera = new runtime.CameraContribution();
  14556. camera.setType(CameraType.EXPLORING, 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);
  14557. // keep ref since it will use raf in camera animation
  14558. camera.canvas = this;
  14559. // redraw when camera changed
  14560. camera.eventEmitter.on(CameraEvent.UPDATED, function () {
  14561. _this2.context.renderingContext.renderReasons.add(RenderReason.CAMERA_CHANGED);
  14562. });
  14563. // bind camera
  14564. this.context.camera = camera;
  14565. };
  14566. _proto.getConfig = function getConfig() {
  14567. return this.context.config;
  14568. }
  14569. /**
  14570. * get the root displayObject in scenegraph
  14571. * @alias this.document.documentElement
  14572. */;
  14573. _proto.getRoot = function getRoot() {
  14574. return this.document.documentElement;
  14575. }
  14576. /**
  14577. * get the camera of canvas
  14578. */;
  14579. _proto.getCamera = function getCamera() {
  14580. return this.context.camera;
  14581. };
  14582. _proto.getContextService = function getContextService() {
  14583. return this.context.contextService;
  14584. };
  14585. _proto.getEventService = function getEventService() {
  14586. return this.context.eventService;
  14587. };
  14588. _proto.getRenderingService = function getRenderingService() {
  14589. return this.context.renderingService;
  14590. };
  14591. _proto.getRenderingContext = function getRenderingContext() {
  14592. return this.context.renderingContext;
  14593. };
  14594. _proto.getStats = function getStats() {
  14595. return this.getRenderingService().getStats();
  14596. }
  14597. // /**
  14598. // * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
  14599. // */
  14600. // getComputedStyle(node: DisplayObject) {
  14601. // return node.computedStyle;
  14602. // }
  14603. ;
  14604. /**
  14605. * `cleanUp` means clean all the internal services of Canvas which happens when calling `canvas.destroy()`.
  14606. */
  14607. _proto.destroy = function destroy(cleanUp, skipTriggerEvent) {
  14608. if (cleanUp === void 0) {
  14609. cleanUp = true;
  14610. }
  14611. if (skipTriggerEvent === void 0) {
  14612. skipTriggerEvent = false;
  14613. }
  14614. if (!skipTriggerEvent) {
  14615. this.dispatchEvent(new CustomEvent(CanvasEvent.BEFORE_DESTROY));
  14616. }
  14617. if (this.frameId) {
  14618. var cancelRAF = this.getConfig().cancelAnimationFrame || cancelAnimationFrame;
  14619. cancelRAF(this.frameId);
  14620. }
  14621. // unmount all children
  14622. var root = this.getRoot();
  14623. this.unmountChildren(root);
  14624. if (cleanUp) {
  14625. // destroy Document
  14626. this.document.destroy();
  14627. this.getEventService().destroy();
  14628. }
  14629. // destroy services
  14630. this.getRenderingService().destroy();
  14631. this.getContextService().destroy();
  14632. // clear root after renderservice destroyed
  14633. if (cleanUp && this.context.rBushRoot) {
  14634. // clear rbush
  14635. this.context.rBushRoot.clear();
  14636. this.context.rBushRoot = null;
  14637. this.context.renderingContext.root = null;
  14638. }
  14639. if (!skipTriggerEvent) {
  14640. this.dispatchEvent(new CustomEvent(CanvasEvent.AFTER_DESTROY));
  14641. }
  14642. }
  14643. /**
  14644. * compatible with G 3.0
  14645. * @deprecated
  14646. * @alias resize
  14647. */;
  14648. _proto.changeSize = function changeSize(width, height) {
  14649. this.resize(width, height);
  14650. };
  14651. _proto.resize = function resize(width, height) {
  14652. // update canvas' config
  14653. var canvasConfig = this.context.config;
  14654. canvasConfig.width = width;
  14655. canvasConfig.height = height;
  14656. // resize context
  14657. this.getContextService().resize(width, height);
  14658. // resize camera
  14659. var camera = this.context.camera;
  14660. var projectionMode = camera.getProjectionMode();
  14661. camera.setPosition(width / 2, height / 2, DEFAULT_CAMERA_Z).setFocalPoint(width / 2, height / 2, 0);
  14662. if (projectionMode === CameraProjectionMode.ORTHOGRAPHIC) {
  14663. camera.setOrthographic(width / -2, width / 2, height / 2, height / -2, camera.getNear(), camera.getFar());
  14664. } else {
  14665. camera.setAspect(width / height);
  14666. }
  14667. this.dispatchEvent(new CustomEvent(CanvasEvent.RESIZE, {
  14668. width: width,
  14669. height: height
  14670. }));
  14671. }
  14672. // proxy to document.documentElement
  14673. ;
  14674. _proto.appendChild = function appendChild(child, index) {
  14675. return this.document.documentElement.appendChild(child, index);
  14676. };
  14677. _proto.insertBefore = function insertBefore(newChild, refChild) {
  14678. return this.document.documentElement.insertBefore(newChild, refChild);
  14679. };
  14680. _proto.removeChild = function removeChild(child) {
  14681. return this.document.documentElement.removeChild(child);
  14682. }
  14683. /**
  14684. * Remove all children which can be appended to its original parent later again.
  14685. */;
  14686. _proto.removeChildren = function removeChildren() {
  14687. this.document.documentElement.removeChildren();
  14688. }
  14689. /**
  14690. * Recursively destroy all children which can not be appended to its original parent later again.
  14691. * But the canvas remains running which means display objects can be appended later.
  14692. */;
  14693. _proto.destroyChildren = function destroyChildren() {
  14694. this.document.documentElement.destroyChildren();
  14695. };
  14696. _proto.render = function render() {
  14697. var _this3 = this;
  14698. this.dispatchEvent(beforeRenderEvent);
  14699. var renderingService = this.getRenderingService();
  14700. renderingService.render(this.getConfig(), function () {
  14701. // trigger actual rerender event
  14702. // @see https://github.com/antvis/G/issues/1268
  14703. _this3.dispatchEvent(rerenderEvent);
  14704. });
  14705. this.dispatchEvent(afterRenderEvent);
  14706. };
  14707. _proto.run = function run() {
  14708. var _this4 = this;
  14709. var tick = function tick() {
  14710. _this4.render();
  14711. _this4.frameId = _this4.requestAnimationFrame(tick);
  14712. };
  14713. tick();
  14714. };
  14715. _proto.initRenderer = function initRenderer(renderer, firstContentfullPaint) {
  14716. var _this5 = this;
  14717. if (firstContentfullPaint === void 0) {
  14718. firstContentfullPaint = false;
  14719. }
  14720. if (!renderer) {
  14721. throw new Error('Renderer is required.');
  14722. }
  14723. // reset
  14724. this.inited = false;
  14725. this.readyPromise = undefined;
  14726. // FIXME: should re-create here?
  14727. this.context.rBushRoot = new RBush();
  14728. // reset rendering plugins
  14729. this.context.renderingPlugins = [];
  14730. this.context.renderingPlugins.push(new EventPlugin(), new PrepareRendererPlugin(), new DirtyCheckPlugin(), new CullingPlugin([new FrustumCullingStrategy()]));
  14731. //
  14732. this.loadRendererContainerModule(renderer);
  14733. // init context service
  14734. this.context.contextService = new this.context.ContextService(_extends({}, runtime, this.context));
  14735. // init rendering service
  14736. this.context.renderingService = new RenderingService(runtime, this.context);
  14737. // init event service
  14738. this.context.eventService = new EventService(runtime, this.context);
  14739. this.context.eventService.init();
  14740. if (this.context.contextService.init) {
  14741. this.context.contextService.init();
  14742. this.initRenderingService(renderer, firstContentfullPaint, true);
  14743. } else {
  14744. this.context.contextService.initAsync().then(function () {
  14745. _this5.initRenderingService(renderer, firstContentfullPaint);
  14746. });
  14747. }
  14748. };
  14749. _proto.initRenderingService = function initRenderingService(renderer, firstContentfullPaint, async) {
  14750. var _this6 = this;
  14751. if (firstContentfullPaint === void 0) {
  14752. firstContentfullPaint = false;
  14753. }
  14754. if (async === void 0) {
  14755. async = false;
  14756. }
  14757. this.context.renderingService.init(function () {
  14758. _this6.inited = true;
  14759. if (firstContentfullPaint) {
  14760. if (async) {
  14761. _this6.requestAnimationFrame(function () {
  14762. _this6.dispatchEvent(new CustomEvent(CanvasEvent.READY));
  14763. });
  14764. } else {
  14765. _this6.dispatchEvent(new CustomEvent(CanvasEvent.READY));
  14766. }
  14767. if (_this6.readyPromise) {
  14768. _this6.resolveReadyPromise();
  14769. }
  14770. } else {
  14771. _this6.dispatchEvent(new CustomEvent(CanvasEvent.RENDERER_CHANGED));
  14772. }
  14773. if (!firstContentfullPaint) {
  14774. _this6.getRoot().forEach(function (node) {
  14775. var renderable = node.renderable;
  14776. if (renderable) {
  14777. renderable.renderBoundsDirty = true;
  14778. renderable.boundsDirty = true;
  14779. renderable.dirty = true;
  14780. }
  14781. });
  14782. }
  14783. // keep current scenegraph unchanged, just trigger mounted event
  14784. _this6.mountChildren(_this6.getRoot());
  14785. if (renderer.getConfig().enableAutoRendering) {
  14786. _this6.run();
  14787. }
  14788. });
  14789. };
  14790. _proto.loadRendererContainerModule = function loadRendererContainerModule(renderer) {
  14791. var _this7 = this;
  14792. // load other container modules provided by g-canvas/g-svg/g-webgl
  14793. var plugins = renderer.getPlugins();
  14794. plugins.forEach(function (plugin) {
  14795. plugin.context = _this7.context;
  14796. plugin.init(runtime);
  14797. });
  14798. };
  14799. _proto.setRenderer = function setRenderer(renderer) {
  14800. // update canvas' config
  14801. var canvasConfig = this.getConfig();
  14802. if (canvasConfig.renderer === renderer) {
  14803. return;
  14804. }
  14805. var oldRenderer = canvasConfig.renderer;
  14806. canvasConfig.renderer = renderer;
  14807. // keep all children undestroyed
  14808. this.destroy(false, true);
  14809. // destroy all plugins, reverse will mutate origin array
  14810. [].concat(oldRenderer === null || oldRenderer === void 0 ? void 0 : oldRenderer.getPlugins()).reverse().forEach(function (plugin) {
  14811. plugin.destroy(runtime);
  14812. });
  14813. this.initRenderer(renderer);
  14814. };
  14815. _proto.setCursor = function setCursor(cursor) {
  14816. var canvasConfig = this.getConfig();
  14817. canvasConfig.cursor = cursor;
  14818. this.getContextService().applyCursorStyle(cursor);
  14819. };
  14820. _proto.unmountChildren = function unmountChildren(parent) {
  14821. var _this8 = this;
  14822. // unmountChildren recursively
  14823. parent.childNodes.forEach(function (child) {
  14824. _this8.unmountChildren(child);
  14825. });
  14826. if (this.inited) {
  14827. if (parent.isMutationObserved) {
  14828. parent.dispatchEvent(unmountedEvent);
  14829. } else {
  14830. unmountedEvent.target = parent;
  14831. this.dispatchEvent(unmountedEvent, true);
  14832. }
  14833. // skip document.documentElement
  14834. if (parent !== this.document.documentElement) {
  14835. parent.ownerDocument = null;
  14836. }
  14837. parent.isConnected = false;
  14838. }
  14839. // trigger after unmounted
  14840. if (parent.isCustomElement) {
  14841. if (parent.disconnectedCallback) {
  14842. parent.disconnectedCallback();
  14843. }
  14844. }
  14845. };
  14846. _proto.mountChildren = function mountChildren(parent) {
  14847. var _this9 = this;
  14848. if (this.inited) {
  14849. if (!parent.isConnected) {
  14850. parent.ownerDocument = this.document;
  14851. parent.isConnected = true;
  14852. if (parent.isMutationObserved) {
  14853. parent.dispatchEvent(mountedEvent);
  14854. } else {
  14855. mountedEvent.target = parent;
  14856. this.dispatchEvent(mountedEvent, true);
  14857. }
  14858. }
  14859. } else {
  14860. 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);
  14861. }
  14862. // recursively mount children
  14863. parent.childNodes.forEach(function (child) {
  14864. _this9.mountChildren(child);
  14865. });
  14866. // trigger after mounted
  14867. if (parent.isCustomElement) {
  14868. if (parent.connectedCallback) {
  14869. parent.connectedCallback();
  14870. }
  14871. }
  14872. };
  14873. _proto.client2Viewport = function client2Viewport(client) {
  14874. return this.getEventService().client2Viewport(client);
  14875. };
  14876. _proto.viewport2Client = function viewport2Client(canvas) {
  14877. return this.getEventService().viewport2Client(canvas);
  14878. };
  14879. _proto.viewport2Canvas = function viewport2Canvas(viewport) {
  14880. return this.getEventService().viewport2Canvas(viewport);
  14881. };
  14882. _proto.canvas2Viewport = function canvas2Viewport(canvas) {
  14883. return this.getEventService().canvas2Viewport(canvas);
  14884. }
  14885. /**
  14886. * @deprecated
  14887. * @alias client2Viewport
  14888. */;
  14889. _proto.getPointByClient = function getPointByClient(clientX, clientY) {
  14890. return this.client2Viewport({
  14891. x: clientX,
  14892. y: clientY
  14893. });
  14894. }
  14895. /**
  14896. * @deprecated
  14897. * @alias viewport2Client
  14898. */;
  14899. _proto.getClientByPoint = function getClientByPoint(x, y) {
  14900. return this.viewport2Client({
  14901. x: x,
  14902. y: y
  14903. });
  14904. };
  14905. _createClass(Canvas, [{
  14906. key: "ready",
  14907. get: function get() {
  14908. var _this10 = this;
  14909. if (!this.readyPromise) {
  14910. this.readyPromise = new Promise(function (resolve) {
  14911. _this10.resolveReadyPromise = function () {
  14912. resolve(_this10);
  14913. };
  14914. });
  14915. if (this.inited) {
  14916. this.resolveReadyPromise();
  14917. }
  14918. }
  14919. return this.readyPromise;
  14920. }
  14921. }]);
  14922. return Canvas;
  14923. }(EventTarget);
  14924. export { AABB, AbstractRenderer, AbstractRendererPlugin, BUILT_IN_PROPERTIES, CSS, CSSGradientValue, CSSKeywordValue, CSSRGB, CSSStyleValue, CSSUnitValue, Camera, CameraEvent, CameraProjectionMode, CameraTrackingMode, CameraType, Canvas, CanvasEvent, Circle, CircleUpdater, CustomElement, CustomElementRegistry, CustomEvent, DefaultSceneGraphSelector, DefaultSceneGraphService, DisplayObject, Document, EMPTY_PARSED_PATH, ERROR_MSG_METHOD_NOT_IMPLEMENTED, Element, ElementEvent, Ellipse, EllipseUpdater, EventService, EventTarget, FederatedEvent, FederatedMouseEvent, FederatedPointerEvent, FederatedWheelEvent, Frustum, GradientType, Group, HTML, Image, Line, LineUpdater, Mask, MutationEvent, Node, OffscreenCanvasCreator, Path, PathUpdater, Plane, Point, Polygon, Polyline, PolylineUpdater, PropertySyntax, Rect, RectUpdater, Rectangle, RenderReason, RenderingService, Shape, SortReason, Strategy, Text, TextService, TextUpdater, UnitType, computeLinearGradient, computeRadialGradient, convertToPath, createVec3, decompose, definedProps, deg2rad, deg2turn, findClosestClipPathTarget, fromRotationTranslationScale, getAngle, getEuler, getOrCalculatePathTotalLength, grad2deg, isBrowser, isCSSGradientValue, isCSSRGB, isCanvas, isDisplayObject, isFederatedEvent, isFillOrStrokeAffected, isPattern, mergeColors, parseColor, parseLength, parsePath, parseTransform, parsedTransformToMat4, propertyMetadataCache, rad2deg, resetEntityCounter, runtime, setDOMSize, translatePathToString, turn2deg };