12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052 |
- import RBush from 'rbush/rbush.js';
- export { default as RBush } from 'rbush/rbush.js';
- 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';
- import { color } from 'd3-color';
- import { vec3, mat3, mat4, vec4, quat as quat$1, vec2 } from 'gl-matrix';
- import { Arc, Cubic, Quad, Polyline as Polyline$1, Line as Line$1 } from '@antv/g-math';
- import EventEmitter from 'eventemitter3';
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type
- */
- var PropertySyntax;
- (function (PropertySyntax) {
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#coordinate
- */
- PropertySyntax["COORDINATE"] = "<coordinate>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#color
- */
- PropertySyntax["COLOR"] = "<color>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#paint
- */
- PropertySyntax["PAINT"] = "<paint>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number
- */
- PropertySyntax["NUMBER"] = "<number>";
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/angle
- */
- PropertySyntax["ANGLE"] = "<angle>";
- /**
- * <number> with range 0..1
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#opacity_value
- */
- PropertySyntax["OPACITY_VALUE"] = "<opacity-value>";
- /**
- * <number> with range 0..Infinity
- */
- PropertySyntax["SHADOW_BLUR"] = "<shadow-blur>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#length
- */
- PropertySyntax["LENGTH"] = "<length>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage
- */
- PropertySyntax["PERCENTAGE"] = "<percentage>";
- PropertySyntax["LENGTH_PERCENTAGE"] = "<length> | <percentage>";
- PropertySyntax["LENGTH_PERCENTAGE_12"] = "[<length> | <percentage>]{1,2}";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin#formal_syntax
- */
- PropertySyntax["LENGTH_PERCENTAGE_14"] = "[<length> | <percentage>]{1,4}";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts
- */
- PropertySyntax["LIST_OF_POINTS"] = "<list-of-points>";
- PropertySyntax["PATH"] = "<path>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter#formal_syntax
- */
- PropertySyntax["FILTER"] = "<filter>";
- PropertySyntax["Z_INDEX"] = "<z-index>";
- PropertySyntax["OFFSET_DISTANCE"] = "<offset-distance>";
- PropertySyntax["DEFINED_PATH"] = "<defined-path>";
- PropertySyntax["MARKER"] = "<marker>";
- PropertySyntax["TRANSFORM"] = "<transform>";
- PropertySyntax["TRANSFORM_ORIGIN"] = "<transform-origin>";
- PropertySyntax["TEXT"] = "<text>";
- PropertySyntax["TEXT_TRANSFORM"] = "<text-transform>";
- })(PropertySyntax || (PropertySyntax = {}));
- function _regeneratorRuntime() {
- _regeneratorRuntime = function () {
- return exports;
- };
- var exports = {},
- Op = Object.prototype,
- hasOwn = Op.hasOwnProperty,
- defineProperty = Object.defineProperty || function (obj, key, desc) {
- obj[key] = desc.value;
- },
- $Symbol = "function" == typeof Symbol ? Symbol : {},
- iteratorSymbol = $Symbol.iterator || "@@iterator",
- asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
- toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
- function define(obj, key, value) {
- return Object.defineProperty(obj, key, {
- value: value,
- enumerable: !0,
- configurable: !0,
- writable: !0
- }), obj[key];
- }
- try {
- define({}, "");
- } catch (err) {
- define = function (obj, key, value) {
- return obj[key] = value;
- };
- }
- function wrap(innerFn, outerFn, self, tryLocsList) {
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
- generator = Object.create(protoGenerator.prototype),
- context = new Context(tryLocsList || []);
- return defineProperty(generator, "_invoke", {
- value: makeInvokeMethod(innerFn, self, context)
- }), generator;
- }
- function tryCatch(fn, obj, arg) {
- try {
- return {
- type: "normal",
- arg: fn.call(obj, arg)
- };
- } catch (err) {
- return {
- type: "throw",
- arg: err
- };
- }
- }
- exports.wrap = wrap;
- var ContinueSentinel = {};
- function Generator() {}
- function GeneratorFunction() {}
- function GeneratorFunctionPrototype() {}
- var IteratorPrototype = {};
- define(IteratorPrototype, iteratorSymbol, function () {
- return this;
- });
- var getProto = Object.getPrototypeOf,
- NativeIteratorPrototype = getProto && getProto(getProto(values([])));
- NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
- var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
- function defineIteratorMethods(prototype) {
- ["next", "throw", "return"].forEach(function (method) {
- define(prototype, method, function (arg) {
- return this._invoke(method, arg);
- });
- });
- }
- function AsyncIterator(generator, PromiseImpl) {
- function invoke(method, arg, resolve, reject) {
- var record = tryCatch(generator[method], generator, arg);
- if ("throw" !== record.type) {
- var result = record.arg,
- value = result.value;
- return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
- invoke("next", value, resolve, reject);
- }, function (err) {
- invoke("throw", err, resolve, reject);
- }) : PromiseImpl.resolve(value).then(function (unwrapped) {
- result.value = unwrapped, resolve(result);
- }, function (error) {
- return invoke("throw", error, resolve, reject);
- });
- }
- reject(record.arg);
- }
- var previousPromise;
- defineProperty(this, "_invoke", {
- value: function (method, arg) {
- function callInvokeWithMethodAndArg() {
- return new PromiseImpl(function (resolve, reject) {
- invoke(method, arg, resolve, reject);
- });
- }
- return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
- }
- });
- }
- function makeInvokeMethod(innerFn, self, context) {
- var state = "suspendedStart";
- return function (method, arg) {
- if ("executing" === state) throw new Error("Generator is already running");
- if ("completed" === state) {
- if ("throw" === method) throw arg;
- return doneResult();
- }
- for (context.method = method, context.arg = arg;;) {
- var delegate = context.delegate;
- if (delegate) {
- var delegateResult = maybeInvokeDelegate(delegate, context);
- if (delegateResult) {
- if (delegateResult === ContinueSentinel) continue;
- return delegateResult;
- }
- }
- if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
- if ("suspendedStart" === state) throw state = "completed", context.arg;
- context.dispatchException(context.arg);
- } else "return" === context.method && context.abrupt("return", context.arg);
- state = "executing";
- var record = tryCatch(innerFn, self, context);
- if ("normal" === record.type) {
- if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
- return {
- value: record.arg,
- done: context.done
- };
- }
- "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
- }
- };
- }
- function maybeInvokeDelegate(delegate, context) {
- var methodName = context.method,
- method = delegate.iterator[methodName];
- 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;
- var record = tryCatch(method, delegate.iterator, context.arg);
- if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
- var info = record.arg;
- 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);
- }
- function pushTryEntry(locs) {
- var entry = {
- tryLoc: locs[0]
- };
- 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
- }
- function resetTryEntry(entry) {
- var record = entry.completion || {};
- record.type = "normal", delete record.arg, entry.completion = record;
- }
- function Context(tryLocsList) {
- this.tryEntries = [{
- tryLoc: "root"
- }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
- }
- function values(iterable) {
- if (iterable) {
- var iteratorMethod = iterable[iteratorSymbol];
- if (iteratorMethod) return iteratorMethod.call(iterable);
- if ("function" == typeof iterable.next) return iterable;
- if (!isNaN(iterable.length)) {
- var i = -1,
- next = function next() {
- for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
- return next.value = undefined, next.done = !0, next;
- };
- return next.next = next;
- }
- }
- return {
- next: doneResult
- };
- }
- function doneResult() {
- return {
- value: undefined,
- done: !0
- };
- }
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
- value: GeneratorFunctionPrototype,
- configurable: !0
- }), defineProperty(GeneratorFunctionPrototype, "constructor", {
- value: GeneratorFunction,
- configurable: !0
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
- var ctor = "function" == typeof genFun && genFun.constructor;
- return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
- }, exports.mark = function (genFun) {
- return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
- }, exports.awrap = function (arg) {
- return {
- __await: arg
- };
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
- return this;
- }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
- void 0 === PromiseImpl && (PromiseImpl = Promise);
- var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
- return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
- return result.done ? result.value : iter.next();
- });
- }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
- return this;
- }), define(Gp, "toString", function () {
- return "[object Generator]";
- }), exports.keys = function (val) {
- var object = Object(val),
- keys = [];
- for (var key in object) keys.push(key);
- return keys.reverse(), function next() {
- for (; keys.length;) {
- var key = keys.pop();
- if (key in object) return next.value = key, next.done = !1, next;
- }
- return next.done = !0, next;
- };
- }, exports.values = values, Context.prototype = {
- constructor: Context,
- reset: function (skipTempReset) {
- 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);
- },
- stop: function () {
- this.done = !0;
- var rootRecord = this.tryEntries[0].completion;
- if ("throw" === rootRecord.type) throw rootRecord.arg;
- return this.rval;
- },
- dispatchException: function (exception) {
- if (this.done) throw exception;
- var context = this;
- function handle(loc, caught) {
- return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
- }
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i],
- record = entry.completion;
- if ("root" === entry.tryLoc) return handle("end");
- if (entry.tryLoc <= this.prev) {
- var hasCatch = hasOwn.call(entry, "catchLoc"),
- hasFinally = hasOwn.call(entry, "finallyLoc");
- if (hasCatch && hasFinally) {
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
- } else if (hasCatch) {
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
- } else {
- if (!hasFinally) throw new Error("try statement without catch or finally");
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
- }
- }
- }
- },
- abrupt: function (type, arg) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
- var finallyEntry = entry;
- break;
- }
- }
- finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
- var record = finallyEntry ? finallyEntry.completion : {};
- return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
- },
- complete: function (record, afterLoc) {
- if ("throw" === record.type) throw record.arg;
- 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;
- },
- finish: function (finallyLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
- }
- },
- catch: function (tryLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc === tryLoc) {
- var record = entry.completion;
- if ("throw" === record.type) {
- var thrown = record.arg;
- resetTryEntry(entry);
- }
- return thrown;
- }
- }
- throw new Error("illegal catch attempt");
- },
- delegateYield: function (iterable, resultName, nextLoc) {
- return this.delegate = {
- iterator: values(iterable),
- resultName: resultName,
- nextLoc: nextLoc
- }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
- }
- }, exports;
- }
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
- try {
- var info = gen[key](arg);
- var value = info.value;
- } catch (error) {
- reject(error);
- return;
- }
- if (info.done) {
- resolve(value);
- } else {
- Promise.resolve(value).then(_next, _throw);
- }
- }
- function _asyncToGenerator(fn) {
- return function () {
- var self = this,
- args = arguments;
- return new Promise(function (resolve, reject) {
- var gen = fn.apply(self, args);
- function _next(value) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
- }
- function _throw(err) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
- }
- _next(undefined);
- });
- };
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", {
- writable: false
- });
- return Constructor;
- }
- function _extends() {
- _extends = Object.assign ? Object.assign.bind() : function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf(subClass, superClass);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
- return target;
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
- }
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
- return arr2;
- }
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (it) return (it = it.call(o)).next.bind(it);
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
- return function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- };
- }
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- function _toPrimitive(input, hint) {
- if (typeof input !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (typeof res !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return (hint === "string" ? String : Number)(input);
- }
- function _toPropertyKey(arg) {
- var key = _toPrimitive(arg, "string");
- return typeof key === "symbol" ? key : String(key);
- }
- // These units are iterated through, so be careful when adding or changing the
- // order.
- var UnitType;
- (function (UnitType) {
- UnitType[UnitType["kUnknown"] = 0] = "kUnknown";
- UnitType[UnitType["kNumber"] = 1] = "kNumber";
- UnitType[UnitType["kPercentage"] = 2] = "kPercentage";
- // Length units
- UnitType[UnitType["kEms"] = 3] = "kEms";
- // kExs,
- UnitType[UnitType["kPixels"] = 4] = "kPixels";
- // kCentimeters,
- // kMillimeters,
- // kInches,
- // kPoints,
- // kPicas,
- // kQuarterMillimeters,
- // https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
- //
- // See also IsViewportPercentageLength.
- // kViewportWidth,
- // kViewportHeight,
- // kViewportInlineSize,
- // kViewportBlockSize,
- // kViewportMin,
- // kViewportMax,
- // kSmallViewportWidth,
- // kSmallViewportHeight,
- // kSmallViewportInlineSize,
- // kSmallViewportBlockSize,
- // kSmallViewportMin,
- // kSmallViewportMax,
- // kLargeViewportWidth,
- // kLargeViewportHeight,
- // kLargeViewportInlineSize,
- // kLargeViewportBlockSize,
- // kLargeViewportMin,
- // kLargeViewportMax,
- // kDynamicViewportWidth,
- // kDynamicViewportHeight,
- // kDynamicViewportInlineSize,
- // kDynamicViewportBlockSize,
- // kDynamicViewportMin,
- // kDynamicViewportMax,
- // https://drafts.csswg.org/css-contain-3/#container-lengths
- //
- // See also IsContainerPercentageLength.
- // kContainerWidth,
- // kContainerHeight,
- // kContainerInlineSize,
- // kContainerBlockSize,
- // kContainerMin,
- // kContainerMax,
- UnitType[UnitType["kRems"] = 5] = "kRems";
- // kChs,
- // kUserUnits, // The SVG term for unitless lengths
- // Angle units
- UnitType[UnitType["kDegrees"] = 6] = "kDegrees";
- UnitType[UnitType["kRadians"] = 7] = "kRadians";
- UnitType[UnitType["kGradians"] = 8] = "kGradians";
- UnitType[UnitType["kTurns"] = 9] = "kTurns";
- // Time units
- UnitType[UnitType["kMilliseconds"] = 10] = "kMilliseconds";
- UnitType[UnitType["kSeconds"] = 11] = "kSeconds";
- // kHertz,
- // kKilohertz,
- // Resolution
- // kDotsPerPixel,
- // kDotsPerInch,
- // kDotsPerCentimeter,
- // Other units
- // kFraction,
- UnitType[UnitType["kInteger"] = 12] = "kInteger";
- // This value is used to handle quirky margins in reflow roots (body, td,
- // and th) like WinIE. The basic idea is that a stylesheet can use the value
- // __qem (for quirky em) instead of em. When the quirky value is used, if
- // you're in quirks mode, the margin will collapse away inside a table cell.
- // This quirk is specified in the HTML spec but our impl is different.
- // TODO: Remove this. crbug.com/443952
- // kQuirkyEms,
- })(UnitType || (UnitType = {}));
- var UnitCategory;
- (function (UnitCategory) {
- UnitCategory[UnitCategory["kUNumber"] = 0] = "kUNumber";
- UnitCategory[UnitCategory["kUPercent"] = 1] = "kUPercent";
- UnitCategory[UnitCategory["kULength"] = 2] = "kULength";
- UnitCategory[UnitCategory["kUAngle"] = 3] = "kUAngle";
- UnitCategory[UnitCategory["kUTime"] = 4] = "kUTime";
- // kUFrequency,
- // kUResolution,
- UnitCategory[UnitCategory["kUOther"] = 5] = "kUOther";
- })(UnitCategory || (UnitCategory = {}));
- var ValueRange;
- (function (ValueRange) {
- ValueRange[ValueRange["kAll"] = 0] = "kAll";
- ValueRange[ValueRange["kNonNegative"] = 1] = "kNonNegative";
- ValueRange[ValueRange["kInteger"] = 2] = "kInteger";
- ValueRange[ValueRange["kNonNegativeInteger"] = 3] = "kNonNegativeInteger";
- ValueRange[ValueRange["kPositiveInteger"] = 4] = "kPositiveInteger";
- })(ValueRange || (ValueRange = {}));
- var Nested;
- (function (Nested) {
- Nested[Nested["kYes"] = 0] = "kYes";
- Nested[Nested["kNo"] = 1] = "kNo";
- })(Nested || (Nested = {}));
- var ParenLess;
- (function (ParenLess) {
- ParenLess[ParenLess["kYes"] = 0] = "kYes";
- ParenLess[ParenLess["kNo"] = 1] = "kNo";
- })(ParenLess || (ParenLess = {}));
- // This file specifies the unit strings used in CSSPrimitiveValues.
- var data = [{
- name: 'em',
- unit_type: UnitType.kEms
- },
- // {
- // name: 'ex',
- // unit_type: UnitType.kExs,
- // },
- {
- name: 'px',
- unit_type: UnitType.kPixels
- },
- // {
- // name: "cm",
- // unit_type: UnitType.kCentimeters,
- // },
- // {
- // name: "mm",
- // unit_type: UnitType.kMillimeters,
- // },
- // {
- // name: "q",
- // unit_type: UnitType.kQuarterMillimeters,
- // },
- // {
- // name: "in",
- // unit_type: UnitType.kInches,
- // },
- // {
- // name: "pt",
- // unit_type: UnitType.kPoints,
- // },
- // {
- // name: "pc",
- // unit_type: UnitType.kPicas,
- // },
- {
- name: 'deg',
- unit_type: UnitType.kDegrees
- }, {
- name: 'rad',
- unit_type: UnitType.kRadians
- }, {
- name: 'grad',
- unit_type: UnitType.kGradians
- }, {
- name: 'ms',
- unit_type: UnitType.kMilliseconds
- }, {
- name: 's',
- unit_type: UnitType.kSeconds
- },
- // {
- // name: "hz",
- // unit_type: UnitType.kHertz,
- // },
- // {
- // name: "khz",
- // unit_type: UnitType.kKilohertz,
- // },
- // {
- // name: "dpi",
- // unit_type: "kDotsPerInch",
- // },
- // {
- // name: "dpcm",
- // unit_type: "kDotsPerCentimeter",
- // },
- // {
- // name: "dppx",
- // unit_type: "kDotsPerPixel",
- // },
- // {
- // name: "x",
- // unit_type: "kDotsPerPixel",
- // },
- // {
- // name: "vw",
- // unit_type: "kViewportWidth",
- // },
- // {
- // name: "vh",
- // unit_type: "kViewportHeight",
- // },
- // {
- // name: "vi",
- // unit_type: "kViewportInlineSize",
- // },
- // {
- // name: "vb",
- // unit_type: "kViewportBlockSize",
- // },
- // {
- // name: "vmin",
- // unit_type: UnitType.kViewportMin,
- // },
- // {
- // name: "vmax",
- // unit_type: UnitType.kViewportMax,
- // },
- // {
- // name: "svw",
- // unit_type: "kSmallViewportWidth",
- // },
- // {
- // name: "svh",
- // unit_type: "kSmallViewportHeight",
- // },
- // {
- // name: "svi",
- // unit_type: "kSmallViewportInlineSize",
- // },
- // {
- // name: "svb",
- // unit_type: "kSmallViewportBlockSize",
- // },
- // {
- // name: "svmin",
- // unit_type: "kSmallViewportMin",
- // },
- // {
- // name: "svmax",
- // unit_type: "kSmallViewportMax",
- // },
- // {
- // name: "lvw",
- // unit_type: "kLargeViewportWidth",
- // },
- // {
- // name: "lvh",
- // unit_type: "kLargeViewportHeight",
- // },
- // {
- // name: "lvi",
- // unit_type: "kLargeViewportInlineSize",
- // },
- // {
- // name: "lvb",
- // unit_type: "kLargeViewportBlockSize",
- // },
- // {
- // name: "lvmin",
- // unit_type: UnitType.kLargeViewportMin,
- // },
- // {
- // name: "lvmax",
- // unit_type: UnitType.kLargeViewportMax,
- // },
- // {
- // name: "dvw",
- // unit_type: UnitType.kDynamicViewportWidth,
- // },
- // {
- // name: "dvh",
- // unit_type: UnitType.kDynamicViewportHeight,
- // },
- // {
- // name: "dvi",
- // unit_type: UnitType.kDynamicViewportInlineSize,
- // },
- // {
- // name: "dvb",
- // unit_type: UnitType.kDynamicViewportBlockSize,
- // },
- // {
- // name: "dvmin",
- // unit_type: UnitType.kDynamicViewportMin,
- // },
- // {
- // name: "dvmax",
- // unit_type: UnitType.kDynamicViewportMax,
- // },
- // {
- // name: "cqw",
- // unit_type: UnitType.kContainerWidth,
- // },
- // {
- // name: "cqh",
- // unit_type: UnitType.kContainerHeight,
- // },
- // {
- // name: "cqi",
- // unit_type: UnitType.kContainerInlineSize,
- // },
- // {
- // name: "cqb",
- // unit_type: UnitType.kContainerBlockSize,
- // },
- // {
- // name: "cqmin",
- // unit_type: UnitType.kContainerMin,
- // },
- // {
- // name: "cqmax",
- // unit_type: UnitType.kContainerMax,
- // },
- {
- name: 'rem',
- unit_type: UnitType.kRems
- },
- // {
- // name: 'fr',
- // unit_type: UnitType.kFraction,
- // },
- {
- name: 'turn',
- unit_type: UnitType.kTurns
- }
- // {
- // name: 'ch',
- // unit_type: UnitType.kChs,
- // },
- // {
- // name: '__qem',
- // unit_type: UnitType.kQuirkyEms,
- // },
- ];
- var CSSStyleValueType;
- (function (CSSStyleValueType) {
- CSSStyleValueType[CSSStyleValueType["kUnknownType"] = 0] = "kUnknownType";
- CSSStyleValueType[CSSStyleValueType["kUnparsedType"] = 1] = "kUnparsedType";
- CSSStyleValueType[CSSStyleValueType["kKeywordType"] = 2] = "kKeywordType";
- // Start of CSSNumericValue subclasses
- CSSStyleValueType[CSSStyleValueType["kUnitType"] = 3] = "kUnitType";
- CSSStyleValueType[CSSStyleValueType["kSumType"] = 4] = "kSumType";
- CSSStyleValueType[CSSStyleValueType["kProductType"] = 5] = "kProductType";
- CSSStyleValueType[CSSStyleValueType["kNegateType"] = 6] = "kNegateType";
- CSSStyleValueType[CSSStyleValueType["kInvertType"] = 7] = "kInvertType";
- CSSStyleValueType[CSSStyleValueType["kMinType"] = 8] = "kMinType";
- CSSStyleValueType[CSSStyleValueType["kMaxType"] = 9] = "kMaxType";
- CSSStyleValueType[CSSStyleValueType["kClampType"] = 10] = "kClampType";
- // End of CSSNumericValue subclasses
- CSSStyleValueType[CSSStyleValueType["kTransformType"] = 11] = "kTransformType";
- CSSStyleValueType[CSSStyleValueType["kPositionType"] = 12] = "kPositionType";
- CSSStyleValueType[CSSStyleValueType["kURLImageType"] = 13] = "kURLImageType";
- CSSStyleValueType[CSSStyleValueType["kColorType"] = 14] = "kColorType";
- CSSStyleValueType[CSSStyleValueType["kUnsupportedColorType"] = 15] = "kUnsupportedColorType";
- })(CSSStyleValueType || (CSSStyleValueType = {}));
- // function parseCSSStyleValue(propertyName: string, value: string): CSSStyleValue[] {
- // // const propertyId = cssPropertyID(propertyName);
- // // if (propertyId === CSSPropertyID.kInvalid) {
- // // return [];
- // // }
- // // const customPropertyName = propertyId === CSSPropertyID.kVariable ? propertyName : null;
- // // return fromString(propertyId, customPropertyName, value);
- // return [];
- // }
- var stringToUnitType = function stringToUnitType(name) {
- return data.find(function (item) {
- return item.name === name;
- }).unit_type;
- };
- var unitFromName = function unitFromName(name) {
- if (!name) {
- return UnitType.kUnknown;
- }
- if (name === 'number') {
- return UnitType.kNumber;
- }
- if (name === 'percent' || name === '%') {
- return UnitType.kPercentage;
- }
- return stringToUnitType(name);
- };
- var unitTypeToUnitCategory = function unitTypeToUnitCategory(type) {
- switch (type) {
- case UnitType.kNumber:
- case UnitType.kInteger:
- return UnitCategory.kUNumber;
- case UnitType.kPercentage:
- return UnitCategory.kUPercent;
- case UnitType.kPixels:
- // case UnitType.kCentimeters:
- // case UnitType.kMillimeters:
- // case UnitType.kQuarterMillimeters:
- // case UnitType.kInches:
- // case UnitType.kPoints:
- // case UnitType.kPicas:
- // case UnitType.kUserUnits:
- return UnitCategory.kULength;
- case UnitType.kMilliseconds:
- case UnitType.kSeconds:
- return UnitCategory.kUTime;
- case UnitType.kDegrees:
- case UnitType.kRadians:
- case UnitType.kGradians:
- case UnitType.kTurns:
- return UnitCategory.kUAngle;
- // case UnitType.kHertz:
- // case UnitType.kKilohertz:
- // return UnitCategory.kUFrequency;
- // case UnitType.kDotsPerPixel:
- // case UnitType.kDotsPerInch:
- // case UnitType.kDotsPerCentimeter:
- // return UnitCategory.kUResolution;
- default:
- return UnitCategory.kUOther;
- }
- };
- var canonicalUnitTypeForCategory = function canonicalUnitTypeForCategory(category) {
- // The canonical unit type is chosen according to the way
- // CSSPropertyParser.ValidUnit() chooses the default unit in each category
- // (based on unitflags).
- switch (category) {
- case UnitCategory.kUNumber:
- return UnitType.kNumber;
- case UnitCategory.kULength:
- return UnitType.kPixels;
- case UnitCategory.kUPercent:
- return UnitType.kPercentage;
- // return UnitType.kUnknown; // Cannot convert between numbers and percent.
- case UnitCategory.kUTime:
- return UnitType.kSeconds;
- case UnitCategory.kUAngle:
- return UnitType.kDegrees;
- // case UnitCategory.kUFrequency:
- // return UnitType.kHertz;
- // case UnitCategory.kUResolution:
- // return UnitType.kDotsPerPixel;
- default:
- return UnitType.kUnknown;
- }
- };
- /**
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/css_primitive_value.cc#353
- */
- var conversionToCanonicalUnitsScaleFactor = function conversionToCanonicalUnitsScaleFactor(unit_type) {
- var factor = 1.0;
- // FIXME: the switch can be replaced by an array of scale factors.
- switch (unit_type) {
- // These are "canonical" units in their respective categories.
- case UnitType.kPixels:
- // case UnitType.kUserUnits:
- case UnitType.kDegrees:
- case UnitType.kSeconds:
- // case UnitType.kHertz:
- break;
- case UnitType.kMilliseconds:
- factor = 0.001;
- break;
- // case UnitType.kCentimeters:
- // // factor = kCssPixelsPerCentimeter;
- // break;
- // case UnitType.kDotsPerCentimeter:
- // // factor = 1 / kCssPixelsPerCentimeter;
- // break;
- // case UnitType.kMillimeters:
- // // factor = kCssPixelsPerMillimeter;
- // break;
- // case UnitType.kQuarterMillimeters:
- // // factor = kCssPixelsPerQuarterMillimeter;
- // break;
- // case UnitType.kInches:
- // // factor = kCssPixelsPerInch;
- // break;
- // case UnitType.kDotsPerInch:
- // // factor = 1 / kCssPixelsPerInch;
- // break;
- // case UnitType.kPoints:
- // // factor = kCssPixelsPerPoint;
- // break;
- // case UnitType.kPicas:
- // // factor = kCssPixelsPerPica;
- // break;
- case UnitType.kRadians:
- factor = 180 / Math.PI;
- break;
- case UnitType.kGradians:
- factor = 0.9;
- break;
- case UnitType.kTurns:
- factor = 360;
- break;
- }
- return factor;
- };
- var unitTypeToString = function unitTypeToString(type) {
- switch (type) {
- case UnitType.kNumber:
- case UnitType.kInteger:
- // case UnitType.kUserUnits:
- return '';
- case UnitType.kPercentage:
- return '%';
- case UnitType.kEms:
- // case UnitType.kQuirkyEms:
- return 'em';
- // case UnitType.kExs:
- // return 'ex';
- case UnitType.kRems:
- return 'rem';
- // case UnitType.kChs:
- // return 'ch';
- case UnitType.kPixels:
- return 'px';
- // case UnitType.kCentimeters:
- // return 'cm';
- // case UnitType.kDotsPerPixel:
- // return 'dppx';
- // case UnitType.kDotsPerInch:
- // return 'dpi';
- // case UnitType.kDotsPerCentimeter:
- // return 'dpcm';
- // case UnitType.kMillimeters:
- // return 'mm';
- // case UnitType.kQuarterMillimeters:
- // return 'q';
- // case UnitType.kInches:
- // return 'in';
- // case UnitType.kPoints:
- // return 'pt';
- // case UnitType.kPicas:
- // return 'pc';
- case UnitType.kDegrees:
- return 'deg';
- case UnitType.kRadians:
- return 'rad';
- case UnitType.kGradians:
- return 'grad';
- case UnitType.kMilliseconds:
- return 'ms';
- case UnitType.kSeconds:
- return 's';
- // case UnitType.kHertz:
- // return 'hz';
- // case UnitType.kKilohertz:
- // return 'khz';
- case UnitType.kTurns:
- return 'turn';
- }
- return '';
- };
- /**
- * CSSStyleValue is the base class for all CSS values accessible from Typed OM.
- * Values that are not yet supported as specific types are also returned as base CSSStyleValues.
- *
- * Spec @see https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects
- * Docs @see https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue
- */
- var CSSStyleValue = /*#__PURE__*/function () {
- function CSSStyleValue() {}
- // static parse(propertyName: string, value: string): CSSStyleValue {
- // return parseCSSStyleValue(propertyName, value)[0];
- // }
- // static parseAll(propertyName: string, value: string): CSSStyleValue[] {
- // return parseCSSStyleValue(propertyName, value);
- // }
- CSSStyleValue.isAngle = function isAngle(unit) {
- return unit === UnitType.kDegrees || unit === UnitType.kRadians || unit === UnitType.kGradians || unit === UnitType.kTurns;
- }
- // static isViewportPercentageLength(type: UnitType) {
- // return type >= UnitType.kViewportWidth && type <= UnitType.kDynamicViewportMax;
- // }
- // static isContainerPercentageLength(type: UnitType) {
- // return type >= UnitType.kContainerWidth && type <= UnitType.kContainerMax;
- // }
- ;
- CSSStyleValue.isLength = function isLength(type) {
- // return (type >= UnitType.kEms && type <= UnitType.kUserUnits) || type == UnitType.kQuirkyEms;
- return type >= UnitType.kEms && type < UnitType.kDegrees;
- };
- CSSStyleValue.isRelativeUnit = function isRelativeUnit(type) {
- return type === UnitType.kPercentage || type === UnitType.kEms ||
- // type === UnitType.kExs ||
- type === UnitType.kRems
- // type === UnitType.kChs ||
- // this.isViewportPercentageLength(type) ||
- // this.isContainerPercentageLength(type)
- ;
- };
- CSSStyleValue.isTime = function isTime(unit) {
- return unit === UnitType.kSeconds || unit === UnitType.kMilliseconds;
- }
- // protected abstract toCSSValue(): CSSValue;
- ;
- var _proto = CSSStyleValue.prototype;
- _proto.toString = function toString() {
- return this.buildCSSText(Nested.kNo, ParenLess.kNo, '');
- };
- _proto.isNumericValue = function isNumericValue() {
- return this.getType() >= CSSStyleValueType.kUnitType && this.getType() <= CSSStyleValueType.kClampType;
- };
- return CSSStyleValue;
- }();
- /**
- * CSSColorValue is the base class used for the various CSS color interfaces.
- *
- * @see https://drafts.css-houdini.org/css-typed-om-1/#colorvalue-objects
- */
- var CSSColorValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSColorValue, _CSSStyleValue);
- function CSSColorValue(colorSpace) {
- var _this;
- _this = _CSSStyleValue.call(this) || this;
- _this.colorSpace = void 0;
- _this.colorSpace = colorSpace;
- return _this;
- }
- var _proto = CSSColorValue.prototype;
- _proto.getType = function getType() {
- return CSSStyleValueType.kColorType;
- }
- // buildCSSText(n: Nested, p: ParenLess, result: string): string {
- // let text = '';
- // if (this.colorSpace === 'rgb') {
- // text = `rgba(${this.channels.join(',')},${this.alpha})`;
- // }
- // return (result += text);
- // }
- /**
- * @see https://drafts.css-houdini.org/css-typed-om-1/#dom-csscolorvalue-to
- */;
- _proto.to = function to(colorSpace) {
- return this;
- };
- return CSSColorValue;
- }(CSSStyleValue);
- var GradientType;
- (function (GradientType) {
- GradientType[GradientType["Constant"] = 0] = "Constant";
- GradientType[GradientType["LinearGradient"] = 1] = "LinearGradient";
- GradientType[GradientType["RadialGradient"] = 2] = "RadialGradient";
- })(GradientType || (GradientType = {}));
- var CSSGradientValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSGradientValue, _CSSStyleValue);
- function CSSGradientValue(type, value) {
- var _this;
- _this = _CSSStyleValue.call(this) || this;
- _this.type = void 0;
- _this.value = void 0;
- _this.type = type;
- _this.value = value;
- return _this;
- }
- var _proto = CSSGradientValue.prototype;
- _proto.clone = function clone() {
- return new CSSGradientValue(this.type, this.value);
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- return result;
- };
- _proto.getType = function getType() {
- return CSSStyleValueType.kColorType;
- };
- return CSSGradientValue;
- }(CSSStyleValue);
- /**
- * CSSKeywordValue represents CSS Values that are specified as keywords
- * eg. 'initial'
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSKeywordValue
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_keyword_value.idl
- */
- var CSSKeywordValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSKeywordValue, _CSSStyleValue);
- function CSSKeywordValue(value) {
- var _this;
- _this = _CSSStyleValue.call(this) || this;
- _this.value = void 0;
- _this.value = value;
- return _this;
- }
- var _proto = CSSKeywordValue.prototype;
- _proto.clone = function clone() {
- return new CSSKeywordValue(this.value);
- };
- _proto.getType = function getType() {
- return CSSStyleValueType.kKeywordType;
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- return result + this.value;
- };
- return CSSKeywordValue;
- }(CSSStyleValue);
- function memoize(func, resolver) {
- if (typeof func !== 'function' || resolver != null && typeof resolver !== 'function') {
- throw new TypeError('Expected a function');
- }
- var memoized = function memoized() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- var key = resolver ? resolver.apply(this, args) : args[0];
- var cache = memoized.cache;
- if (cache.has(key)) {
- return cache.get(key);
- }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result) || cache;
- return result;
- };
- memoized.cache = new (memoize.Cache || Map)();
- return memoized;
- }
- memoize.Cache = Map;
- var camelCase = memoize(function (str) {
- if (str === void 0) {
- str = '';
- }
- return str.replace(/-([a-z])/g, function (g) {
- return g[1].toUpperCase();
- });
- });
- var kebabize = function kebabize(str) {
- return str.split('').map(function (letter, idx) {
- return letter.toUpperCase() === letter ? "" + (idx !== 0 ? '-' : '') + letter.toLowerCase() : letter;
- }).join('');
- };
- function DCHECK(bool) {
- if (!bool) {
- throw new Error();
- }
- }
- function isFunction(func) {
- return typeof func === 'function';
- }
- function isSymbol(value) {
- // @see https://github.com/lodash/lodash/blob/master/isSymbol.js
- return typeof value === 'symbol';
- }
- var definedProps = function definedProps(obj) {
- return Object.fromEntries(Object.entries(obj).filter(function (_ref) {
- var v = _ref[1];
- return v !== undefined;
- }));
- };
- var FORMAT_ATTR_MAP = {
- d: {
- alias: 'path'
- },
- strokeDasharray: {
- alias: 'lineDash'
- },
- strokeWidth: {
- alias: 'lineWidth'
- },
- textAnchor: {
- alias: 'textAlign'
- },
- src: {
- alias: 'img'
- }
- };
- var formatAttributeName = memoize(function (name) {
- var attributeName = camelCase(name);
- var map = FORMAT_ATTR_MAP[attributeName];
- attributeName = (map === null || map === void 0 ? void 0 : map.alias) || attributeName;
- return attributeName;
- });
- // type CSSNumericBaseType =
- // | 'length'
- // | 'angle'
- // | 'time'
- // | 'frequency'
- // | 'resolution'
- // | 'flex'
- // | 'percent';
- // https://drafts.css-houdini.org/css-typed-om/#dictdef-cssnumerictype
- // interface CSSNumericType {
- // length: number;
- // angle: number;
- // time: number;
- // frequency: number;
- // resolution: number;
- // flex: number;
- // percent: number;
- // percentHint: CSSNumericBaseType;
- // }
- var formatInfinityOrNaN = function formatInfinityOrNaN(number, suffix) {
- if (suffix === void 0) {
- suffix = '';
- }
- var result = '';
- if (!Number.isFinite(number)) {
- if (number > 0) result = 'infinity';else result = '-infinity';
- } else {
- DCHECK(Number.isNaN(number));
- result = 'NaN';
- }
- return result += suffix;
- };
- var toCanonicalUnit = function toCanonicalUnit(unit) {
- return canonicalUnitTypeForCategory(unitTypeToUnitCategory(unit));
- };
- /**
- * CSSNumericValue is the base class for numeric and length typed CSS Values.
- * @see https://drafts.css-houdini.org/css-typed-om/#numeric-objects
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericValue
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_numeric_value.idl
- */
- /**
- * Represents numeric values that can be expressed as a single number plus a
- * unit (or a naked number or percentage).
- * @see https://drafts.css-houdini.org/css-typed-om/#cssunitvalue
- */
- var CSSUnitValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSUnitValue, _CSSStyleValue);
- function CSSUnitValue(value, unitOrName) {
- var _this;
- if (unitOrName === void 0) {
- unitOrName = UnitType.kNumber;
- }
- _this = _CSSStyleValue.call(this) || this;
- _this.unit = void 0;
- _this.value = void 0;
- var unit;
- if (typeof unitOrName === 'string') {
- unit = unitFromName(unitOrName);
- } else {
- unit = unitOrName;
- }
- _this.unit = unit;
- _this.value = value;
- return _this;
- }
- var _proto = CSSUnitValue.prototype;
- _proto.clone = function clone() {
- return new CSSUnitValue(this.value, this.unit);
- };
- _proto.equals = function equals(other) {
- var other_unit_value = other;
- return this.value === other_unit_value.value && this.unit === other_unit_value.unit;
- };
- _proto.getType = function getType() {
- return CSSStyleValueType.kUnitType;
- };
- _proto.convertTo = function convertTo(target_unit) {
- if (this.unit === target_unit) {
- return new CSSUnitValue(this.value, this.unit);
- }
- // Instead of defining the scale factors for every unit to every other unit,
- // we simply convert to the canonical unit and back since we already have
- // the scale factors for canonical units.
- var canonical_unit = toCanonicalUnit(this.unit);
- if (canonical_unit !== toCanonicalUnit(target_unit) || canonical_unit === UnitType.kUnknown) {
- return null;
- }
- var scale_factor = conversionToCanonicalUnitsScaleFactor(this.unit) / conversionToCanonicalUnitsScaleFactor(target_unit);
- return new CSSUnitValue(this.value * scale_factor, target_unit);
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- var text;
- switch (this.unit) {
- case UnitType.kUnknown:
- // FIXME
- break;
- case UnitType.kInteger:
- text = Number(this.value).toFixed(0);
- break;
- case UnitType.kNumber:
- case UnitType.kPercentage:
- case UnitType.kEms:
- // case UnitType.kQuirkyEms:
- // case UnitType.kExs:
- case UnitType.kRems:
- // case UnitType.kChs:
- case UnitType.kPixels:
- // case UnitType.kCentimeters:
- // case UnitType.kDotsPerPixel:
- // case UnitType.kDotsPerInch:
- // case UnitType.kDotsPerCentimeter:
- // case UnitType.kMillimeters:
- // case UnitType.kQuarterMillimeters:
- // case UnitType.kInches:
- // case UnitType.kPoints:
- // case UnitType.kPicas:
- // case UnitType.kUserUnits:
- case UnitType.kDegrees:
- case UnitType.kRadians:
- case UnitType.kGradians:
- case UnitType.kMilliseconds:
- case UnitType.kSeconds:
- // case UnitType.kHertz:
- // case UnitType.kKilohertz:
- case UnitType.kTurns:
- // 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:
- {
- var kMinInteger = -999999;
- var kMaxInteger = 999999;
- var value = this.value;
- var unit = unitTypeToString(this.unit);
- if (value < kMinInteger || value > kMaxInteger) {
- var _unit = unitTypeToString(this.unit);
- if (!Number.isFinite(value) || Number.isNaN(value)) {
- text = formatInfinityOrNaN(value, _unit);
- } else {
- text = value + (_unit || '');
- }
- } else {
- text = "" + value + unit;
- }
- }
- }
- result += text;
- return result;
- };
- return CSSUnitValue;
- }(CSSStyleValue);
- var Opx = new CSSUnitValue(0, 'px');
- var Lpx = new CSSUnitValue(1, 'px');
- var Odeg = new CSSUnitValue(0, 'deg');
- /**
- * The CSSRGB class represents the CSS rgb()/rgba() functions.
- *
- * @see https://drafts.css-houdini.org/css-typed-om-1/#cssrgb
- */
- var CSSRGB = /*#__PURE__*/function (_CSSColorValue) {
- _inheritsLoose(CSSRGB, _CSSColorValue);
- function CSSRGB(r, g, b, alpha,
- /**
- * 'transparent' & 'none' has the same rgba data
- */
- isNone) {
- var _this;
- if (alpha === void 0) {
- alpha = 1;
- }
- if (isNone === void 0) {
- isNone = false;
- }
- _this = _CSSColorValue.call(this, 'rgb') || this;
- _this.r = void 0;
- _this.g = void 0;
- _this.b = void 0;
- _this.alpha = void 0;
- _this.isNone = void 0;
- _this.r = r;
- _this.g = g;
- _this.b = b;
- _this.alpha = alpha;
- _this.isNone = isNone;
- return _this;
- }
- var _proto = CSSRGB.prototype;
- _proto.clone = function clone() {
- return new CSSRGB(this.r, this.g, this.b, this.alpha);
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- return result + ("rgba(" + this.r + "," + this.g + "," + this.b + "," + this.alpha + ")");
- };
- return CSSRGB;
- }(CSSColorValue);
- /**
- * holds useful CSS-related methods.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS
- *
- * * CSS Typed OM @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/factory_functions
- * * register property @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
- * * CSS Layout API
- */
- var CSS = {
- /**
- * <number>
- * @see https://drafts.csswg.org/css-values-4/#number-value
- */
- number: function number(n) {
- return new CSSUnitValue(n);
- },
- /**
- * <percentage>
- * @see https://drafts.csswg.org/css-values-4/#percentage-value
- */
- percent: function percent(n) {
- return new CSSUnitValue(n, '%');
- },
- /**
- * <length>
- */
- px: function px(n) {
- return new CSSUnitValue(n, 'px');
- },
- /**
- * <length>
- */
- em: function em(n) {
- return new CSSUnitValue(n, 'em');
- },
- rem: function rem(n) {
- return new CSSUnitValue(n, 'rem');
- },
- /**
- * <angle>
- */
- deg: function deg(n) {
- return new CSSUnitValue(n, 'deg');
- },
- /**
- * <angle>
- */
- grad: function grad(n) {
- return new CSSUnitValue(n, 'grad');
- },
- /**
- * <angle>
- */
- rad: function rad(n) {
- return new CSSUnitValue(n, 'rad');
- },
- /**
- * <angle>
- */
- turn: function turn(n) {
- return new CSSUnitValue(n, 'turn');
- },
- /**
- * <time>
- */
- s: function s(n) {
- return new CSSUnitValue(n, 's');
- },
- /**
- * <time>
- */
- ms: function ms(n) {
- return new CSSUnitValue(n, 'ms');
- },
- /**
- * CSS Properties & Values API
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS_Properties_and_Values_API
- * @see https://drafts.css-houdini.org/css-properties-values-api/#registering-custom-properties
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
- */
- registerProperty: function registerProperty(definition) {
- var name = definition.name,
- inherits = definition.inherits,
- interpolable = definition.interpolable,
- initialValue = definition.initialValue,
- syntax = definition.syntax;
- runtime.styleValueRegistry.registerMetadata({
- n: name,
- inh: inherits,
- int: interpolable,
- d: initialValue,
- syntax: syntax
- });
- },
- /**
- * CSS Layout API
- * register layout
- *
- * @see https://github.com/w3c/css-houdini-drafts/blob/main/css-layout-api/EXPLAINER.md
- * @see https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini#css_layout_api
- */
- registerLayout: function registerLayout(name, clazz) {
- runtime.layoutRegistry.registerLayout(name, clazz);
- }
- };
- /**
- * CSSKeywordValue
- */
- var unsetKeywordValue = new CSSKeywordValue('unset');
- var initialKeywordValue = new CSSKeywordValue('initial');
- var inheritKeywordValue = new CSSKeywordValue('inherit');
- var keywordCache = {
- '': unsetKeywordValue,
- unset: unsetKeywordValue,
- initial: initialKeywordValue,
- inherit: inheritKeywordValue
- };
- var getOrCreateKeyword = function getOrCreateKeyword(name) {
- if (!keywordCache[name]) {
- keywordCache[name] = new CSSKeywordValue(name);
- }
- return keywordCache[name];
- };
- /**
- * CSSColor
- */
- var noneColor = new CSSRGB(0, 0, 0, 0, true);
- var transparentColor = new CSSRGB(0, 0, 0, 0);
- var getOrCreateRGBA = memoize(function (r, g, b, a) {
- return new CSSRGB(r, g, b, a);
- }, function (r, g, b, a) {
- return "rgba(" + r + "," + g + "," + b + "," + a + ")";
- });
- // export const getOrCreateUnitValue = memoize(
- // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
- // return new CSSUnitValue(value, unitOrName);
- // },
- // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
- // return `${value}${unitOrName}`;
- // },
- // );
- var getOrCreateUnitValue = function getOrCreateUnitValue(value, unitOrName) {
- if (unitOrName === void 0) {
- unitOrName = UnitType.kNumber;
- }
- return new CSSUnitValue(value, unitOrName);
- };
- var PECENTAGE_50 = new CSSUnitValue(50, '%');
- var canvasMap = {};
- var defaultCanvasIdCounter = 0;
- /**
- * destroy existed canvas with the same id
- */
- function cleanExistedCanvas(container, canvas) {
- if (container) {
- var id = typeof container === 'string' ? container : container.id || defaultCanvasIdCounter++;
- if (canvasMap[id]) {
- canvasMap[id].destroy();
- }
- canvasMap[id] = canvas;
- }
- }
- var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
- function sortedIndex(array, value) {
- var low = 0;
- var high = array.length;
- while (low < high) {
- var mid = low + high >>> 1;
- if (sortByZIndex(array[mid], value) < 0) {
- low = mid + 1;
- } else {
- high = mid;
- }
- }
- return low;
- }
- function sortByZIndex(o1, o2) {
- var zIndex1 = Number(o1.parsedStyle.zIndex);
- var zIndex2 = Number(o2.parsedStyle.zIndex);
- if (zIndex1 === zIndex2) {
- var parent = o1.parentNode;
- if (parent) {
- var children = parent.childNodes || [];
- return children.indexOf(o1) - children.indexOf(o2);
- }
- }
- return zIndex1 - zIndex2;
- }
- function findClosestClipPathTarget(object) {
- var el = object;
- do {
- var _el$parsedStyle;
- var clipPath = (_el$parsedStyle = el.parsedStyle) === null || _el$parsedStyle === void 0 ? void 0 : _el$parsedStyle.clipPath;
- if (clipPath) return el;
- el = el.parentElement;
- } while (el !== null);
- return null;
- }
- var PX_SUFFIX = 'px';
- function setDOMSize($el, width, height) {
- if (isBrowser && $el.style) {
- $el.style.width = width + PX_SUFFIX;
- $el.style.height = height + PX_SUFFIX;
- }
- }
- function getStyle($el, property) {
- if (isBrowser) {
- return document.defaultView.getComputedStyle($el, null).getPropertyValue(property);
- }
- }
- function getWidth($el) {
- var width = getStyle($el, 'width');
- if (width === 'auto') {
- return $el.offsetWidth;
- }
- return parseFloat(width);
- }
- function getHeight($el) {
- var height = getStyle($el, 'height');
- if (height === 'auto') {
- return $el.offsetHeight;
- }
- return parseFloat(height);
- }
- var ERROR_MSG_METHOD_NOT_IMPLEMENTED = 'Method not implemented.';
- var ERROR_MSG_USE_DOCUMENT_ELEMENT = 'Use document.documentElement instead.';
- var ERROR_MSG_APPEND_DESTROYED_ELEMENT = 'Cannot append a destroyed element.';
- // borrow from hammer.js
- var MOUSE_POINTER_ID = 1;
- var TOUCH_TO_POINTER = {
- touchstart: 'pointerdown',
- touchend: 'pointerup',
- touchendoutside: 'pointerupoutside',
- touchmove: 'pointermove',
- touchcancel: 'pointercancel'
- };
- function copyVec3(a, b) {
- a[0] = b[0];
- a[1] = b[1];
- a[2] = b[2];
- return a;
- }
- function subVec3(o, a, b) {
- o[0] = a[0] - b[0];
- o[1] = a[1] - b[1];
- o[2] = a[2] - b[2];
- return o;
- }
- function addVec3(o, a, b) {
- o[0] = a[0] + b[0];
- o[1] = a[1] + b[1];
- o[2] = a[2] + b[2];
- return o;
- }
- function scaleVec3(o, a, b) {
- o[0] = a[0] * b;
- o[1] = a[1] * b;
- o[2] = a[2] * b;
- return o;
- }
- function maxVec3(o, a, b) {
- o[0] = Math.max(a[0], b[0]);
- o[1] = Math.max(a[1], b[1]);
- o[2] = Math.max(a[2], b[2]);
- return o;
- }
- function minVec3(o, a, b) {
- o[0] = Math.min(a[0], b[0]);
- o[1] = Math.min(a[1], b[1]);
- o[2] = Math.min(a[2], b[2]);
- return o;
- }
- function getAngle(angle) {
- if (angle === undefined) {
- return 0;
- } else if (angle > 360 || angle < -360) {
- return angle % 360;
- }
- return angle;
- }
- function createVec3(x, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (Array.isArray(x) && x.length === 3) {
- return vec3.clone(x);
- }
- if (isNumber(x)) {
- return vec3.fromValues(x, y, z);
- }
- return vec3.fromValues(x[0], x[1] || y, x[2] || z);
- }
- function deg2rad(deg) {
- return deg * (Math.PI / 180);
- }
- function rad2deg(rad) {
- return rad * (180 / Math.PI);
- }
- function grad2deg(grads) {
- grads = grads % 400;
- if (grads < 0) {
- grads += 400;
- }
- return grads / 400 * 360;
- }
- function deg2turn(deg) {
- return deg / 360;
- }
- function turn2deg(turn) {
- return 360 * turn;
- }
- function getEulerFromQuat(out, quat) {
- var x = quat[0];
- var y = quat[1];
- var z = quat[2];
- var w = quat[3];
- var x2 = x * x;
- var y2 = y * y;
- var z2 = z * z;
- var w2 = w * w;
- var unit = x2 + y2 + z2 + w2;
- var test = x * w - y * z;
- if (test > 0.499995 * unit) {
- // TODO: Use glmatrix.EPSILON
- // singularity at the north pole
- out[0] = Math.PI / 2;
- out[1] = 2 * Math.atan2(y, x);
- out[2] = 0;
- } else if (test < -0.499995 * unit) {
- //TODO: Use glmatrix.EPSILON
- // singularity at the south pole
- out[0] = -Math.PI / 2;
- out[1] = 2 * Math.atan2(y, x);
- out[2] = 0;
- } else {
- out[0] = Math.asin(2 * (x * z - w * y));
- out[1] = Math.atan2(2 * (x * w + y * z), 1 - 2 * (z2 + w2));
- out[2] = Math.atan2(2 * (x * y + z * w), 1 - 2 * (y2 + z2));
- }
- // TODO: Return them as degrees and not as radians
- return out;
- }
- function getEulerFromMat4(out, m) {
- var x;
- var z;
- var halfPi = Math.PI * 0.5;
- var _mat4$getScaling = mat4.getScaling(vec3.create(), m),
- sx = _mat4$getScaling[0],
- sy = _mat4$getScaling[1],
- sz = _mat4$getScaling[2];
- var y = Math.asin(-m[2] / sx);
- if (y < halfPi) {
- if (y > -halfPi) {
- x = Math.atan2(m[6] / sy, m[10] / sz);
- z = Math.atan2(m[1] / sx, m[0] / sx);
- } else {
- // Not a unique solution
- z = 0;
- x = -Math.atan2(m[4] / sy, m[5] / sy);
- }
- } else {
- // Not a unique solution
- z = 0;
- x = Math.atan2(m[4] / sy, m[5] / sy);
- }
- out[0] = x;
- out[1] = y;
- out[2] = z;
- return out;
- }
- /**
- * @see https://github.com/toji/gl-matrix/issues/329
- * @see https://doc.babylonjs.com/divingDeeper/mesh/transforms/center_origin/rotation_conventions
- */
- function getEuler(out, quat) {
- if (quat.length === 16) {
- return getEulerFromMat4(out, quat);
- } else {
- return getEulerFromQuat(out, quat);
- }
- }
- function fromRotationTranslationScale(rotation, x, y, scaleX, scaleY) {
- var cos = Math.cos(rotation);
- var sin = Math.sin(rotation);
- return mat3.fromValues(scaleX * cos, scaleY * sin, 0, -scaleX * sin, scaleY * cos, 0, x, y, 1);
- }
- function makePerspective(out, left, right, top, bottom, near, far) {
- var x = 2 * near / (right - left);
- var y = 2 * near / (top - bottom);
- var a = (right + left) / (right - left);
- var b = (top + bottom) / (top - bottom);
- var c = -(far + near) / (far - near);
- var d = -2 * far * near / (far - near);
- out[0] = x;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = y;
- out[6] = 0;
- out[7] = 0;
- out[8] = a;
- out[9] = b;
- out[10] = c;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[14] = d;
- out[15] = 0;
- return out;
- }
- function decompose(mat) {
- var row0x = mat[0];
- var row0y = mat[1];
- var row1x = mat[3];
- var row1y = mat[4];
- // decompose 3x3 matrix
- // @see https://www.w3.org/TR/css-transforms-1/#decomposing-a-2d-matrix
- var scalingX = Math.sqrt(row0x * row0x + row0y * row0y);
- var scalingY = Math.sqrt(row1x * row1x + row1y * row1y);
- // If determinant is negative, one axis was flipped.
- var determinant = row0x * row1y - row0y * row1x;
- if (determinant < 0) {
- // Flip axis with minimum unit vector dot product.
- if (row0x < row1y) {
- scalingX = -scalingX;
- } else {
- scalingY = -scalingY;
- }
- }
- // Renormalize matrix to remove scale.
- if (scalingX) {
- row0x *= 1 / scalingX;
- row0y *= 1 / scalingX;
- }
- if (scalingY) {
- row1x *= 1 / scalingY;
- row1y *= 1 / scalingY;
- }
- // Compute rotation and renormalize matrix.
- var rotation = Math.atan2(row0y, row0x);
- var angle = rad2deg(rotation);
- return [mat[6], mat[7], scalingX, scalingY, angle];
- }
- var tmp = mat4.create();
- var perspectiveMatrix = mat4.create();
- var tmpVec4 = vec4.create();
- var row = [vec3.create(), vec3.create(), vec3.create()];
- var pdum3 = vec3.create();
- /*
- Input: matrix ; a 4x4 matrix
- Output: translation ; a 3 component vector
- scale ; a 3 component vector
- skew ; skew factors XY,XZ,YZ represented as a 3 component vector
- perspective ; a 4 component vector
- quaternion ; a 4 component vector
- Returns false if the matrix cannot be decomposed, true if it can
- References:
- https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
- https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
- http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
- */
- function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
- //normalize, if not possible then bail out early
- if (!normalize(tmp, matrix)) return false;
- // perspectiveMatrix is used to solve for perspective, but it also provides
- // an easy way to test for singularity of the upper 3x3 component.
- mat4.copy(perspectiveMatrix, tmp);
- perspectiveMatrix[3] = 0;
- perspectiveMatrix[7] = 0;
- perspectiveMatrix[11] = 0;
- perspectiveMatrix[15] = 1;
- // If the perspectiveMatrix is not invertible, we are also unable to
- // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
- if (Math.abs(mat4.determinant(perspectiveMatrix)) < 1e-8) return false;
- var a03 = tmp[3],
- a13 = tmp[7],
- a23 = tmp[11],
- a30 = tmp[12],
- a31 = tmp[13],
- a32 = tmp[14],
- a33 = tmp[15];
- // First, isolate perspective.
- if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
- tmpVec4[0] = a03;
- tmpVec4[1] = a13;
- tmpVec4[2] = a23;
- tmpVec4[3] = a33;
- // Solve the equation by inverting perspectiveMatrix and multiplying
- // rightHandSide by the inverse.
- // resuing the perspectiveMatrix here since it's no longer needed
- var ret = mat4.invert(perspectiveMatrix, perspectiveMatrix);
- if (!ret) return false;
- mat4.transpose(perspectiveMatrix, perspectiveMatrix);
- //multiply by transposed inverse perspective matrix, into perspective vec4
- vec4.transformMat4(perspective, tmpVec4, perspectiveMatrix);
- } else {
- //no perspective
- perspective[0] = perspective[1] = perspective[2] = 0;
- perspective[3] = 1;
- }
- // Next take care of translation
- translation[0] = a30;
- translation[1] = a31;
- translation[2] = a32;
- // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
- mat3from4(row, tmp);
- // Compute X scale factor and normalize first row.
- scale[0] = vec3.length(row[0]);
- vec3.normalize(row[0], row[0]);
- // Compute XY shear factor and make 2nd row orthogonal to 1st.
- skew[0] = vec3.dot(row[0], row[1]);
- combine(row[1], row[1], row[0], 1.0, -skew[0]);
- // Now, compute Y scale and normalize 2nd row.
- scale[1] = vec3.length(row[1]);
- vec3.normalize(row[1], row[1]);
- skew[0] /= scale[1];
- // Compute XZ and YZ shears, orthogonalize 3rd row
- skew[1] = vec3.dot(row[0], row[2]);
- combine(row[2], row[2], row[0], 1.0, -skew[1]);
- skew[2] = vec3.dot(row[1], row[2]);
- combine(row[2], row[2], row[1], 1.0, -skew[2]);
- // Next, get Z scale and normalize 3rd row.
- scale[2] = vec3.length(row[2]);
- vec3.normalize(row[2], row[2]);
- skew[1] /= scale[2];
- skew[2] /= scale[2];
- // At this point, the matrix (in rows) is orthonormal.
- // Check for a coordinate system flip. If the determinant
- // is -1, then negate the matrix and the scaling factors.
- vec3.cross(pdum3, row[1], row[2]);
- if (vec3.dot(row[0], pdum3) < 0) {
- for (var i = 0; i < 3; i++) {
- scale[i] *= -1;
- row[i][0] *= -1;
- row[i][1] *= -1;
- row[i][2] *= -1;
- }
- }
- // Now, get the rotations out
- quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0));
- quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0));
- quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0));
- quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0));
- if (row[2][1] > row[1][2]) quaternion[0] = -quaternion[0];
- if (row[0][2] > row[2][0]) quaternion[1] = -quaternion[1];
- if (row[1][0] > row[0][1]) quaternion[2] = -quaternion[2];
- return true;
- }
- function normalize(out, mat) {
- var m44 = mat[15];
- // Cannot normalize.
- if (m44 === 0) return false;
- var scale = 1 / m44;
- for (var i = 0; i < 16; i++) out[i] = mat[i] * scale;
- return true;
- }
- //gets upper-left of a 4x4 matrix into a 3x3 of vectors
- function mat3from4(out, mat4x4) {
- out[0][0] = mat4x4[0];
- out[0][1] = mat4x4[1];
- out[0][2] = mat4x4[2];
- out[1][0] = mat4x4[4];
- out[1][1] = mat4x4[5];
- out[1][2] = mat4x4[6];
- out[2][0] = mat4x4[8];
- out[2][1] = mat4x4[9];
- out[2][2] = mat4x4[10];
- }
- function combine(out, a, b, scale1, scale2) {
- out[0] = a[0] * scale1 + b[0] * scale2;
- out[1] = a[1] * scale1 + b[1] * scale2;
- out[2] = a[2] * scale1 + b[2] * scale2;
- }
- var tmpMat4 = mat4.create();
- function parsedTransformToMat4(transform, object) {
- if (transform && transform.length) {
- var defX = 0;
- var defY = 0;
- if (object) {
- defX = object.parsedStyle.defX || 0;
- defY = object.parsedStyle.defY || 0;
- // reset transform
- object.resetLocalTransform();
- object.setLocalPosition(defX, defY);
- } else {
- object = new DisplayObject({});
- }
- transform.forEach(function (parsed) {
- var t = parsed.t,
- d = parsed.d;
- if (t === 'scale') {
- // scale(1) scale(1, 1)
- var newScale = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1, 1];
- object.scaleLocal(newScale[0], newScale[1], 1);
- } else if (t === 'scalex') {
- var _newScale = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1];
- object.scaleLocal(_newScale[0], 1, 1);
- } else if (t === 'scaley') {
- var _newScale2 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1];
- object.scaleLocal(1, _newScale2[0], 1);
- } else if (t === 'scalez') {
- var _newScale3 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1];
- object.scaleLocal(1, 1, _newScale3[0]);
- } else if (t === 'scale3d') {
- var _newScale4 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1, 1, 1];
- object.scaleLocal(_newScale4[0], _newScale4[1], _newScale4[2]);
- } else if (t === 'translate') {
- var newTranslation = d || [Opx, Opx];
- object.translateLocal(newTranslation[0].value, newTranslation[1].value, 0);
- } else if (t === 'translatex') {
- var _newTranslation = d || [Opx];
- object.translateLocal(_newTranslation[0].value, 0, 0);
- } else if (t === 'translatey') {
- var _newTranslation2 = d || [Opx];
- object.translateLocal(0, _newTranslation2[0].value, 0);
- } else if (t === 'translatez') {
- var _newTranslation3 = d || [Opx];
- object.translateLocal(0, 0, _newTranslation3[0].value);
- } else if (t === 'translate3d') {
- var _newTranslation4 = d || [Opx, Opx, Opx];
- object.translateLocal(_newTranslation4[0].value, _newTranslation4[1].value, _newTranslation4[2].value);
- } else if (t === 'rotate') {
- var newAngles = d || [Odeg];
- object.rotateLocal(0, 0, convertAngleUnit(newAngles[0]));
- } else if (t === 'rotatex') {
- var _newAngles = d || [Odeg];
- object.rotateLocal(convertAngleUnit(_newAngles[0]), 0, 0);
- } else if (t === 'rotatey') {
- var _newAngles2 = d || [Odeg];
- object.rotateLocal(0, convertAngleUnit(_newAngles2[0]), 0);
- } else if (t === 'rotatez') {
- var _newAngles3 = d || [Odeg];
- object.rotateLocal(0, 0, convertAngleUnit(_newAngles3[0]));
- } else if (t === 'rotate3d') ; else if (t === 'skew') {
- var newSkew = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [0, 0];
- object.setLocalSkew(deg2rad(newSkew[0]), deg2rad(newSkew[1]));
- } else if (t === 'skewx') {
- var _newSkew = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [0];
- object.setLocalSkew(deg2rad(_newSkew[0]), object.getLocalSkew()[1]);
- } else if (t === 'skewy') {
- var _newSkew2 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [0];
- object.setLocalSkew(object.getLocalSkew()[0], deg2rad(_newSkew2[0]));
- } else if (t === 'matrix') {
- var _d$map = d.map(function (s) {
- return s.value;
- }),
- a = _d$map[0],
- b = _d$map[1],
- c = _d$map[2],
- dd = _d$map[3],
- tx = _d$map[4],
- ty = _d$map[5];
- object.setLocalTransform(mat4.set(tmpMat4, a, b, 0, 0, c, dd, 0, 0, 0, 0, 1, 0, tx + defX, ty + defY, 0, 1));
- } else if (t === 'matrix3d') {
- // @ts-ignore
- mat4.set.apply(mat4, [tmpMat4].concat(d.map(function (s) {
- return s.value;
- })));
- tmpMat4[12] += defX;
- tmpMat4[13] += defY;
- object.setLocalTransform(tmpMat4);
- }
- });
- }
- return object.getLocalTransform();
- }
- /**
- * borrow from gradient-parser, but we delete some browser compatible prefix such as `-webkit-`
- * @see https://github.com/rafaelcaricio/gradient-parser
- */
- function colorStopToString(colorStop) {
- var type = colorStop.type,
- value = colorStop.value;
- if (type === 'hex') {
- return "#" + value;
- } else if (type === 'literal') {
- return value;
- } else if (type === 'rgb') {
- return "rgb(" + value.join(',') + ")";
- } else {
- return "rgba(" + value.join(',') + ")";
- }
- }
- var parseGradient = function () {
- var tokens = {
- linearGradient: /^(linear\-gradient)/i,
- repeatingLinearGradient: /^(repeating\-linear\-gradient)/i,
- radialGradient: /^(radial\-gradient)/i,
- repeatingRadialGradient: /^(repeating\-radial\-gradient)/i,
- /**
- * @see https://projects.verou.me/conic-gradient/
- */
- conicGradient: /^(conic\-gradient)/i,
- sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,
- extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
- positionKeywords: /^(left|center|right|top|bottom)/i,
- pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
- percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
- emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
- angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
- startCall: /^\(/,
- endCall: /^\)/,
- comma: /^,/,
- hexColor: /^\#([0-9a-fA-F]+)/,
- literalColor: /^([a-zA-Z]+)/,
- rgbColor: /^rgb/i,
- rgbaColor: /^rgba/i,
- number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
- };
- var input = '';
- function error(msg) {
- throw new Error(input + ': ' + msg);
- }
- function getAST() {
- var ast = matchListDefinitions();
- if (input.length > 0) {
- error('Invalid input not EOF');
- }
- return ast;
- }
- function matchListDefinitions() {
- return matchListing(matchDefinition);
- }
- function matchDefinition() {
- 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);
- }
- function matchGradient(gradientType, pattern, orientationMatcher) {
- return matchCall(pattern, function (captures) {
- var orientation = orientationMatcher();
- if (orientation) {
- if (!scan(tokens.comma)) {
- error('Missing comma before color stops');
- }
- }
- return {
- type: gradientType,
- orientation: orientation,
- colorStops: matchListing(matchColorStop)
- };
- });
- }
- function matchCall(pattern, callback) {
- var captures = scan(pattern);
- if (captures) {
- if (!scan(tokens.startCall)) {
- error('Missing (');
- }
- var result = callback(captures);
- if (!scan(tokens.endCall)) {
- error('Missing )');
- }
- return result;
- }
- }
- function matchLinearOrientation() {
- return matchSideOrCorner() || matchAngle();
- }
- function matchSideOrCorner() {
- return match('directional', tokens.sideOrCorner, 1);
- }
- function matchAngle() {
- return match('angular', tokens.angleValue, 1);
- }
- function matchListRadialOrientations() {
- var radialOrientations,
- radialOrientation = matchRadialOrientation(),
- lookaheadCache;
- if (radialOrientation) {
- radialOrientations = [];
- radialOrientations.push(radialOrientation);
- lookaheadCache = input;
- if (scan(tokens.comma)) {
- radialOrientation = matchRadialOrientation();
- if (radialOrientation) {
- radialOrientations.push(radialOrientation);
- } else {
- input = lookaheadCache;
- }
- }
- }
- return radialOrientations;
- }
- function matchRadialOrientation() {
- var radialType = matchCircle() || matchEllipse();
- if (radialType) {
- // @ts-ignore
- radialType.at = matchAtPosition();
- } else {
- var extent = matchExtentKeyword();
- if (extent) {
- radialType = extent;
- var positionAt = matchAtPosition();
- if (positionAt) {
- // @ts-ignore
- radialType.at = positionAt;
- }
- } else {
- var defaultPosition = matchPositioning();
- if (defaultPosition) {
- radialType = {
- type: 'default-radial',
- // @ts-ignore
- at: defaultPosition
- };
- }
- }
- }
- return radialType;
- }
- function matchCircle() {
- var circle = match('shape', /^(circle)/i, 0);
- if (circle) {
- // @ts-ignore
- circle.style = matchLength() || matchExtentKeyword();
- }
- return circle;
- }
- function matchEllipse() {
- var ellipse = match('shape', /^(ellipse)/i, 0);
- if (ellipse) {
- // @ts-ignore
- ellipse.style = matchDistance() || matchExtentKeyword();
- }
- return ellipse;
- }
- function matchExtentKeyword() {
- return match('extent-keyword', tokens.extentKeywords, 1);
- }
- function matchAtPosition() {
- if (match('position', /^at/, 0)) {
- var positioning = matchPositioning();
- if (!positioning) {
- error('Missing positioning value');
- }
- return positioning;
- }
- }
- function matchPositioning() {
- var location = matchCoordinates();
- if (location.x || location.y) {
- return {
- type: 'position',
- value: location
- };
- }
- }
- function matchCoordinates() {
- return {
- x: matchDistance(),
- y: matchDistance()
- };
- }
- function matchListing(matcher) {
- var captures = matcher();
- var result = [];
- if (captures) {
- result.push(captures);
- while (scan(tokens.comma)) {
- captures = matcher();
- if (captures) {
- result.push(captures);
- } else {
- error('One extra comma');
- }
- }
- }
- return result;
- }
- function matchColorStop() {
- var color = matchColor();
- if (!color) {
- error('Expected color definition');
- }
- color.length = matchDistance();
- return color;
- }
- function matchColor() {
- return matchHexColor() || matchRGBAColor() || matchRGBColor() || matchLiteralColor();
- }
- function matchLiteralColor() {
- return match('literal', tokens.literalColor, 0);
- }
- function matchHexColor() {
- return match('hex', tokens.hexColor, 1);
- }
- function matchRGBColor() {
- return matchCall(tokens.rgbColor, function () {
- return {
- type: 'rgb',
- value: matchListing(matchNumber)
- };
- });
- }
- function matchRGBAColor() {
- return matchCall(tokens.rgbaColor, function () {
- return {
- type: 'rgba',
- value: matchListing(matchNumber)
- };
- });
- }
- function matchNumber() {
- return scan(tokens.number)[1];
- }
- function matchDistance() {
- return match('%', tokens.percentageValue, 1) || matchPositionKeyword() || matchLength();
- }
- function matchPositionKeyword() {
- return match('position-keyword', tokens.positionKeywords, 1);
- }
- function matchLength() {
- return match('px', tokens.pixelValue, 1) || match('em', tokens.emValue, 1);
- }
- function match(type, pattern, captureIndex) {
- var captures = scan(pattern);
- if (captures) {
- return {
- type: type,
- value: captures[captureIndex]
- };
- }
- }
- function scan(regexp) {
- var blankCaptures = /^[\n\r\t\s]+/.exec(input);
- if (blankCaptures) {
- consume(blankCaptures[0].length);
- }
- var captures = regexp.exec(input);
- if (captures) {
- consume(captures[0].length);
- }
- return captures;
- }
- function consume(size) {
- input = input.substring(size);
- }
- return function (code) {
- input = code;
- return getAST();
- };
- }();
- function computeLinearGradient(width, height, angle) {
- var rad = deg2rad(angle.value);
- var rx = 0;
- var ry = 0;
- var rcx = rx + width / 2;
- var rcy = ry + height / 2;
- // get the length of gradient line
- // @see https://observablehq.com/@danburzo/css-gradient-line
- var length = Math.abs(width * Math.cos(rad)) + Math.abs(height * Math.sin(rad));
- var x1 = rcx - Math.cos(rad) * length / 2;
- var y1 = rcy - Math.sin(rad) * length / 2;
- var x2 = rcx + Math.cos(rad) * length / 2;
- var y2 = rcy + Math.sin(rad) * length / 2;
- return {
- x1: x1,
- y1: y1,
- x2: x2,
- y2: y2
- };
- }
- function computeRadialGradient(width, height, cx, cy, size) {
- // 'px'
- var x = cx.value;
- var y = cy.value;
- // TODO: 'em'
- // '%'
- if (cx.unit === UnitType.kPercentage) {
- x = cx.value / 100 * width;
- }
- if (cy.unit === UnitType.kPercentage) {
- y = cy.value / 100 * height;
- }
- // default to farthest-side
- var r = Math.max(distanceSquareRoot([0, 0], [x, y]), distanceSquareRoot([0, height], [x, y]), distanceSquareRoot([width, height], [x, y]), distanceSquareRoot([width, 0], [x, y]));
- if (size) {
- if (size instanceof CSSUnitValue) {
- r = size.value;
- } else if (size instanceof CSSKeywordValue) {
- // @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Images/Using_CSS_gradients#example_closest-side_for_circles
- if (size.value === 'closest-side') {
- r = Math.min(x, width - x, y, height - y);
- } else if (size.value === 'farthest-side') {
- r = Math.max(x, width - x, y, height - y);
- } else if (size.value === 'closest-corner') {
- r = Math.min(distanceSquareRoot([0, 0], [x, y]), distanceSquareRoot([0, height], [x, y]), distanceSquareRoot([width, height], [x, y]), distanceSquareRoot([width, 0], [x, y]));
- }
- }
- }
- return {
- x: x,
- y: y,
- r: r
- };
- }
- var Shape;
- (function (Shape) {
- Shape["GROUP"] = "g";
- Shape["CIRCLE"] = "circle";
- Shape["ELLIPSE"] = "ellipse";
- Shape["IMAGE"] = "image";
- Shape["RECT"] = "rect";
- Shape["LINE"] = "line";
- Shape["POLYLINE"] = "polyline";
- Shape["POLYGON"] = "polygon";
- Shape["TEXT"] = "text";
- Shape["PATH"] = "path";
- Shape["HTML"] = "html";
- Shape["MESH"] = "mesh";
- })(Shape || (Shape = {}));
- function getOrCalculatePathTotalLength(path) {
- if (path.parsedStyle.path.totalLength === 0) {
- path.parsedStyle.path.totalLength = getTotalLength(path.parsedStyle.path.absolutePath);
- }
- return path.parsedStyle.path.totalLength;
- }
- function hasArcOrBezier(path) {
- var hasArc = false;
- var count = path.length;
- for (var i = 0; i < count; i++) {
- var params = path[i];
- var cmd = params[0];
- if (cmd === 'C' || cmd === 'A' || cmd === 'Q') {
- hasArc = true;
- break;
- }
- }
- return hasArc;
- }
- function extractPolygons(pathArray) {
- var polygons = [];
- var polylines = [];
- var points = []; // 防止第一个命令不是 'M'
- for (var i = 0; i < pathArray.length; i++) {
- var params = pathArray[i];
- var cmd = params[0];
- if (cmd === 'M') {
- // 遇到 'M' 判定是否是新数组,新数组中没有点
- if (points.length) {
- // 如果存在点,则说明没有遇到 'Z',开始了一个新的多边形
- polylines.push(points);
- points = []; // 创建新的点
- }
- points.push([params[1], params[2]]);
- } else if (cmd === 'Z') {
- if (points.length) {
- // 存在点
- polygons.push(points);
- points = []; // 开始新的点集合
- }
- // 如果不存在点,同时 'Z',则说明是错误,不处理
- } else {
- points.push([params[1], params[2]]);
- }
- }
- // 说明 points 未放入 polygons 或者 polyline
- // 仅当只有一个 M,没有 Z 时会发生这种情况
- if (points.length > 0) {
- polylines.push(points);
- }
- return {
- polygons: polygons,
- polylines: polylines
- };
- }
- function isSamePoint(point1, point2) {
- return point1[0] === point2[0] && point1[1] === point2[1];
- }
- function getPathBBox(segments, lineWidth) {
- var xArr = [];
- var yArr = [];
- var segmentsWithAngle = [];
- for (var i = 0; i < segments.length; i++) {
- var segment = segments[i];
- var currentPoint = segment.currentPoint,
- params = segment.params,
- prePoint = segment.prePoint;
- var box = void 0;
- switch (segment.command) {
- case 'Q':
- box = Quad.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4]);
- break;
- case 'C':
- box = Cubic.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4], params[5], params[6]);
- break;
- case 'A':
- var arcParams = segment.arcParams;
- box = Arc.box(arcParams.cx, arcParams.cy, arcParams.rx, arcParams.ry, arcParams.xRotation, arcParams.startAngle, arcParams.endAngle);
- break;
- default:
- xArr.push(currentPoint[0]);
- yArr.push(currentPoint[1]);
- break;
- }
- if (box) {
- segment.box = box;
- xArr.push(box.x, box.x + box.width);
- yArr.push(box.y, box.y + box.height);
- }
- if (lineWidth && (segment.command === 'L' || segment.command === 'M') && segment.prePoint && segment.nextPoint) {
- segmentsWithAngle.push(segment);
- }
- }
- // bbox calculation should ignore NaN for path attribute
- // ref: https://github.com/antvis/g/issues/210
- // ref: https://github.com/antvis/G2/issues/3109
- xArr = xArr.filter(function (item) {
- return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
- });
- yArr = yArr.filter(function (item) {
- return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
- });
- var minX = min(xArr);
- var minY = min(yArr);
- var maxX = max(xArr);
- var maxY = max(yArr);
- if (segmentsWithAngle.length === 0) {
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- }
- for (var _i = 0; _i < segmentsWithAngle.length; _i++) {
- var _segment = segmentsWithAngle[_i];
- var _currentPoint = _segment.currentPoint;
- var extra = void 0;
- if (_currentPoint[0] === minX) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- minX = minX - extra.xExtra;
- } else if (_currentPoint[0] === maxX) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- maxX = maxX + extra.xExtra;
- }
- if (_currentPoint[1] === minY) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- minY = minY - extra.yExtra;
- } else if (_currentPoint[1] === maxY) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- maxY = maxY + extra.yExtra;
- }
- }
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- }
- function getExtraFromSegmentWithAngle(segment, lineWidth) {
- var prePoint = segment.prePoint,
- currentPoint = segment.currentPoint,
- nextPoint = segment.nextPoint;
- var currentAndPre = Math.pow(currentPoint[0] - prePoint[0], 2) + Math.pow(currentPoint[1] - prePoint[1], 2);
- var currentAndNext = Math.pow(currentPoint[0] - nextPoint[0], 2) + Math.pow(currentPoint[1] - nextPoint[1], 2);
- var preAndNext = Math.pow(prePoint[0] - nextPoint[0], 2) + Math.pow(prePoint[1] - nextPoint[1], 2);
- // 以 currentPoint 为顶点的夹角
- var currentAngle = Math.acos((currentAndPre + currentAndNext - preAndNext) / (2 * Math.sqrt(currentAndPre) * Math.sqrt(currentAndNext)));
- // 夹角为空、 0 或 PI 时,不需要计算夹角处的额外宽度
- // 注意: 由于计算精度问题,夹角为 0 的情况计算出来的角度可能是一个很小的值,还需要判断其与 0 是否近似相等
- if (!currentAngle || Math.sin(currentAngle) === 0 || isNumberEqual(currentAngle, 0)) {
- return {
- xExtra: 0,
- yExtra: 0
- };
- }
- var xAngle = Math.abs(Math.atan2(nextPoint[1] - currentPoint[1], nextPoint[0] - currentPoint[0]));
- var yAngle = Math.abs(Math.atan2(nextPoint[0] - currentPoint[0], nextPoint[1] - currentPoint[1]));
- // 将夹角转为锐角
- xAngle = xAngle > Math.PI / 2 ? Math.PI - xAngle : xAngle;
- yAngle = yAngle > Math.PI / 2 ? Math.PI - yAngle : yAngle;
- // 这里不考虑在水平和垂直方向的投影,直接使用最大差值
- // 由于上层统一加减了二分之一线宽,这里需要进行弥补
- var extra = {
- // 水平方向投影
- xExtra: Math.cos(currentAngle / 2 - xAngle) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0,
- // 垂直方向投影
- yExtra: Math.cos(yAngle - currentAngle / 2) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0
- };
- return extra;
- }
- // 点对称
- function toSymmetry(point, center) {
- return [center[0] + (center[0] - point[0]), center[1] + (center[1] - point[1])];
- }
- var angleBetween = function angleBetween(v0, v1) {
- var p = v0.x * v1.x + v0.y * v1.y;
- var n = Math.sqrt((Math.pow(v0.x, 2) + Math.pow(v0.y, 2)) * (Math.pow(v1.x, 2) + Math.pow(v1.y, 2)));
- var sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1 : 1;
- var angle = sign * Math.acos(p / n);
- return angle;
- };
- /**
- * @see https://github.com/rveciana/svg-path-properties/blob/b6bd9a322966f6ef7a311872d80c56e3718de861/src/arc.ts#L121
- */
- var pointOnEllipticalArc = function pointOnEllipticalArc(p0, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p1, t) {
- // In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
- rx = Math.abs(rx);
- ry = Math.abs(ry);
- xAxisRotation = mod(xAxisRotation, 360);
- var xAxisRotationRadians = deg2rad(xAxisRotation);
- // If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
- if (p0.x === p1.x && p0.y === p1.y) {
- return {
- x: p0.x,
- y: p0.y,
- ellipticalArcAngle: 0
- }; // Check if angle is correct
- }
- // If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
- if (rx === 0 || ry === 0) {
- //return this.pointOnLine(p0, p1, t);
- return {
- x: 0,
- y: 0,
- ellipticalArcAngle: 0
- }; // Check if angle is correct
- }
- // Following "Conversion from endpoint to center parameterization"
- // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
- // Step #1: Compute transformedPoint
- var dx = (p0.x - p1.x) / 2;
- var dy = (p0.y - p1.y) / 2;
- var transformedPoint = {
- x: Math.cos(xAxisRotationRadians) * dx + Math.sin(xAxisRotationRadians) * dy,
- y: -Math.sin(xAxisRotationRadians) * dx + Math.cos(xAxisRotationRadians) * dy
- };
- // Ensure radii are large enough
- var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
- if (radiiCheck > 1) {
- rx = Math.sqrt(radiiCheck) * rx;
- ry = Math.sqrt(radiiCheck) * ry;
- }
- // Step #2: Compute transformedCenter
- 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);
- var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cRadicand = cSquareNumerator / cSquareRootDenom;
- // Make sure this never drops below zero because of precision
- cRadicand = cRadicand < 0 ? 0 : cRadicand;
- var cCoef = (largeArcFlag !== sweepFlag ? 1 : -1) * Math.sqrt(cRadicand);
- var transformedCenter = {
- x: cCoef * (rx * transformedPoint.y / ry),
- y: cCoef * (-(ry * transformedPoint.x) / rx)
- };
- // Step #3: Compute center
- var center = {
- x: Math.cos(xAxisRotationRadians) * transformedCenter.x - Math.sin(xAxisRotationRadians) * transformedCenter.y + (p0.x + p1.x) / 2,
- y: Math.sin(xAxisRotationRadians) * transformedCenter.x + Math.cos(xAxisRotationRadians) * transformedCenter.y + (p0.y + p1.y) / 2
- };
- // Step #4: Compute start/sweep angles
- // Start angle of the elliptical arc prior to the stretch and rotate operations.
- // Difference between the start and end angles
- var startVector = {
- x: (transformedPoint.x - transformedCenter.x) / rx,
- y: (transformedPoint.y - transformedCenter.y) / ry
- };
- var startAngle = angleBetween({
- x: 1,
- y: 0
- }, startVector);
- var endVector = {
- x: (-transformedPoint.x - transformedCenter.x) / rx,
- y: (-transformedPoint.y - transformedCenter.y) / ry
- };
- var sweepAngle = angleBetween(startVector, endVector);
- if (!sweepFlag && sweepAngle > 0) {
- sweepAngle -= 2 * Math.PI;
- } else if (sweepFlag && sweepAngle < 0) {
- sweepAngle += 2 * Math.PI;
- }
- // We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
- sweepAngle %= 2 * Math.PI;
- // From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
- var angle = startAngle + sweepAngle * t;
- var ellipseComponentX = rx * Math.cos(angle);
- var ellipseComponentY = ry * Math.sin(angle);
- var point = {
- x: Math.cos(xAxisRotationRadians) * ellipseComponentX - Math.sin(xAxisRotationRadians) * ellipseComponentY + center.x,
- y: Math.sin(xAxisRotationRadians) * ellipseComponentX + Math.cos(xAxisRotationRadians) * ellipseComponentY + center.y,
- ellipticalArcStartAngle: startAngle,
- ellipticalArcEndAngle: startAngle + sweepAngle,
- ellipticalArcAngle: angle,
- ellipticalArcCenter: center,
- resultantRx: rx,
- resultantRy: ry
- };
- return point;
- };
- function path2Segments(path) {
- var segments = [];
- var currentPoint = null; // 当前图形
- var nextParams = null; // 下一节点的 path 参数
- var startMovePoint = null; // 开始 M 的点,可能会有多个
- var lastStartMovePointIndex = 0; // 最近一个开始点 M 的索引
- var count = path.length;
- for (var i = 0; i < count; i++) {
- var params = path[i];
- nextParams = path[i + 1];
- var command = params[0];
- // 数学定义上的参数,便于后面的计算
- var segment = {
- command: command,
- prePoint: currentPoint,
- params: params,
- startTangent: null,
- endTangent: null,
- currentPoint: null,
- nextPoint: null,
- arcParams: null,
- box: null,
- cubicParams: null
- };
- switch (command) {
- case 'M':
- startMovePoint = [params[1], params[2]];
- lastStartMovePointIndex = i;
- break;
- case 'A':
- var arcParams = getArcParams(currentPoint, params);
- segment.arcParams = arcParams;
- break;
- }
- if (command === 'Z') {
- // 有了 Z 后,当前节点从开始 M 的点开始
- currentPoint = startMovePoint;
- // 如果当前点的命令为 Z,相当于当前点为最近一个 M 点,则下一个点直接指向最近一个 M 点的下一个点
- nextParams = path[lastStartMovePointIndex + 1];
- } else {
- var len = params.length;
- currentPoint = [params[len - 2], params[len - 1]];
- }
- if (nextParams && nextParams[0] === 'Z') {
- // 如果下一个点的命令为 Z,则下一个点直接指向最近一个 M 点
- nextParams = path[lastStartMovePointIndex];
- if (segments[lastStartMovePointIndex]) {
- // 如果下一个点的命令为 Z,则最近一个 M 点的前一个点为当前点
- segments[lastStartMovePointIndex].prePoint = currentPoint;
- }
- }
- segment.currentPoint = currentPoint;
- // 如果当前点与最近一个 M 点相同,则最近一个 M 点的前一个点为当前点的前一个点
- if (segments[lastStartMovePointIndex] && isSamePoint(currentPoint, segments[lastStartMovePointIndex].currentPoint)) {
- segments[lastStartMovePointIndex].prePoint = segment.prePoint;
- }
- var nextPoint = nextParams ? [nextParams[nextParams.length - 2], nextParams[nextParams.length - 1]] : null;
- segment.nextPoint = nextPoint;
- // Add startTangent and endTangent
- var prePoint = segment.prePoint;
- if (['L', 'H', 'V'].includes(command)) {
- segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
- segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
- } else if (command === 'Q') {
- // 二次贝塞尔曲线只有一个控制点
- var cp = [params[1], params[2]];
- // 二次贝塞尔曲线的终点为 currentPoint
- segment.startTangent = [prePoint[0] - cp[0], prePoint[1] - cp[1]];
- segment.endTangent = [currentPoint[0] - cp[0], currentPoint[1] - cp[1]];
- } else if (command === 'T') {
- var preSegment = segments[i - 1];
- var _cp = toSymmetry(preSegment.currentPoint, prePoint);
- if (preSegment.command === 'Q') {
- segment.command = 'Q';
- segment.startTangent = [prePoint[0] - _cp[0], prePoint[1] - _cp[1]];
- segment.endTangent = [currentPoint[0] - _cp[0], currentPoint[1] - _cp[1]];
- } else {
- // @ts-ignore
- segment.command = 'TL';
- segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
- segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
- }
- } else if (command === 'C') {
- // 三次贝塞尔曲线有两个控制点
- var cp1 = [params[1], params[2]];
- var cp2 = [params[3], params[4]];
- segment.startTangent = [prePoint[0] - cp1[0], prePoint[1] - cp1[1]];
- segment.endTangent = [currentPoint[0] - cp2[0], currentPoint[1] - cp2[1]];
- // horizontal line, eg. ['C', 100, 100, 100, 100, 200, 200]
- if (segment.startTangent[0] === 0 && segment.startTangent[1] === 0) {
- segment.startTangent = [cp1[0] - cp2[0], cp1[1] - cp2[1]];
- }
- if (segment.endTangent[0] === 0 && segment.endTangent[1] === 0) {
- segment.endTangent = [cp2[0] - cp1[0], cp2[1] - cp1[1]];
- }
- } else if (command === 'S') {
- var _preSegment = segments[i - 1];
- var _cp2 = toSymmetry(_preSegment.currentPoint, prePoint);
- var _cp3 = [params[1], params[2]];
- if (_preSegment.command === 'C') {
- segment.command = 'C'; // 将 S 命令变换为 C 命令
- segment.startTangent = [prePoint[0] - _cp2[0], prePoint[1] - _cp2[1]];
- segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
- } else {
- // @ts-ignore
- segment.command = 'SQ'; // 将 S 命令变换为 SQ 命令
- segment.startTangent = [prePoint[0] - _cp3[0], prePoint[1] - _cp3[1]];
- segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
- }
- } else if (command === 'A') {
- var _getTangentAtRatio = getTangentAtRatio(segment, 0),
- dx1 = _getTangentAtRatio.x,
- dy1 = _getTangentAtRatio.y;
- var _getTangentAtRatio2 = getTangentAtRatio(segment, 1, false),
- dx2 = _getTangentAtRatio2.x,
- dy2 = _getTangentAtRatio2.y;
- segment.startTangent = [dx1, dy1];
- segment.endTangent = [dx2, dy2];
- }
- segments.push(segment);
- }
- return segments;
- }
- /**
- * Use length instead of ratio
- */
- function getTangentAtRatio(segment, ratio, sign) {
- if (sign === void 0) {
- sign = true;
- }
- var _segment$arcParams = segment.arcParams,
- _segment$arcParams$rx = _segment$arcParams.rx,
- rx = _segment$arcParams$rx === void 0 ? 0 : _segment$arcParams$rx,
- _segment$arcParams$ry = _segment$arcParams.ry,
- ry = _segment$arcParams$ry === void 0 ? 0 : _segment$arcParams$ry,
- xRotation = _segment$arcParams.xRotation,
- arcFlag = _segment$arcParams.arcFlag,
- sweepFlag = _segment$arcParams.sweepFlag;
- var p1 = pointOnEllipticalArc({
- x: segment.prePoint[0],
- y: segment.prePoint[1]
- }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
- x: segment.currentPoint[0],
- y: segment.currentPoint[1]
- }, ratio);
- var p2 = pointOnEllipticalArc({
- x: segment.prePoint[0],
- y: segment.prePoint[1]
- }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
- x: segment.currentPoint[0],
- y: segment.currentPoint[1]
- }, sign ? ratio + 0.005 : ratio - 0.005);
- var xDist = p2.x - p1.x;
- var yDist = p2.y - p1.y;
- var dist = Math.sqrt(xDist * xDist + yDist * yDist);
- return {
- x: -xDist / dist,
- y: -yDist / dist
- };
- }
- // 向量长度
- function vMag(v) {
- return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
- }
- // u.v/|u||v|,计算夹角的余弦值
- function vRatio(u, v) {
- // 当存在一个向量的长度为 0 时,夹角也为 0,即夹角的余弦值为 1
- return vMag(u) * vMag(v) ? (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)) : 1;
- }
- // 向量角度
- function vAngle(u, v) {
- return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
- }
- function getArcParams(startPoint, params) {
- var rx = params[1];
- var ry = params[2];
- var xRotation = mod(deg2rad(params[3]), Math.PI * 2);
- var arcFlag = params[4];
- var sweepFlag = params[5];
- // 弧形起点坐标
- var x1 = startPoint[0];
- var y1 = startPoint[1];
- // 弧形终点坐标
- var x2 = params[6];
- var y2 = params[7];
- var xp = Math.cos(xRotation) * (x1 - x2) / 2.0 + Math.sin(xRotation) * (y1 - y2) / 2.0;
- var yp = -1 * Math.sin(xRotation) * (x1 - x2) / 2.0 + Math.cos(xRotation) * (y1 - y2) / 2.0;
- var lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
- if (lambda > 1) {
- rx *= Math.sqrt(lambda);
- ry *= Math.sqrt(lambda);
- }
- var diff = rx * rx * (yp * yp) + ry * ry * (xp * xp);
- var f = diff ? Math.sqrt((rx * rx * (ry * ry) - diff) / diff) : 1;
- if (arcFlag === sweepFlag) {
- f *= -1;
- }
- if (isNaN(f)) {
- f = 0;
- }
- // 旋转前的起点坐标,且当长半轴和短半轴的长度为 0 时,坐标按 (0, 0) 处理
- var cxp = ry ? f * rx * yp / ry : 0;
- var cyp = rx ? f * -ry * xp / rx : 0;
- // 椭圆圆心坐标
- var cx = (x1 + x2) / 2.0 + Math.cos(xRotation) * cxp - Math.sin(xRotation) * cyp;
- var cy = (y1 + y2) / 2.0 + Math.sin(xRotation) * cxp + Math.cos(xRotation) * cyp;
- // 起始点的单位向量
- var u = [(xp - cxp) / rx, (yp - cyp) / ry];
- // 终止点的单位向量
- var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
- // 计算起始点和圆心的连线,与 x 轴正方向的夹角
- var theta = vAngle([1, 0], u);
- // 计算圆弧起始点和终止点与椭圆圆心连线的夹角
- var dTheta = vAngle(u, v);
- if (vRatio(u, v) <= -1) {
- dTheta = Math.PI;
- }
- if (vRatio(u, v) >= 1) {
- dTheta = 0;
- }
- if (sweepFlag === 0 && dTheta > 0) {
- dTheta = dTheta - 2 * Math.PI;
- }
- if (sweepFlag === 1 && dTheta < 0) {
- dTheta = dTheta + 2 * Math.PI;
- }
- return {
- cx: cx,
- cy: cy,
- // 弧形的起点和终点相同时,长轴和短轴的长度按 0 处理
- rx: isSamePoint(startPoint, [x2, y2]) ? 0 : rx,
- ry: isSamePoint(startPoint, [x2, y2]) ? 0 : ry,
- startAngle: theta,
- endAngle: theta + dTheta,
- xRotation: xRotation,
- arcFlag: arcFlag,
- sweepFlag: sweepFlag
- };
- }
- function commandsToPathString(commands, object, transform) {
- var _object$parsedStyle = object.parsedStyle,
- _object$parsedStyle$d = _object$parsedStyle.defX,
- defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
- _object$parsedStyle$d2 = _object$parsedStyle.defY,
- defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
- return commands.reduce(function (prev, cur) {
- var path = '';
- if (cur[0] === 'M' || cur[0] === 'L') {
- var p = vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
- if (transform) {
- vec3.transformMat4(p, p, transform);
- }
- path = "" + cur[0] + p[0] + "," + p[1];
- } else if (cur[0] === 'Z') {
- path = cur[0];
- } else if (cur[0] === 'C') {
- var p1 = vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
- var p2 = vec3.fromValues(cur[3] - defX, cur[4] - defY, 0);
- var p3 = vec3.fromValues(cur[5] - defX, cur[6] - defY, 0);
- if (transform) {
- vec3.transformMat4(p1, p1, transform);
- vec3.transformMat4(p2, p2, transform);
- vec3.transformMat4(p3, p3, transform);
- }
- path = "" + cur[0] + p1[0] + "," + p1[1] + "," + p2[0] + "," + p2[1] + "," + p3[0] + "," + p3[1];
- } else if (cur[0] === 'A') {
- var c = vec3.fromValues(cur[6] - defX, cur[7] - defY, 0);
- if (transform) {
- vec3.transformMat4(c, c, transform);
- }
- path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "," + cur[5] + "," + c[0] + "," + c[1];
- } else if (cur[0] === 'Q') {
- var _p = vec3.fromValues(cur[1] - defX, cur[2] - defY, 0);
- var _p2 = vec3.fromValues(cur[3] - defX, cur[4] - defY, 0);
- if (transform) {
- vec3.transformMat4(_p, _p, transform);
- vec3.transformMat4(_p2, _p2, transform);
- }
- path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "}";
- }
- return prev += path;
- }, '');
- }
- function lineToCommands(x1, y1, x2, y2) {
- return [['M', x1, y1], ['L', x2, y2]];
- }
- function ellipseToCommands(rx, ry, cx, cy) {
- var factor = (-1 + Math.sqrt(2)) / 3 * 4;
- var dx = rx * factor;
- var dy = ry * factor;
- var left = cx - rx;
- var right = cx + rx;
- var top = cy - ry;
- var bottom = cy + ry;
- 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']];
- }
- function polygonToCommands(points, closed) {
- var result = points.map(function (point, i) {
- return [i === 0 ? 'M' : 'L', point[0], point[1]];
- });
- if (closed) {
- result.push(['Z']);
- }
- return result;
- }
- function rectToCommands(width, height, x, y, radius) {
- // @see https://gist.github.com/danielpquinn/dd966af424030d47e476
- if (radius) {
- var tlr = radius[0],
- trr = radius[1],
- brr = radius[2],
- blr = radius[3];
- var signX = width > 0 ? 1 : -1;
- var signY = height > 0 ? 1 : -1;
- // sweep-flag @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths#arcs
- var sweepFlag = signX + signY !== 0 ? 1 : 0;
- 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) {
- return command;
- });
- }
- return [['M', x, y], ['L', x + width, y], ['L', x + width, y + height], ['L', x, y + height], ['Z']];
- }
- /**
- * convert object to path, should account for:
- * * transform & origin
- * * anchor
- * * lineWidth
- */
- function convertToPath(object, transform) {
- if (transform === void 0) {
- transform = object.getLocalTransform();
- }
- var commands = [];
- switch (object.nodeName) {
- case Shape.LINE:
- var _object$parsedStyle2 = object.parsedStyle,
- x1 = _object$parsedStyle2.x1,
- y1 = _object$parsedStyle2.y1,
- x2 = _object$parsedStyle2.x2,
- y2 = _object$parsedStyle2.y2;
- commands = lineToCommands(x1, y1, x2, y2);
- break;
- case Shape.CIRCLE:
- {
- var _object$parsedStyle3 = object.parsedStyle,
- r = _object$parsedStyle3.r,
- cx = _object$parsedStyle3.cx,
- cy = _object$parsedStyle3.cy;
- commands = ellipseToCommands(r, r, cx, cy);
- break;
- }
- case Shape.ELLIPSE:
- {
- var _object$parsedStyle4 = object.parsedStyle,
- rx = _object$parsedStyle4.rx,
- ry = _object$parsedStyle4.ry,
- _cx = _object$parsedStyle4.cx,
- _cy = _object$parsedStyle4.cy;
- commands = ellipseToCommands(rx, ry, _cx, _cy);
- break;
- }
- case Shape.POLYLINE:
- case Shape.POLYGON:
- var points = object.parsedStyle.points;
- commands = polygonToCommands(points.points, object.nodeName === Shape.POLYGON);
- break;
- case Shape.RECT:
- var _object$parsedStyle5 = object.parsedStyle,
- width = _object$parsedStyle5.width,
- height = _object$parsedStyle5.height,
- x = _object$parsedStyle5.x,
- y = _object$parsedStyle5.y,
- radius = _object$parsedStyle5.radius;
- var hasRadius = radius && radius.some(function (r) {
- return r !== 0;
- });
- commands = rectToCommands(width, height, x, y, hasRadius && radius.map(function (r) {
- return clamp(r, 0, Math.min(Math.abs(width) / 2, Math.abs(height) / 2));
- }));
- break;
- case Shape.PATH:
- var absolutePath = object.parsedStyle.path.absolutePath;
- commands = [].concat(absolutePath);
- break;
- }
- if (commands.length) {
- return commandsToPathString(commands, object, transform);
- }
- }
- function translatePathToString(absolutePath, defX, defY, startOffsetX, startOffsetY, endOffsetX, endOffsetY) {
- if (startOffsetX === void 0) {
- startOffsetX = 0;
- }
- if (startOffsetY === void 0) {
- startOffsetY = 0;
- }
- if (endOffsetX === void 0) {
- endOffsetX = 0;
- }
- if (endOffsetY === void 0) {
- endOffsetY = 0;
- }
- var newValue = absolutePath.map(function (params, i) {
- var command = params[0];
- var nextSegment = absolutePath[i + 1];
- var useStartOffset = i === 0 && (startOffsetX !== 0 || startOffsetY !== 0);
- var useEndOffset = (i === absolutePath.length - 1 || nextSegment && (nextSegment[0] === 'M' || nextSegment[0] === 'Z')) && endOffsetX !== 0 && endOffsetY !== 0;
- switch (command) {
- case 'M':
- // Use start marker offset
- if (useStartOffset) {
- return "M " + (params[1] - defX + startOffsetX) + "," + (params[2] - defY + startOffsetY) + " L " + (params[1] - defX) + "," + (params[2] - defY);
- } else {
- return "M " + (params[1] - defX) + "," + (params[2] - defY);
- }
- case 'L':
- return "L " + (params[1] - defX + (useEndOffset ? endOffsetX : 0)) + "," + (params[2] - defY + (useEndOffset ? endOffsetY : 0));
- case 'Q':
- return "Q " + (params[1] - defX) + " " + (params[2] - defY) + "," + (params[3] - defX) + " " + (params[4] - defY) + (useEndOffset ? " L " + (params[3] - defX + endOffsetX) + "," + (params[4] - defY + endOffsetY) : '');
- case 'C':
- 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) : '');
- case 'A':
- 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) : '');
- case 'Z':
- return 'Z';
- }
- }).join(' ');
- if (~newValue.indexOf('NaN')) {
- return '';
- }
- return newValue;
- }
- function isFillOrStrokeAffected(pointerEvents, fill, stroke) {
- // account for pointerEvents
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
- var hasFill = false;
- var hasStroke = false;
- var isFillOtherThanNone = !!fill && !fill.isNone;
- var isStrokeOtherThanNone = !!stroke && !stroke.isNone;
- if (pointerEvents === 'visiblepainted' || pointerEvents === 'painted' || pointerEvents === 'auto') {
- hasFill = isFillOtherThanNone;
- hasStroke = isStrokeOtherThanNone;
- } else if (pointerEvents === 'visiblefill' || pointerEvents === 'fill') {
- hasFill = true;
- } else if (pointerEvents === 'visiblestroke' || pointerEvents === 'stroke') {
- hasStroke = true;
- } else if (pointerEvents === 'visible' || pointerEvents === 'all') {
- // The values of the fill and stroke do not affect event processing.
- hasFill = true;
- hasStroke = true;
- }
- return [hasFill, hasStroke];
- }
- var AsyncParallelHook = /*#__PURE__*/function () {
- function AsyncParallelHook() {
- this.callbacks = [];
- }
- var _proto = AsyncParallelHook.prototype;
- _proto.getCallbacksNum = function getCallbacksNum() {
- return this.callbacks.length;
- };
- _proto.tapPromise = function tapPromise(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.promise = function promise() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- return Promise.all(this.callbacks.map(function (callback) {
- return callback.apply(void 0, args);
- }));
- };
- return AsyncParallelHook;
- }();
- var AsyncSeriesWaterfallHook = /*#__PURE__*/function () {
- function AsyncSeriesWaterfallHook() {
- this.callbacks = [];
- }
- var _proto = AsyncSeriesWaterfallHook.prototype;
- _proto.tapPromise = function tapPromise(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.promise = /*#__PURE__*/function () {
- var _promise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
- var _this$callbacks,
- result,
- i,
- callback,
- _args = arguments;
- return _regeneratorRuntime().wrap(function _callee$(_context) {
- while (1) switch (_context.prev = _context.next) {
- case 0:
- if (!this.callbacks.length) {
- _context.next = 14;
- break;
- }
- _context.next = 3;
- return (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, _args);
- case 3:
- result = _context.sent;
- i = 0;
- case 5:
- if (!(i < this.callbacks.length - 1)) {
- _context.next = 13;
- break;
- }
- callback = this.callbacks[i]; // @ts-ignore
- _context.next = 9;
- return callback(result);
- case 9:
- result = _context.sent;
- case 10:
- i++;
- _context.next = 5;
- break;
- case 13:
- return _context.abrupt("return", result);
- case 14:
- return _context.abrupt("return", null);
- case 15:
- case "end":
- return _context.stop();
- }
- }, _callee, this);
- }));
- function promise() {
- return _promise.apply(this, arguments);
- }
- return promise;
- }();
- return AsyncSeriesWaterfallHook;
- }();
- var SyncHook = /*#__PURE__*/function () {
- function SyncHook() {
- this.callbacks = [];
- }
- var _proto = SyncHook.prototype;
- _proto.tap = function tap(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.call = function call() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- this.callbacks.forEach(function (callback) {
- callback.apply(void 0, args);
- });
- };
- return SyncHook;
- }();
- var SyncWaterfallHook = /*#__PURE__*/function () {
- function SyncWaterfallHook() {
- this.callbacks = [];
- }
- var _proto = SyncWaterfallHook.prototype;
- _proto.tap = function tap(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.call = function call() {
- if (this.callbacks.length) {
- var _this$callbacks;
- var result = (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, arguments);
- for (var i = 0; i < this.callbacks.length - 1; i++) {
- var callback = this.callbacks[i];
- // @ts-ignore
- result = callback(result);
- }
- return result;
- }
- return null;
- };
- return SyncWaterfallHook;
- }();
- var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui'];
- var stringRegExp = /([\"\'])[^\'\"]+\1/;
- function toFontString(attributes) {
- var fontSize = attributes.fontSize,
- fontFamily = attributes.fontFamily,
- fontStyle = attributes.fontStyle,
- fontVariant = attributes.fontVariant,
- fontWeight = attributes.fontWeight;
- // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
- // const fontSizeString: string = isNumber(fontSize) ? `${fontSize}px` : fontSize.toString();
- var fontSizeString = isNumber(fontSize) && fontSize + "px" || '16px';
- // Clean-up fontFamily property by quoting each font name
- // this will support font names with spaces
- var fontFamilies = fontFamily.split(',');
- for (var i = fontFamilies.length - 1; i >= 0; i--) {
- // Trim any extra white-space
- var _fontFamily = fontFamilies[i].trim();
- // Check if font already contains strings
- if (!stringRegExp.test(_fontFamily) && genericFontFamilies.indexOf(_fontFamily) < 0) {
- _fontFamily = "\"" + _fontFamily + "\"";
- }
- fontFamilies[i] = _fontFamily;
- }
- return fontStyle + " " + fontVariant + " " + fontWeight + " " + fontSizeString + " " + fontFamilies.join(',');
- }
- /**
- * Thanks for following contributor of codes
- * https://gist.github.com/1866474
- * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
- * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
- * https://github.com/Financial-Times/polyfill-library/blob/master/polyfills/requestAnimationFrame/polyfill.js
- **/
- var uId = 1;
- var uniqueId = function uniqueId() {
- return uId++;
- };
- // We use `self` instead of `window` for `WebWorker` support.
- var root = typeof self === 'object' && self.self == self ? self :
- // @ts-ignore
- typeof global === 'object' && global.global == global ?
- // @ts-ignore
- global : {};
- var nowOffset = Date.now();
- // use performance api if exist, otherwise use Date.now.
- // Date.now polyfill required.
- var pnow = function pnow() {
- if (root.performance && typeof root.performance.now === 'function') {
- return root.performance.now();
- }
- // fallback
- return Date.now() - nowOffset;
- };
- var reservedCBs = {};
- var lastTime = Date.now();
- var polyfillRaf = function polyfillRaf(callback) {
- if (typeof callback !== 'function') {
- throw new TypeError(callback + ' is not a function');
- }
- var currentTime = Date.now();
- var gap = currentTime - lastTime;
- var delay = gap > 16 ? 0 : 16 - gap;
- var id = uniqueId();
- reservedCBs[id] = callback;
- // keys(reservedCBs).length > 1 의미는 이미 setTimeout 이 걸려있는 경우.
- // 함께 callback 이 실행될 수 있게 reservedCBs 에만 추가해주고 return
- if (Object.keys(reservedCBs).length > 1) return id;
- setTimeout(function () {
- lastTime = currentTime;
- var copied = reservedCBs;
- reservedCBs = {};
- Object.keys(copied).forEach(function (key) {
- return copied[key](pnow());
- });
- }, delay);
- return id;
- };
- var polyfillCaf = function polyfillCaf(id) {
- delete reservedCBs[id];
- };
- var vendorPrefixes = ['', 'webkit', 'moz', 'ms', 'o'];
- var getRequestAnimationFrame = function getRequestAnimationFrame(vp) {
- if (typeof vp !== 'string') return polyfillRaf;
- if (vp === '') return root['requestAnimationFrame'];
- return root[vp + 'RequestAnimationFrame'];
- };
- var getCancelAnimationFrame = function getCancelAnimationFrame(vp) {
- if (typeof vp !== 'string') return polyfillCaf;
- if (vp === '') return root['cancelAnimationFrame'];
- return root[vp + 'CancelAnimationFrame'] || root[vp + 'CancelRequestAnimationFrame'];
- };
- var find = function find(arr, predicate) {
- var i = 0;
- while (arr[i] !== void 0) {
- if (predicate(arr[i])) return arr[i];
- i = i + 1;
- }
- };
- var vp = find(vendorPrefixes, function (vp) {
- return !!getRequestAnimationFrame(vp);
- });
- var raf = getRequestAnimationFrame(vp);
- var caf = getCancelAnimationFrame(vp);
- root.requestAnimationFrame = raf;
- root.cancelAnimationFrame = caf;
- var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i;
- var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i;
- var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i;
- var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/gi;
- function spaceColorStops(colorStops) {
- var _colorStops$length;
- var length = colorStops.length;
- colorStops[length - 1].length = (_colorStops$length = colorStops[length - 1].length) !== null && _colorStops$length !== void 0 ? _colorStops$length : {
- type: '%',
- value: '100'
- };
- if (length > 1) {
- var _colorStops$0$length;
- colorStops[0].length = (_colorStops$0$length = colorStops[0].length) !== null && _colorStops$0$length !== void 0 ? _colorStops$0$length : {
- type: '%',
- value: '0'
- };
- }
- var previousIndex = 0;
- var previousOffset = Number(colorStops[0].length.value);
- for (var i = 1; i < length; i++) {
- var _colorStops$i$length;
- // support '%' & 'px'
- var offset = (_colorStops$i$length = colorStops[i].length) === null || _colorStops$i$length === void 0 ? void 0 : _colorStops$i$length.value;
- if (!isNil(offset) && !isNil(previousOffset)) {
- for (var j = 1; j < i - previousIndex; j++) colorStops[previousIndex + j].length = {
- type: '%',
- value: "" + (previousOffset + (Number(offset) - previousOffset) * j / (i - previousIndex))
- };
- previousIndex = i;
- previousOffset = Number(offset);
- }
- }
- }
- // The position of the gradient line's starting point.
- // different from CSS side(to top) @see https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#values
- var SideOrCornerToDegMap = {
- left: 270 - 90,
- top: 0 - 90,
- bottom: 180 - 90,
- right: 90 - 90,
- 'left top': 315 - 90,
- 'top left': 315 - 90,
- 'left bottom': 225 - 90,
- 'bottom left': 225 - 90,
- 'right top': 45 - 90,
- 'top right': 45 - 90,
- 'right bottom': 135 - 90,
- 'bottom right': 135 - 90
- };
- var angleToDeg = memoize(function (orientation) {
- var angle;
- if (orientation.type === 'angular') {
- angle = Number(orientation.value);
- } else {
- angle = SideOrCornerToDegMap[orientation.value] || 0;
- }
- return getOrCreateUnitValue(angle, 'deg');
- });
- var positonToCSSUnitValue = memoize(function (position) {
- var cx = 50;
- var cy = 50;
- var unitX = '%';
- var unitY = '%';
- if ((position === null || position === void 0 ? void 0 : position.type) === 'position') {
- var _position$value = position.value,
- x = _position$value.x,
- y = _position$value.y;
- if ((x === null || x === void 0 ? void 0 : x.type) === 'position-keyword') {
- if (x.value === 'left') {
- cx = 0;
- } else if (x.value === 'center') {
- cx = 50;
- } else if (x.value === 'right') {
- cx = 100;
- } else if (x.value === 'top') {
- cy = 0;
- } else if (x.value === 'bottom') {
- cy = 100;
- }
- }
- if ((y === null || y === void 0 ? void 0 : y.type) === 'position-keyword') {
- if (y.value === 'left') {
- cx = 0;
- } else if (y.value === 'center') {
- cy = 50;
- } else if (y.value === 'right') {
- cx = 100;
- } else if (y.value === 'top') {
- cy = 0;
- } else if (y.value === 'bottom') {
- cy = 100;
- }
- }
- 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') {
- unitX = x === null || x === void 0 ? void 0 : x.type;
- cx = Number(x.value);
- }
- 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') {
- unitY = y === null || y === void 0 ? void 0 : y.type;
- cy = Number(y.value);
- }
- }
- return {
- cx: getOrCreateUnitValue(cx, unitX),
- cy: getOrCreateUnitValue(cy, unitY)
- };
- });
- var parseGradient$1 = memoize(function (colorStr) {
- if (colorStr.indexOf('linear') > -1 || colorStr.indexOf('radial') > -1) {
- var ast = parseGradient(colorStr);
- return ast.map(function (_ref) {
- var type = _ref.type,
- orientation = _ref.orientation,
- colorStops = _ref.colorStops;
- spaceColorStops(colorStops);
- var steps = colorStops.map(function (colorStop) {
- // TODO: only support % for now, should calc percentage of axis length when using px/em
- return {
- offset: getOrCreateUnitValue(Number(colorStop.length.value), '%'),
- color: colorStopToString(colorStop)
- };
- });
- if (type === 'linear-gradient') {
- return new CSSGradientValue(GradientType.LinearGradient, {
- angle: orientation ? angleToDeg(orientation) : Odeg,
- steps: steps
- });
- } else if (type === 'radial-gradient') {
- if (!orientation) {
- orientation = [{
- type: 'shape',
- value: 'circle'
- }];
- }
- if (orientation[0].type === 'shape' && orientation[0].value === 'circle') {
- var _positonToCSSUnitValu = positonToCSSUnitValue(orientation[0].at),
- cx = _positonToCSSUnitValu.cx,
- cy = _positonToCSSUnitValu.cy;
- var size;
- if (orientation[0].style) {
- var _orientation$0$style = orientation[0].style,
- _type = _orientation$0$style.type,
- value = _orientation$0$style.value;
- if (_type === 'extent-keyword') {
- size = getOrCreateKeyword(value);
- } else {
- size = getOrCreateUnitValue(value, _type);
- }
- }
- return new CSSGradientValue(GradientType.RadialGradient, {
- cx: cx,
- cy: cy,
- size: size,
- steps: steps
- });
- }
- // TODO: support ellipse shape
- // TODO: repeating-linear-gradient & repeating-radial-gradient
- // } else if (type === 'repeating-linear-gradient') {
- // } else if (type === 'repeating-radial-gradient') {
- }
- });
- }
- // legacy format, should be deprecated later
- var type = colorStr[0];
- if (colorStr[1] === '(' || colorStr[2] === '(') {
- if (type === 'l') {
- var arr = regexLG.exec(colorStr);
- if (arr) {
- var _arr$2$match;
- var steps = ((_arr$2$match = arr[2].match(regexColorStop)) === null || _arr$2$match === void 0 ? void 0 : _arr$2$match.map(function (stop) {
- return stop.split(':');
- })) || [];
- return [new CSSGradientValue(GradientType.LinearGradient, {
- angle: getOrCreateUnitValue(parseFloat(arr[1]), 'deg'),
- steps: steps.map(function (_ref2) {
- var offset = _ref2[0],
- color = _ref2[1];
- return {
- offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
- color: color
- };
- })
- })];
- }
- } else if (type === 'r') {
- var parsedRadialGradient = parseRadialGradient(colorStr);
- if (parsedRadialGradient) {
- if (isString(parsedRadialGradient)) {
- colorStr = parsedRadialGradient;
- } else {
- return [new CSSGradientValue(GradientType.RadialGradient, parsedRadialGradient)];
- }
- }
- } else if (type === 'p') {
- return parsePattern(colorStr);
- }
- }
- });
- function parseRadialGradient(gradientStr) {
- var arr = regexRG.exec(gradientStr);
- if (arr) {
- var _arr$4$match;
- var steps = ((_arr$4$match = arr[4].match(regexColorStop)) === null || _arr$4$match === void 0 ? void 0 : _arr$4$match.map(function (stop) {
- return stop.split(':');
- })) || [];
- return {
- cx: getOrCreateUnitValue(50, '%'),
- cy: getOrCreateUnitValue(50, '%'),
- steps: steps.map(function (_ref3) {
- var offset = _ref3[0],
- color = _ref3[1];
- return {
- offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
- color: color
- };
- })
- };
- }
- return null;
- }
- function parsePattern(patternStr) {
- var arr = regexPR.exec(patternStr);
- if (arr) {
- var repetition = arr[1];
- var src = arr[2];
- switch (repetition) {
- case 'a':
- repetition = 'repeat';
- break;
- case 'x':
- repetition = 'repeat-x';
- break;
- case 'y':
- repetition = 'repeat-y';
- break;
- case 'n':
- repetition = 'no-repeat';
- break;
- default:
- repetition = 'no-repeat';
- }
- return {
- image: src,
- // @ts-ignore
- repetition: repetition
- };
- }
- return null;
- }
- function isCSSGradientValue(object) {
- return !!object.type && !!object.value;
- }
- function isPattern(object) {
- return object && !!object.image;
- }
- function isCSSRGB(object) {
- return object && !isNil(object.r) && !isNil(object.g) && !isNil(object.b);
- }
- /**
- * @see https://github.com/WebKit/WebKit/blob/main/Source/WebCore/css/parser/CSSParser.cpp#L97
- */
- var parseColor = memoize(function (colorStr) {
- if (isPattern(colorStr)) {
- return _extends({
- repetition: 'repeat'
- }, colorStr);
- }
- if (isNil(colorStr)) {
- colorStr = '';
- }
- if (colorStr === 'transparent') {
- // transparent black
- return transparentColor;
- } else if (colorStr === 'currentColor') {
- // @see https://github.com/adobe-webplatform/Snap.svg/issues/526
- colorStr = 'black';
- }
- // support CSS gradient syntax
- var g = parseGradient$1(colorStr);
- if (g) {
- return g;
- }
- // constants
- var color$1 = color(colorStr);
- var rgba = [0, 0, 0, 0];
- if (color$1 !== null) {
- rgba[0] = color$1.r || 0;
- rgba[1] = color$1.g || 0;
- rgba[2] = color$1.b || 0;
- rgba[3] = color$1.opacity;
- }
- // return new CSSRGB(...rgba);
- return getOrCreateRGBA.apply(void 0, rgba);
- });
- function mergeColors(left, right) {
- // only support constant value, exclude gradient & pattern
- if (!isCSSRGB(left) || !isCSSRGB(right)) {
- return;
- }
- 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) {
- var rgba = color.slice();
- if (rgba[3]) {
- for (var i = 0; i < 3; i++) rgba[i] = Math.round(clamp(rgba[i], 0, 255));
- }
- rgba[3] = clamp(rgba[3], 0, 1);
- return "rgba(" + rgba.join(',') + ")";
- }];
- }
- function parseDimension(unitRegExp, string) {
- if (isNil(string)) {
- return getOrCreateUnitValue(0, 'px');
- }
- string = ("" + string).trim().toLowerCase();
- if (isFinite(Number(string))) {
- if ('px'.search(unitRegExp) >= 0) {
- return getOrCreateUnitValue(Number(string), 'px');
- } else if ('deg'.search(unitRegExp) >= 0) {
- return getOrCreateUnitValue(Number(string), 'deg');
- }
- }
- var matchedUnits = [];
- string = string.replace(unitRegExp, function (match) {
- matchedUnits.push(match);
- return 'U' + match;
- });
- var taggedUnitRegExp = 'U(' + unitRegExp.source + ')';
- return matchedUnits.map(function (unit) {
- return getOrCreateUnitValue(Number(string.replace(new RegExp('U' + unit, 'g'), '').replace(new RegExp(taggedUnitRegExp, 'g'), '*0')), unit);
- })[0];
- }
- /**
- * <length>
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length
- * length with only absolute unit, eg. 1px
- */
- var parseLength = memoize(function (css) {
- return parseDimension(new RegExp('px', 'g'), css);
- });
- /**
- * <percentage>
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage
- */
- var parserPercentage = memoize(function (css) {
- return parseDimension(new RegExp('%', 'g'), css);
- });
- /**
- * length with absolute or relative unit,
- * eg. 1px, 0.7em, 50%, calc(100% - 200px);
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length-percentage
- */
- // export const parseLengthOrPercentage = memoize((css: string): CSSUnitValue => {
- // if (isNumber(css) || isFinite(Number(css))) {
- // return getOrCreateUnitValue(Number(css), 'px');
- // }
- // return parseDimension(new RegExp('px|%|em|rem', 'g'), css) as CSSUnitValue;
- // });
- var parseLengthOrPercentage = function parseLengthOrPercentage(css) {
- if (isNumber(css) || isFinite(Number(css))) {
- // Number(css) is NaN
- return getOrCreateUnitValue(Number(css) || 0, 'px');
- // return Number(css);
- }
- return parseDimension(new RegExp('px|%|em|rem', 'g'), css);
- };
- var parseAngle = memoize(function (css) {
- return parseDimension(new RegExp('deg|rad|grad|turn', 'g'), css);
- });
- /**
- * merge CSSUnitValue
- *
- * @example
- * 10px + 20px = 30px
- * 10deg + 10rad
- * 10% + 20% = 30%
- */
- function mergeDimensions(left, right, target, nonNegative, index) {
- if (index === void 0) {
- index = 0;
- }
- var unit = '';
- var leftValue = left.value || 0;
- var rightValue = right.value || 0;
- var canonicalUnit = toCanonicalUnit(left.unit);
- var leftCanonicalUnitValue = left.convertTo(canonicalUnit);
- var rightCanonicalUnitValue = right.convertTo(canonicalUnit);
- if (leftCanonicalUnitValue && rightCanonicalUnitValue) {
- leftValue = leftCanonicalUnitValue.value;
- rightValue = rightCanonicalUnitValue.value;
- unit = unitTypeToString(left.unit);
- } else {
- // format '%' to 'px'
- if (CSSUnitValue.isLength(left.unit) || CSSUnitValue.isLength(right.unit)) {
- leftValue = convertPercentUnit(left, index, target);
- rightValue = convertPercentUnit(right, index, target);
- unit = 'px';
- }
- }
- // // format 'rad' 'turn' to 'deg'
- // if (CSSUnitValue.isAngle(left.unit) || CSSUnitValue.isAngle(right.unit)) {
- // leftValue = convertAngleUnit(left);
- // rightValue = convertAngleUnit(right);
- // unit = 'deg';
- // }
- return [leftValue, rightValue, function (value) {
- if (nonNegative) {
- value = Math.max(value, 0);
- }
- return value + unit;
- }];
- }
- function convertAngleUnit(value) {
- var deg = 0;
- if (value.unit === UnitType.kDegrees) {
- deg = value.value;
- } else if (value.unit === UnitType.kRadians) {
- deg = rad2deg(Number(value.value));
- } else if (value.unit === UnitType.kTurns) {
- deg = turn2deg(Number(value.value));
- }
- return deg;
- }
- function parseDimensionArrayFormat(string, size) {
- var parsed;
- if (Array.isArray(string)) {
- // [1, '2px', 3]
- parsed = string.map(function (segment) {
- return Number(segment);
- });
- } else if (isString(string)) {
- parsed = string.split(' ').map(function (segment) {
- return Number(segment);
- });
- } else if (isNumber(string)) {
- parsed = [string];
- }
- if (size === 2) {
- if (parsed.length === 1) {
- return [parsed[0], parsed[0]];
- } else {
- return [parsed[0], parsed[1]];
- }
- } else {
- if (parsed.length === 1) {
- return [parsed[0], parsed[0], parsed[0], parsed[0]];
- } else if (parsed.length === 2) {
- return [parsed[0], parsed[1], parsed[0], parsed[1]];
- } else if (parsed.length === 3) {
- return [parsed[0], parsed[1], parsed[2], parsed[1]];
- } else {
- return [parsed[0], parsed[1], parsed[2], parsed[3]];
- }
- }
- }
- function parseDimensionArray(string) {
- if (isString(string)) {
- // "1px 2px 3px"
- return string.split(' ').map(function (segment) {
- return parseLengthOrPercentage(segment);
- });
- } else {
- // [1, '2px', 3]
- return string.map(function (segment) {
- return parseLengthOrPercentage(segment.toString());
- });
- }
- }
- // export function mergeDimensionList(
- // left: CSSUnitValue[],
- // right: CSSUnitValue[],
- // target: IElement | null,
- // ): [number[], number[], (list: number[]) => string] | undefined {
- // if (left.length !== right.length) {
- // return;
- // }
- // const unit = left[0].unit;
- // return [
- // left.map((l) => l.value),
- // right.map((l) => l.value),
- // (values: number[]) => {
- // return values.map((n) => new CSSUnitValue(n, unit)).join(' ');
- // },
- // ];
- // }
- function convertPercentUnit(valueWithUnit, vec3Index, target) {
- if (valueWithUnit.value === 0) {
- return 0;
- }
- if (valueWithUnit.unit === UnitType.kPixels) {
- return Number(valueWithUnit.value);
- } else if (valueWithUnit.unit === UnitType.kPercentage && target) {
- var bounds = target.nodeName === Shape.GROUP ? target.getLocalBounds() :
- // : target.getGeometryBounds();
- target.geometry.contentBounds;
- return valueWithUnit.value / 100 * bounds.halfExtents[vec3Index] * 2;
- }
- return 0;
- }
- var parseParam = function parseParam(css) {
- return parseDimension(/deg|rad|grad|turn|px|%/g, css);
- };
- var supportedFilters = ['blur', 'brightness', 'drop-shadow', 'contrast', 'grayscale', 'sepia', 'saturate', 'hue-rotate', 'invert'];
- function parseFilter(filterStr) {
- if (filterStr === void 0) {
- filterStr = '';
- }
- filterStr = filterStr.toLowerCase().trim();
- if (filterStr === 'none') {
- return [];
- }
- var filterRegExp = /\s*([\w-]+)\(([^)]*)\)/g;
- var result = [];
- var match;
- var prevLastIndex = 0;
- while (match = filterRegExp.exec(filterStr)) {
- if (match.index !== prevLastIndex) {
- return [];
- }
- prevLastIndex = match.index + match[0].length;
- if (supportedFilters.indexOf(match[1]) > -1) {
- result.push({
- name: match[1],
- params: match[2].split(' ').map(function (p) {
- return parseParam(p) || parseColor(p);
- })
- });
- }
- if (filterRegExp.lastIndex === filterStr.length) {
- return result;
- }
- }
- return [];
- }
- function numberToString(x) {
- // scale(0.00000001) -> scale(0)
- // return x.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
- return x.toString();
- }
- /**
- * parse string or number to CSSUnitValue(numeric)
- *
- * eg.
- * * 0 -> CSSUnitValue(0)
- * * '2' -> CSSUnitValue(2)
- */
- var parseNumber = memoize(function (string) {
- if (typeof string === 'number') {
- return getOrCreateUnitValue(string);
- }
- if (/^\s*[-+]?(\d*\.)?\d+\s*$/.test(string)) {
- return getOrCreateUnitValue(Number(string));
- } else {
- return getOrCreateUnitValue(0);
- }
- });
- /**
- * separate string to array
- * eg.
- * * [0.5, 0.5] -> [CSSUnitValue, CSSUnitValue]
- */
- var parseNumberList = memoize(function (string) {
- if (isString(string)) {
- return string.split(' ').map(parseNumber);
- } else {
- return string.map(parseNumber);
- }
- });
- function mergeNumbers(left, right) {
- return [left, right, numberToString];
- }
- function clampedMergeNumbers(min, max) {
- return function (left, right) {
- return [left, right, function (x) {
- return numberToString(clamp(x, min, max));
- }];
- };
- }
- function mergeNumberLists(left, right) {
- if (left.length !== right.length) {
- return;
- }
- return [left, right, function (numberList) {
- return numberList;
- }];
- }
- var internalParsePath = function internalParsePath(path) {
- // empty path
- if (path === '' || Array.isArray(path) && path.length === 0) {
- return {
- absolutePath: [],
- hasArc: false,
- segments: [],
- polygons: [],
- polylines: [],
- curve: null,
- totalLength: 0,
- rect: {
- x: 0,
- y: 0,
- width: 0,
- height: 0
- }
- };
- }
- var absolutePath;
- try {
- absolutePath = normalizePath(path);
- } catch (e) {
- absolutePath = normalizePath('');
- console.error("[g]: Invalid SVG Path definition: " + path);
- }
- var hasArc = hasArcOrBezier(absolutePath);
- var _extractPolygons = extractPolygons(absolutePath),
- polygons = _extractPolygons.polygons,
- polylines = _extractPolygons.polylines;
- // for later use
- var segments = path2Segments(absolutePath);
- // Only calculate bbox here since we don't need length now.
- var _getPathBBox = getPathBBox(segments, 0),
- x = _getPathBBox.x,
- y = _getPathBBox.y,
- width = _getPathBBox.width,
- height = _getPathBBox.height;
- return {
- absolutePath: absolutePath,
- hasArc: hasArc,
- segments: segments,
- polygons: polygons,
- polylines: polylines,
- // curve,
- // Delay the calculation of length.
- totalLength: 0,
- rect: {
- x: Number.isFinite(x) ? x : 0,
- y: Number.isFinite(y) ? y : 0,
- width: Number.isFinite(width) ? width : 0,
- height: Number.isFinite(height) ? height : 0
- }
- };
- };
- var memoizedParsePath = memoize(internalParsePath);
- function parsePath(path, object) {
- var result = isString(path) ? memoizedParsePath(path) : internalParsePath(path);
- if (object) {
- object.parsedStyle.defX = result.rect.x;
- object.parsedStyle.defY = result.rect.y;
- }
- return result;
- }
- function mergePaths(left, right, object) {
- var curve1 = left.curve;
- var curve2 = right.curve;
- if (!curve1 || curve1.length === 0) {
- // convert to curves to do morphing & picking later
- // @see http://thednp.github.io/kute.js/svgCubicMorph.html
- curve1 = path2Curve(left.absolutePath, false);
- left.curve = curve1;
- }
- if (!curve2 || curve2.length === 0) {
- curve2 = path2Curve(right.absolutePath, false);
- right.curve = curve2;
- }
- var curves = [curve1, curve2];
- if (curve1.length !== curve2.length) {
- curves = equalizeSegments(curve1, curve2);
- }
- var curve0 = getDrawDirection(curves[0]) !== getDrawDirection(curves[1]) ? reverseCurve(curves[0]) : clonePath(curves[0]);
- return [curve0, getRotatedCurve(curves[1], curve0), function (pathArray) {
- // need converting to path string?
- return pathArray;
- }];
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/points
- *
- * @example
- * points="100,10 250,150 200,110"
- */
- function parsePoints(pointsOrStr, object) {
- var points;
- if (isString(pointsOrStr)) {
- points = pointsOrStr.split(' ').map(function (pointStr) {
- var _pointStr$split = pointStr.split(','),
- x = _pointStr$split[0],
- y = _pointStr$split[1];
- return [Number(x), Number(y)];
- });
- } else {
- points = pointsOrStr;
- }
- var segments = [];
- var tempLength = 0;
- var segmentT;
- var segmentL;
- var totalLength = Polyline$1.length(points);
- points.forEach(function (p, i) {
- if (points[i + 1]) {
- segmentT = [0, 0];
- segmentT[0] = tempLength / totalLength;
- segmentL = Line$1.length(p[0], p[1], points[i + 1][0], points[i + 1][1]);
- tempLength += segmentL;
- segmentT[1] = tempLength / totalLength;
- segments.push(segmentT);
- }
- });
- var minX = Math.min.apply(Math, points.map(function (point) {
- return point[0];
- }));
- var minY = Math.min.apply(Math, points.map(function (point) {
- return point[1];
- }));
- if (object) {
- object.parsedStyle.defX = minX;
- object.parsedStyle.defY = minY;
- }
- return {
- points: points,
- totalLength: totalLength,
- segments: segments
- };
- }
- function mergePoints(left, right) {
- return [left.points, right.points, function (points) {
- return points;
- }];
- }
- var _ = null;
- function cast(pattern) {
- return function (contents) {
- var i = 0;
- return pattern.map(function (x) {
- return x === _ ? contents[i++] : x;
- });
- };
- }
- function id(x) {
- return x;
- }
- // type: [argTypes, convertTo3D, convertTo2D]
- // In the argument types string, lowercase characters represent optional arguments
- var transformFunctions = {
- // @ts-ignore
- matrix: ['NNNNNN', [_, _, 0, 0, _, _, 0, 0, 0, 0, 1, 0, _, _, 0, 1], id],
- matrix3d: ['NNNNNNNNNNNNNNNN', id],
- rotate: ['A'],
- rotatex: ['A'],
- rotatey: ['A'],
- rotatez: ['A'],
- rotate3d: ['NNNA'],
- perspective: ['L'],
- scale: ['Nn', cast([_, _, new CSSUnitValue(1)]), id],
- scalex: ['N', cast([_, new CSSUnitValue(1), new CSSUnitValue(1)]), cast([_, new CSSUnitValue(1)])],
- scaley: ['N', cast([new CSSUnitValue(1), _, new CSSUnitValue(1)]), cast([new CSSUnitValue(1), _])],
- scalez: ['N', cast([new CSSUnitValue(1), new CSSUnitValue(1), _])],
- scale3d: ['NNN', id],
- skew: ['Aa', null, id],
- skewx: ['A', null, cast([_, Odeg])],
- skewy: ['A', null, cast([Odeg, _])],
- translate: ['Tt', cast([_, _, Opx]), id],
- translatex: ['T', cast([_, Opx, Opx]), cast([_, Opx])],
- translatey: ['T', cast([Opx, _, Opx]), cast([Opx, _])],
- translatez: ['L', cast([Opx, Opx, _])],
- translate3d: ['TTL', id]
- };
- /**
- * none
- * scale(1) scale(1, 2)
- * scaleX(1)
- */
- function parseTransform(string) {
- string = (string || 'none').toLowerCase().trim();
- if (string === 'none') {
- return [];
- }
- var transformRegExp = /\s*(\w+)\(([^)]*)\)/g;
- var result = [];
- var match;
- var prevLastIndex = 0;
- while (match = transformRegExp.exec(string)) {
- if (match.index !== prevLastIndex) {
- return [];
- }
- prevLastIndex = match.index + match[0].length;
- var functionName = match[1]; // scale
- var functionData = transformFunctions[functionName]; // scale(1, 2)
- if (!functionData) {
- // invalid, eg. scale()
- return [];
- }
- var args = match[2].split(','); // 1,2
- var argTypes = functionData[0]; // Nn
- if (argTypes.length < args.length) {
- // scale(N, n)
- return [];
- }
- var parsedArgs = [];
- for (var i = 0; i < argTypes.length; i++) {
- var arg = args[i];
- var type = argTypes[i];
- var parsedArg = void 0;
- if (!arg) {
- // @ts-ignore
- parsedArg = {
- a: Odeg,
- n: parsedArgs[0],
- t: Opx
- }[type];
- } else {
- // @ts-ignore
- parsedArg = {
- A: function A(s) {
- return s.trim() === '0' ? Odeg : parseAngle(s);
- },
- N: parseNumber,
- T: parseLengthOrPercentage,
- L: parseLength
- }[type.toUpperCase()](arg);
- }
- if (parsedArg === undefined) {
- return [];
- }
- parsedArgs.push(parsedArg);
- }
- result.push({
- t: functionName,
- d: parsedArgs
- }); // { t: scale, d: [1, 2] }
- if (transformRegExp.lastIndex === string.length) {
- return result;
- }
- }
- return [];
- }
- function convertItemToMatrix(item) {
- var x;
- var y;
- var z;
- var angle;
- switch (item.t) {
- case 'rotatex':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- 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];
- case 'rotatey':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- 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];
- case 'rotate':
- case 'rotatez':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- 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];
- case 'rotate3d':
- x = item.d[0].value;
- y = item.d[1].value;
- z = item.d[2].value;
- angle = deg2rad(convertAngleUnit(item.d[3]));
- var sqrLength = x * x + y * y + z * z;
- if (sqrLength === 0) {
- x = 1;
- y = 0;
- z = 0;
- } else if (sqrLength !== 1) {
- var length = Math.sqrt(sqrLength);
- x /= length;
- y /= length;
- z /= length;
- }
- var s = Math.sin(angle / 2);
- var sc = s * Math.cos(angle / 2);
- var sq = s * s;
- 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];
- case 'scale':
- return [item.d[0].value, 0, 0, 0, 0, item.d[1].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'scalex':
- return [item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'scaley':
- return [1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'scalez':
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1];
- case 'scale3d':
- 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];
- case 'skew':
- var xAngle = deg2rad(convertAngleUnit(item.d[0]));
- var yAngle = deg2rad(convertAngleUnit(item.d[1]));
- return [1, Math.tan(yAngle), 0, 0, Math.tan(xAngle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'skewx':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [1, 0, 0, 0, Math.tan(angle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'skewy':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [1, Math.tan(angle), 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'translate':
- // TODO: pass target
- x = convertPercentUnit(item.d[0], 0, null) || 0;
- y = convertPercentUnit(item.d[1], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1];
- case 'translatex':
- x = convertPercentUnit(item.d[0], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1];
- case 'translatey':
- y = convertPercentUnit(item.d[0], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, y, 0, 1];
- case 'translatez':
- z = convertPercentUnit(item.d[0], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, z, 1];
- case 'translate3d':
- x = convertPercentUnit(item.d[0], 0, null) || 0;
- y = convertPercentUnit(item.d[1], 0, null) || 0;
- z = convertPercentUnit(item.d[2], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
- case 'perspective':
- var t = convertPercentUnit(item.d[0], 0, null) || 0;
- var p = t ? -1 / t : 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, p, 0, 0, 0, 1];
- case 'matrix':
- 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];
- case 'matrix3d':
- return item.d.map(function (d) {
- return d.value;
- });
- }
- }
- function multiplyMatrices(a, b) {
- 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]];
- }
- function convertToMatrix(transformList) {
- if (transformList.length === 0) {
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- }
- return transformList.map(convertItemToMatrix).reduce(multiplyMatrices);
- }
- function makeMatrixDecomposition(transformList) {
- var translate = [0, 0, 0];
- var scale = [1, 1, 1];
- var skew = [0, 0, 0];
- var perspective = [0, 0, 0, 1];
- var quaternion = [0, 0, 0, 1];
- // @ts-ignore
- decomposeMat4(convertToMatrix(transformList), translate, scale, skew, perspective, quaternion);
- return [[translate, scale, skew, quaternion, perspective]];
- }
- var composeMatrix = function () {
- function multiply(a, b) {
- var result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
- for (var i = 0; i < 4; i++) {
- for (var j = 0; j < 4; j++) {
- for (var k = 0; k < 4; k++) {
- result[i][j] += b[i][k] * a[k][j];
- }
- }
- }
- return result;
- }
- function is2D(m) {
- 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;
- }
- function composeMatrix(translate, scale, skew, quat, perspective) {
- var matrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
- for (var i = 0; i < 4; i++) {
- matrix[i][3] = perspective[i];
- }
- for (var _i = 0; _i < 3; _i++) {
- for (var j = 0; j < 3; j++) {
- matrix[3][_i] += translate[j] * matrix[j][_i];
- }
- }
- var x = quat[0],
- y = quat[1],
- z = quat[2],
- w = quat[3];
- var rotMatrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
- rotMatrix[0][0] = 1 - 2 * (y * y + z * z);
- rotMatrix[0][1] = 2 * (x * y - z * w);
- rotMatrix[0][2] = 2 * (x * z + y * w);
- rotMatrix[1][0] = 2 * (x * y + z * w);
- rotMatrix[1][1] = 1 - 2 * (x * x + z * z);
- rotMatrix[1][2] = 2 * (y * z - x * w);
- rotMatrix[2][0] = 2 * (x * z - y * w);
- rotMatrix[2][1] = 2 * (y * z + x * w);
- rotMatrix[2][2] = 1 - 2 * (x * x + y * y);
- matrix = multiply(matrix, rotMatrix);
- var temp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
- if (skew[2]) {
- temp[2][1] = skew[2];
- matrix = multiply(matrix, temp);
- }
- if (skew[1]) {
- temp[2][1] = 0;
- temp[2][0] = skew[0];
- matrix = multiply(matrix, temp);
- }
- if (skew[0]) {
- temp[2][0] = 0;
- temp[1][0] = skew[0];
- matrix = multiply(matrix, temp);
- }
- for (var _i2 = 0; _i2 < 3; _i2++) {
- for (var _j = 0; _j < 3; _j++) {
- matrix[_i2][_j] *= scale[_i2];
- }
- }
- if (is2D(matrix)) {
- return [matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1], matrix[3][0], matrix[3][1]];
- }
- return matrix[0].concat(matrix[1], matrix[2], matrix[3]);
- }
- return composeMatrix;
- }();
- function numberToLongString(x) {
- return x.toFixed(6).replace('.000000', '');
- }
- function mergeMatrices(left, right) {
- var leftArgs;
- var rightArgs;
- // @ts-ignore
- if (left.decompositionPair !== right) {
- // @ts-ignore
- left.decompositionPair = right;
- // @ts-ignore
- leftArgs = makeMatrixDecomposition(left);
- }
- // @ts-ignore
- if (right.decompositionPair !== left) {
- // @ts-ignore
- right.decompositionPair = left;
- // @ts-ignore
- rightArgs = makeMatrixDecomposition(right);
- }
- if (leftArgs[0] === null || rightArgs[0] === null) return [
- // @ts-ignore
- [false],
- // @ts-ignore
- [true],
- // @ts-ignore
- function (x) {
- return x ? right[0].d : left[0].d;
- }];
- leftArgs[0].push(0);
- rightArgs[0].push(1);
- return [leftArgs, rightArgs,
- // @ts-ignore
- function (list) {
- // @ts-ignore
- var q = quat(leftArgs[0][3], rightArgs[0][3], list[5]);
- var mat = composeMatrix(list[0], list[1], list[2], q, list[4]);
- var stringifiedArgs = mat.map(numberToLongString).join(',');
- return stringifiedArgs;
- }];
- }
- function dot(v1, v2) {
- var result = 0;
- for (var i = 0; i < v1.length; i++) {
- result += v1[i] * v2[i];
- }
- return result;
- }
- function quat(fromQ, toQ, f) {
- var product = dot(fromQ, toQ);
- product = clamp(product, -1.0, 1.0);
- var quat = [];
- if (product === 1.0) {
- quat = fromQ;
- } else {
- var theta = Math.acos(product);
- var w = Math.sin(f * theta) * 1 / Math.sqrt(1 - product * product);
- for (var i = 0; i < 4; i++) {
- quat.push(fromQ[i] * (Math.cos(f * theta) - product * w) + toQ[i] * w);
- }
- }
- return quat;
- }
- // scalex/y/z -> scale
- function typeTo2D(type) {
- return type.replace(/[xy]/, '');
- }
- // scalex/y/z -> scale3d
- function typeTo3D(type) {
- return type.replace(/(x|y|z|3d)?$/, '3d');
- }
- var isMatrixOrPerspective = function isMatrixOrPerspective(lt, rt) {
- return lt === 'perspective' && rt === 'perspective' || (lt === 'matrix' || lt === 'matrix3d') && (rt === 'matrix' || rt === 'matrix3d');
- };
- function mergeTransforms(left, right, target) {
- var flipResults = false;
- // padding empty transform, eg. merge 'scale(10)' with 'none' -> scale(1)
- if (!left.length || !right.length) {
- if (!left.length) {
- flipResults = true;
- left = right;
- right = [];
- }
- var _loop = function _loop() {
- var _left$i = left[i],
- type = _left$i.t,
- args = _left$i.d;
- // none -> scale(1)/translateX(0)
- var defaultValue = type.substring(0, 5) === 'scale' ? 1 : 0;
- right.push({
- t: type,
- d: args.map(function (arg) {
- if (typeof arg === 'number') {
- return getOrCreateUnitValue(defaultValue);
- }
- return getOrCreateUnitValue(defaultValue, arg.unit);
- // {
- // unit: arg.unit,
- // value: defaultValue,
- // };
- })
- });
- };
- for (var i = 0; i < left.length; i++) {
- _loop();
- }
- }
- var leftResult = [];
- var rightResult = [];
- var types = [];
- // merge matrix() with matrix3d()
- if (left.length !== right.length) {
- var merged = mergeMatrices(left, right);
- // @ts-ignore
- leftResult = [merged[0]];
- // @ts-ignore
- rightResult = [merged[1]];
- types = [['matrix', [merged[2]]]];
- } else {
- for (var _i3 = 0; _i3 < left.length; _i3++) {
- var leftType = left[_i3].t;
- var rightType = right[_i3].t;
- var leftArgs = left[_i3].d;
- var rightArgs = right[_i3].d;
- var leftFunctionData = transformFunctions[leftType];
- var rightFunctionData = transformFunctions[rightType];
- var type = void 0;
- if (isMatrixOrPerspective(leftType, rightType)) {
- var _merged = mergeMatrices([left[_i3]], [right[_i3]]);
- // @ts-ignore
- leftResult.push(_merged[0]);
- // @ts-ignore
- rightResult.push(_merged[1]);
- types.push(['matrix', [_merged[2]]]);
- continue;
- } else if (leftType === rightType) {
- type = leftType;
- } else if (leftFunctionData[2] && rightFunctionData[2] && typeTo2D(leftType) === typeTo2D(rightType)) {
- type = typeTo2D(leftType);
- // @ts-ignore
- leftArgs = leftFunctionData[2](leftArgs);
- // @ts-ignore
- rightArgs = rightFunctionData[2](rightArgs);
- } else if (leftFunctionData[1] && rightFunctionData[1] && typeTo3D(leftType) === typeTo3D(rightType)) {
- type = typeTo3D(leftType);
- // @ts-ignore
- leftArgs = leftFunctionData[1](leftArgs);
- // @ts-ignore
- rightArgs = rightFunctionData[1](rightArgs);
- } else {
- var _merged2 = mergeMatrices(left, right);
- // @ts-ignore
- leftResult = [_merged2[0]];
- // @ts-ignore
- rightResult = [_merged2[1]];
- types = [['matrix', [_merged2[2]]]];
- break;
- }
- var leftArgsCopy = [];
- var rightArgsCopy = [];
- var stringConversions = [];
- for (var j = 0; j < leftArgs.length; j++) {
- // const merge = leftArgs[j].unit === UnitType.kNumber ? mergeDimensions : mergeDimensions;
- var _merged3 = mergeDimensions(leftArgs[j], rightArgs[j], target, false, j);
- leftArgsCopy[j] = _merged3[0];
- rightArgsCopy[j] = _merged3[1];
- stringConversions.push(_merged3[2]);
- }
- leftResult.push(leftArgsCopy);
- rightResult.push(rightArgsCopy);
- types.push([type, stringConversions]);
- }
- }
- if (flipResults) {
- var tmp = leftResult;
- leftResult = rightResult;
- rightResult = tmp;
- }
- return [leftResult, rightResult, function (list) {
- return list.map(function (args, i) {
- var stringifiedArgs = args.map(function (arg, j) {
- return types[i][1][j](arg);
- }).join(',');
- if (types[i][0] === 'matrix' && stringifiedArgs.split(',').length === 16) {
- types[i][0] = 'matrix3d';
- }
- if (types[i][0] === 'matrix3d' && stringifiedArgs.split(',').length === 6) {
- types[i][0] = 'matrix';
- }
- return types[i][0] + '(' + stringifiedArgs + ')';
- }).join(' ');
- }];
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
- * eg. 'center' 'top left' '50px 50px'
- */
- var parseTransformOrigin = memoize(function (value) {
- if (isString(value)) {
- if (value === 'text-anchor') {
- return [getOrCreateUnitValue(0, 'px'), getOrCreateUnitValue(0, 'px')];
- }
- var values = value.split(' ');
- if (values.length === 1) {
- if (values[0] === 'top' || values[0] === 'bottom') {
- // 'top' -> 'center top'
- values[1] = values[0];
- values[0] = 'center';
- } else {
- // '50px' -> '50px center'
- values[1] = 'center';
- }
- }
- if (values.length !== 2) {
- return null;
- }
- // eg. center bottom
- return [parseLengthOrPercentage(convertKeyword2Percent(values[0])), parseLengthOrPercentage(convertKeyword2Percent(values[1]))];
- } else {
- return [getOrCreateUnitValue(value[0] || 0, 'px'), getOrCreateUnitValue(value[1] || 0, 'px')];
- }
- });
- function convertKeyword2Percent(keyword) {
- if (keyword === 'center') {
- return '50%';
- } else if (keyword === 'left' || keyword === 'top') {
- return '0';
- } else if (keyword === 'right' || keyword === 'bottom') {
- return '100%';
- }
- return keyword;
- }
- var CSSPropertyAngle = /*#__PURE__*/function () {
- function CSSPropertyAngle() {
- this.parser = parseAngle;
- this.parserWithCSSDisabled = null;
- this.mixer = mergeNumbers;
- }
- var _proto = CSSPropertyAngle.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- return convertAngleUnit(parsed);
- };
- return CSSPropertyAngle;
- }();
- /**
- * clipPath / textPath / offsetPath
- */
- var CSSPropertyClipPath = /*#__PURE__*/function () {
- function CSSPropertyClipPath() {}
- var _proto = CSSPropertyClipPath.prototype;
- _proto.calculator = function calculator(name, oldPath, newPath, object) {
- // unset
- if (newPath instanceof CSSKeywordValue) {
- newPath = null;
- }
- runtime.sceneGraphService.updateDisplayObjectDependency(name, oldPath, newPath, object);
- if (name === 'clipPath') {
- // should affect children
- object.forEach(function (leaf) {
- if (leaf.childNodes.length === 0) {
- runtime.sceneGraphService.dirtifyToRoot(leaf);
- }
- });
- }
- return newPath;
- };
- return CSSPropertyClipPath;
- }();
- var CSSPropertyColor = /*#__PURE__*/function () {
- function CSSPropertyColor() {
- this.parser = parseColor;
- this.parserWithCSSDisabled = parseColor;
- this.mixer = mergeColors;
- }
- var _proto = CSSPropertyColor.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- if (parsed instanceof CSSKeywordValue) {
- // 'unset' 'none'
- return parsed.value === 'none' ? noneColor : transparentColor;
- }
- return parsed;
- };
- return CSSPropertyColor;
- }();
- var CSSPropertyFilter = /*#__PURE__*/function () {
- function CSSPropertyFilter() {
- this.parser = parseFilter;
- }
- var _proto = CSSPropertyFilter.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed) {
- // unset or none
- if (parsed instanceof CSSKeywordValue) {
- return [];
- }
- return parsed;
- };
- return CSSPropertyFilter;
- }();
- function getFontSize(object) {
- var fontSize = object.parsedStyle.fontSize;
- return isNil(fontSize) ? null : fontSize;
- }
- /**
- * <length> & <percentage>
- */
- var CSSPropertyLengthOrPercentage = /*#__PURE__*/function () {
- function CSSPropertyLengthOrPercentage() {
- this.parser = parseLengthOrPercentage;
- this.parserWithCSSDisabled = null;
- this.mixer = mergeNumbers;
- }
- var _proto = CSSPropertyLengthOrPercentage.prototype;
- /**
- * according to parent's bounds
- *
- * @example
- * CSS.percent(50) -> CSS.px(0.5 * parent.width)
- */
- _proto.calculator = function calculator(name, oldParsed, computed, object, registry) {
- if (isNumber(computed)) {
- return computed;
- }
- if (CSSUnitValue.isRelativeUnit(computed.unit)) {
- if (computed.unit === UnitType.kPercentage) {
- // TODO: merge dimensions
- return 0;
- } else if (computed.unit === UnitType.kEms) {
- if (object.parentNode) {
- var fontSize = getFontSize(object.parentNode);
- if (fontSize) {
- fontSize *= computed.value;
- return fontSize;
- } else {
- registry.addUnresolveProperty(object, name);
- }
- } else {
- registry.addUnresolveProperty(object, name);
- }
- return 0;
- } else if (computed.unit === UnitType.kRems) {
- var _object$ownerDocument;
- if (object === null || object === void 0 ? void 0 : (_object$ownerDocument = object.ownerDocument) === null || _object$ownerDocument === void 0 ? void 0 : _object$ownerDocument.documentElement) {
- var _fontSize = getFontSize(object.ownerDocument.documentElement);
- if (_fontSize) {
- _fontSize *= computed.value;
- return _fontSize;
- } else {
- registry.addUnresolveProperty(object, name);
- }
- } else {
- registry.addUnresolveProperty(object, name);
- }
- return 0;
- }
- } else {
- // remove listener if exists
- // registry.unregisterParentGeometryBoundsChangedHandler(object, name);
- // return absolute value
- return computed.value;
- }
- };
- return CSSPropertyLengthOrPercentage;
- }();
- /**
- * format to Tuple2<CSSUnitValue>
- *
- * @example
- * rect.style.lineDash = 10;
- * rect.style.lineDash = [10, 10];
- * rect.style.lineDash = '10 10';
- */
- var CSSPropertyLengthOrPercentage12 = /*#__PURE__*/function () {
- function CSSPropertyLengthOrPercentage12() {
- this.mixer = mergeNumberLists;
- }
- var _proto = CSSPropertyLengthOrPercentage12.prototype;
- _proto.parser = function parser(radius) {
- var parsed = parseDimensionArray(isNumber(radius) ? [radius] : radius);
- var formatted;
- if (parsed.length === 1) {
- formatted = [parsed[0], parsed[0]];
- } else {
- formatted = [parsed[0], parsed[1]];
- }
- return formatted;
- };
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.map(function (c) {
- return c.value;
- });
- };
- return CSSPropertyLengthOrPercentage12;
- }();
- /**
- * used in rounded rect
- *
- * @example
- * rect.style.radius = 10;
- * rect.style.radius = '10 10';
- * rect.style.radius = '10 10 10 10';
- */
- var CSSPropertyLengthOrPercentage14 = /*#__PURE__*/function () {
- function CSSPropertyLengthOrPercentage14() {
- this.mixer = mergeNumberLists;
- }
- var _proto = CSSPropertyLengthOrPercentage14.prototype;
- _proto.parser = function parser(radius) {
- var parsed = parseDimensionArray(isNumber(radius) ? [radius] : radius);
- var formatted;
- // format to Tuple<CSSUnitValue>
- if (parsed.length === 1) {
- formatted = [parsed[0], parsed[0], parsed[0], parsed[0]];
- } else if (parsed.length === 2) {
- formatted = [parsed[0], parsed[1], parsed[0], parsed[1]];
- } else if (parsed.length === 3) {
- formatted = [parsed[0], parsed[1], parsed[2], parsed[1]];
- } else {
- formatted = [parsed[0], parsed[1], parsed[2], parsed[3]];
- }
- return formatted;
- };
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.map(function (c) {
- return c.value;
- });
- };
- return CSSPropertyLengthOrPercentage14;
- }();
- /**
- * local position
- */
- var CSSPropertyLocalPosition = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
- _inheritsLoose(CSSPropertyLocalPosition, _CSSPropertyLengthOrP);
- function CSSPropertyLocalPosition() {
- return _CSSPropertyLengthOrP.apply(this, arguments) || this;
- }
- var _proto = CSSPropertyLocalPosition.prototype;
- /**
- * update local position
- */
- _proto.postProcessor = function postProcessor(object, attributes) {
- var x;
- var y;
- var z;
- switch (object.nodeName) {
- case Shape.CIRCLE:
- case Shape.ELLIPSE:
- var _object$parsedStyle = object.parsedStyle,
- cx = _object$parsedStyle.cx,
- cy = _object$parsedStyle.cy,
- cz = _object$parsedStyle.cz;
- if (!isNil(cx)) {
- x = cx;
- }
- if (!isNil(cy)) {
- y = cy;
- }
- if (!isNil(cz)) {
- z = cz;
- }
- break;
- case Shape.LINE:
- var _object$parsedStyle2 = object.parsedStyle,
- x1 = _object$parsedStyle2.x1,
- x2 = _object$parsedStyle2.x2,
- y1 = _object$parsedStyle2.y1,
- y2 = _object$parsedStyle2.y2;
- var minX = Math.min(x1, x2);
- var minY = Math.min(y1, y2);
- x = minX;
- y = minY;
- z = 0;
- break;
- case Shape.RECT:
- case Shape.IMAGE:
- case Shape.GROUP:
- case Shape.HTML:
- case Shape.TEXT:
- case Shape.MESH:
- if (!isNil(object.parsedStyle.x)) {
- x = object.parsedStyle.x;
- }
- if (!isNil(object.parsedStyle.y)) {
- y = object.parsedStyle.y;
- }
- if (!isNil(object.parsedStyle.z)) {
- z = object.parsedStyle.z;
- }
- break;
- }
- if (object.nodeName !== Shape.PATH && object.nodeName !== Shape.POLYLINE && object.nodeName !== Shape.POLYGON) {
- object.parsedStyle.defX = x || 0;
- object.parsedStyle.defY = y || 0;
- }
- var needResetLocalPosition = !isNil(x) || !isNil(y) || !isNil(z);
- // only if `transform` won't be processed later
- if (needResetLocalPosition && attributes.indexOf('transform') === -1) {
- // account for current transform if needed
- var transform = object.parsedStyle.transform;
- if (transform && transform.length) {
- parsedTransformToMat4(transform, object);
- } else {
- var _object$getLocalPosit = object.getLocalPosition(),
- ox = _object$getLocalPosit[0],
- oy = _object$getLocalPosit[1],
- oz = _object$getLocalPosit[2];
- object.setLocalPosition(isNil(x) ? ox : x, isNil(y) ? oy : y, isNil(z) ? oz : z);
- }
- }
- };
- return CSSPropertyLocalPosition;
- }(CSSPropertyLengthOrPercentage);
- var CSSPropertyMarker = /*#__PURE__*/function () {
- function CSSPropertyMarker() {}
- var _proto = CSSPropertyMarker.prototype;
- _proto.calculator = function calculator(name, oldMarker, newMarker, object) {
- var _newMarker;
- // unset
- if (newMarker instanceof CSSKeywordValue) {
- newMarker = null;
- }
- var cloned = (_newMarker = newMarker) === null || _newMarker === void 0 ? void 0 : _newMarker.cloneNode(true);
- if (cloned) {
- // FIXME: SVG should not inherit parent's style, add a flag here
- cloned.style.isMarker = true;
- }
- return cloned;
- };
- return CSSPropertyMarker;
- }();
- var CSSPropertyNumber = /*#__PURE__*/function () {
- function CSSPropertyNumber() {
- this.mixer = mergeNumbers;
- this.parser = parseNumber;
- this.parserWithCSSDisabled = null;
- }
- var _proto = CSSPropertyNumber.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.value;
- };
- return CSSPropertyNumber;
- }();
- var CSSPropertyOffsetDistance = /*#__PURE__*/function () {
- function CSSPropertyOffsetDistance() {
- this.parser = parseNumber;
- this.parserWithCSSDisabled = null;
- this.mixer = clampedMergeNumbers(0, 1);
- }
- var _proto = CSSPropertyOffsetDistance.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.value;
- };
- _proto.postProcessor = function postProcessor(object) {
- var _object$parsedStyle = object.parsedStyle,
- offsetPath = _object$parsedStyle.offsetPath,
- offsetDistance = _object$parsedStyle.offsetDistance;
- if (!offsetPath) {
- return;
- }
- var nodeName = offsetPath.nodeName;
- if (nodeName === Shape.LINE || nodeName === Shape.PATH || nodeName === Shape.POLYLINE) {
- // set position in world space
- var point = offsetPath.getPoint(offsetDistance);
- if (point) {
- object.parsedStyle.defX = point.x;
- object.parsedStyle.defY = point.y;
- object.setLocalPosition(point.x, point.y);
- }
- }
- };
- return CSSPropertyOffsetDistance;
- }();
- /**
- * opacity
- */
- var CSSPropertyOpacity = /*#__PURE__*/function () {
- function CSSPropertyOpacity() {
- this.parser = parseNumber;
- this.parserWithCSSDisabled = null;
- this.mixer = clampedMergeNumbers(0, 1);
- }
- var _proto = CSSPropertyOpacity.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.value;
- };
- return CSSPropertyOpacity;
- }();
- /**
- * Axis-Aligned Bounding Box
- * 为了便于后续 Frustum Culling,通过查找表定义 p-vertex 和 n-vertex
- * @see https://github.com/antvis/GWebGPUEngine/issues/3
- */
- var AABB = /*#__PURE__*/function () {
- function AABB() {
- this.center = [0, 0, 0];
- this.halfExtents = [0, 0, 0];
- this.min = [0, 0, 0];
- this.max = [0, 0, 0];
- }
- AABB.isEmpty = function isEmpty(aabb) {
- return !aabb || aabb.halfExtents[0] === 0 && aabb.halfExtents[1] === 0 && aabb.halfExtents[2] === 0;
- };
- var _proto = AABB.prototype;
- // center: vec3 = vec3.create();
- // halfExtents: vec3 = vec3.create();
- // min: vec3 = vec3.create();
- // max: vec3 = vec3.create();
- _proto.update = function update(center, halfExtents) {
- copyVec3(this.center, center);
- copyVec3(this.halfExtents, halfExtents);
- subVec3(this.min, this.center, this.halfExtents);
- addVec3(this.max, this.center, this.halfExtents);
- // vec3.copy(this.center, center);
- // vec3.copy(this.halfExtents, halfExtents);
- // vec3.sub(this.min, this.center, this.halfExtents);
- // vec3.add(this.max, this.center, this.halfExtents);
- };
- _proto.setMinMax = function setMinMax(min, max) {
- // vec3.add(this.center, max, min);
- // vec3.scale(this.center, this.center, 0.5);
- // vec3.sub(this.halfExtents, max, min);
- // vec3.scale(this.halfExtents, this.halfExtents, 0.5);
- // vec3.copy(this.min, min);
- // vec3.copy(this.max, max);
- addVec3(this.center, max, min);
- scaleVec3(this.center, this.center, 0.5);
- subVec3(this.halfExtents, max, min);
- scaleVec3(this.halfExtents, this.halfExtents, 0.5);
- copyVec3(this.min, min);
- copyVec3(this.max, max);
- };
- _proto.getMin = function getMin() {
- return this.min;
- };
- _proto.getMax = function getMax() {
- return this.max;
- };
- _proto.add = function add(aabb) {
- if (AABB.isEmpty(aabb)) {
- return;
- }
- if (AABB.isEmpty(this)) {
- this.setMinMax(aabb.getMin(), aabb.getMax());
- return;
- }
- var tc = this.center;
- var tcx = tc[0];
- var tcy = tc[1];
- var tcz = tc[2];
- var th = this.halfExtents;
- var thx = th[0];
- var thy = th[1];
- var thz = th[2];
- var tminx = tcx - thx;
- var tmaxx = tcx + thx;
- var tminy = tcy - thy;
- var tmaxy = tcy + thy;
- var tminz = tcz - thz;
- var tmaxz = tcz + thz;
- var oc = aabb.center;
- var ocx = oc[0];
- var ocy = oc[1];
- var ocz = oc[2];
- var oh = aabb.halfExtents;
- var ohx = oh[0];
- var ohy = oh[1];
- var ohz = oh[2];
- var ominx = ocx - ohx;
- var omaxx = ocx + ohx;
- var ominy = ocy - ohy;
- var omaxy = ocy + ohy;
- var ominz = ocz - ohz;
- var omaxz = ocz + ohz;
- if (ominx < tminx) {
- tminx = ominx;
- }
- if (omaxx > tmaxx) {
- tmaxx = omaxx;
- }
- if (ominy < tminy) {
- tminy = ominy;
- }
- if (omaxy > tmaxy) {
- tmaxy = omaxy;
- }
- if (ominz < tminz) {
- tminz = ominz;
- }
- if (omaxz > tmaxz) {
- tmaxz = omaxz;
- }
- tc[0] = (tminx + tmaxx) * 0.5;
- tc[1] = (tminy + tmaxy) * 0.5;
- tc[2] = (tminz + tmaxz) * 0.5;
- th[0] = (tmaxx - tminx) * 0.5;
- th[1] = (tmaxy - tminy) * 0.5;
- th[2] = (tmaxz - tminz) * 0.5;
- this.min[0] = tminx;
- this.min[1] = tminy;
- this.min[2] = tminz;
- this.max[0] = tmaxx;
- this.max[1] = tmaxy;
- this.max[2] = tmaxz;
- };
- _proto.setFromTransformedAABB = function setFromTransformedAABB(aabb, m) {
- var bc = this.center;
- var br = this.halfExtents;
- var ac = aabb.center;
- var ar = aabb.halfExtents;
- var mx0 = m[0];
- var mx1 = m[4];
- var mx2 = m[8];
- var my0 = m[1];
- var my1 = m[5];
- var my2 = m[9];
- var mz0 = m[2];
- var mz1 = m[6];
- var mz2 = m[10];
- var mx0a = Math.abs(mx0);
- var mx1a = Math.abs(mx1);
- var mx2a = Math.abs(mx2);
- var my0a = Math.abs(my0);
- var my1a = Math.abs(my1);
- var my2a = Math.abs(my2);
- var mz0a = Math.abs(mz0);
- var mz1a = Math.abs(mz1);
- var mz2a = Math.abs(mz2);
- bc[0] = m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2];
- bc[1] = m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2];
- bc[2] = m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2];
- // vec3.set(
- // bc,
- // m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
- // m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
- // m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2],
- // );
- br[0] = mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2];
- br[1] = my0a * ar[0] + my1a * ar[1] + my2a * ar[2];
- br[2] = mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2];
- // vec3.set(
- // br,
- // mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
- // my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
- // mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2],
- // );
- // this.min = vec3.sub(this.min, bc, br);
- // this.max = vec3.add(this.max, bc, br);
- subVec3(this.min, bc, br);
- addVec3(this.max, bc, br);
- };
- _proto.intersects = function intersects(aabb) {
- var aMax = this.getMax();
- var aMin = this.getMin();
- var bMax = aabb.getMax();
- var bMin = aabb.getMin();
- 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];
- };
- _proto.intersection = function intersection(aabb) {
- if (!this.intersects(aabb)) {
- return null;
- }
- var intersection = new AABB();
- // const min = vec3.max(vec3.create(), this.getMin(), aabb.getMin());
- // const max = vec3.min(vec3.create(), this.getMax(), aabb.getMax());
- var min = maxVec3([0, 0, 0], this.getMin(), aabb.getMin());
- var max = minVec3([0, 0, 0], this.getMax(), aabb.getMax());
- intersection.setMinMax(min, max);
- return intersection;
- }
- // containsPoint(point: vec3) {
- // const min = this.getMin();
- // const max = this.getMax();
- // return !(
- // point[0] < min[0] ||
- // point[0] > max[0] ||
- // point[1] < min[1] ||
- // point[1] > max[1] ||
- // point[2] < min[2] ||
- // point[2] > max[2]
- // );
- // }
- /**
- * get n-vertex
- * @param plane plane of CullingVolume
- */;
- _proto.getNegativeFarPoint = function getNegativeFarPoint(plane) {
- if (plane.pnVertexFlag === 0x111) {
- return copyVec3([0, 0, 0], this.min);
- // return vec3.copy(vec3.create(), this.min);
- } else if (plane.pnVertexFlag === 0x110) {
- return [this.min[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x101) {
- return [this.min[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x100) {
- return [this.min[0], this.max[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x011) {
- return [this.max[0], this.min[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x010) {
- return [this.max[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x001) {
- return [this.max[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
- } else {
- return [this.max[0], this.max[1], this.max[2]];
- // return vec3.fromValues(this.max[0], this.max[1], this.max[2]);
- }
- }
- /**
- * get p-vertex
- * @param plane plane of CullingVolume
- */;
- _proto.getPositiveFarPoint = function getPositiveFarPoint(plane) {
- if (plane.pnVertexFlag === 0x111) {
- return copyVec3([0, 0, 0], this.max);
- // return vec3.copy(vec3.create(), this.max);
- } else if (plane.pnVertexFlag === 0x110) {
- return [this.max[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x101) {
- return [this.max[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x100) {
- return [this.max[0], this.min[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x011) {
- return [this.min[0], this.max[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x010) {
- return [this.min[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x001) {
- return [this.min[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
- } else {
- return [this.min[0], this.min[1], this.min[2]];
- // return vec3.fromValues(this.min[0], this.min[1], this.min[2]);
- }
- };
- return AABB;
- }();
- var Plane = /*#__PURE__*/function () {
- function Plane(distance, normal) {
- this.distance = void 0;
- this.normal = void 0;
- /**
- * lookup table for p-vertex & n-vertex when doing frustum culling
- */
- this.pnVertexFlag = void 0;
- this.distance = distance || 0;
- this.normal = normal || vec3.fromValues(0, 1, 0);
- this.updatePNVertexFlag();
- }
- var _proto = Plane.prototype;
- _proto.updatePNVertexFlag = function updatePNVertexFlag() {
- this.pnVertexFlag = (Number(this.normal[0] >= 0) << 8) + (Number(this.normal[1] >= 0) << 4) + Number(this.normal[2] >= 0);
- };
- _proto.distanceToPoint = function distanceToPoint(point) {
- return vec3.dot(point, this.normal) - this.distance;
- };
- _proto.normalize = function normalize() {
- var invLen = 1 / vec3.len(this.normal);
- vec3.scale(this.normal, this.normal, invLen);
- this.distance *= invLen;
- };
- _proto.intersectsLine = function intersectsLine(start, end, point) {
- var d0 = this.distanceToPoint(start);
- var d1 = this.distanceToPoint(end);
- var t = d0 / (d0 - d1);
- var intersects = t >= 0 && t <= 1;
- if (intersects && point) {
- vec3.lerp(point, start, end, t);
- }
- return intersects;
- };
- return Plane;
- }();
- var Mask;
- (function (Mask) {
- Mask[Mask["OUTSIDE"] = 4294967295] = "OUTSIDE";
- Mask[Mask["INSIDE"] = 0] = "INSIDE";
- Mask[Mask["INDETERMINATE"] = 2147483647] = "INDETERMINATE";
- })(Mask || (Mask = {}));
- var Frustum = /*#__PURE__*/function () {
- function Frustum(planes) {
- this.planes = [];
- if (planes) {
- this.planes = planes;
- } else {
- for (var i = 0; i < 6; i++) {
- this.planes.push(new Plane());
- }
- }
- }
- /**
- * extract 6 planes from projectionMatrix
- * @see http://www8.cs.umu.se/kurser/5DV051/HT12/lab/plane_extraction.pdf
- */
- var _proto = Frustum.prototype;
- _proto.extractFromVPMatrix = function extractFromVPMatrix(projectionMatrix) {
- // @ts-ignore
- var m0 = projectionMatrix[0],
- m1 = projectionMatrix[1],
- m2 = projectionMatrix[2],
- m3 = projectionMatrix[3],
- m4 = projectionMatrix[4],
- m5 = projectionMatrix[5],
- m6 = projectionMatrix[6],
- m7 = projectionMatrix[7],
- m8 = projectionMatrix[8],
- m9 = projectionMatrix[9],
- m10 = projectionMatrix[10],
- m11 = projectionMatrix[11],
- m12 = projectionMatrix[12],
- m13 = projectionMatrix[13],
- m14 = projectionMatrix[14],
- m15 = projectionMatrix[15];
- // right
- vec3.set(this.planes[0].normal, m3 - m0, m7 - m4, m11 - m8);
- this.planes[0].distance = m15 - m12;
- // left
- vec3.set(this.planes[1].normal, m3 + m0, m7 + m4, m11 + m8);
- this.planes[1].distance = m15 + m12;
- // bottom
- vec3.set(this.planes[2].normal, m3 + m1, m7 + m5, m11 + m9);
- this.planes[2].distance = m15 + m13;
- // top
- vec3.set(this.planes[3].normal, m3 - m1, m7 - m5, m11 - m9);
- this.planes[3].distance = m15 - m13;
- // far
- vec3.set(this.planes[4].normal, m3 - m2, m7 - m6, m11 - m10);
- this.planes[4].distance = m15 - m14;
- // near
- vec3.set(this.planes[5].normal, m3 + m2, m7 + m6, m11 + m10);
- this.planes[5].distance = m15 + m14;
- this.planes.forEach(function (plane) {
- plane.normalize();
- plane.updatePNVertexFlag();
- });
- };
- return Frustum;
- }();
- var Point = /*#__PURE__*/function () {
- function Point(x, y) {
- if (x === void 0) {
- x = 0;
- }
- if (y === void 0) {
- y = 0;
- }
- this.x = 0;
- this.y = 0;
- this.x = x;
- this.y = y;
- }
- var _proto = Point.prototype;
- _proto.clone = function clone() {
- return new Point(this.x, this.y);
- };
- _proto.copyFrom = function copyFrom(p) {
- this.x = p.x;
- this.y = p.y;
- };
- return Point;
- }();
- var Rectangle = /*#__PURE__*/function () {
- function Rectangle(x, y, width, height) {
- this.x = void 0;
- this.y = void 0;
- this.width = void 0;
- this.height = void 0;
- this.left = void 0;
- this.right = void 0;
- this.top = void 0;
- this.bottom = void 0;
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- this.left = x;
- this.right = x + width;
- this.top = y;
- this.bottom = y + height;
- }
- var _proto = Rectangle.prototype;
- _proto.toJSON = function toJSON() {};
- return Rectangle;
- }();
- var CSSPropertyPath = /*#__PURE__*/function () {
- function CSSPropertyPath() {
- /**
- * path2Curve
- */
- this.parser = parsePath;
- this.parserWithCSSDisabled = parsePath;
- this.mixer = mergePaths;
- }
- var _proto = CSSPropertyPath.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed) {
- // unset
- if (parsed instanceof CSSKeywordValue && parsed.value === 'unset') {
- return {
- absolutePath: [],
- hasArc: false,
- segments: [],
- polygons: [],
- polylines: [],
- curve: null,
- totalLength: 0,
- rect: new Rectangle(0, 0, 0, 0)
- };
- }
- return parsed;
- };
- /**
- * update local position
- */
- _proto.postProcessor = function postProcessor(object, attributes) {
- if (object.nodeName === Shape.PATH && attributes.indexOf('transform') === -1) {
- var _object$parsedStyle = object.parsedStyle,
- _object$parsedStyle$d = _object$parsedStyle.defX,
- defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
- _object$parsedStyle$d2 = _object$parsedStyle.defY,
- defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
- object.setLocalPosition(defX, defY);
- }
- };
- return CSSPropertyPath;
- }();
- var CSSPropertyPoints = /*#__PURE__*/function () {
- function CSSPropertyPoints() {
- this.parser = parsePoints;
- this.mixer = mergePoints;
- }
- var _proto = CSSPropertyPoints.prototype;
- /**
- * update local position
- */
- _proto.postProcessor = function postProcessor(object, attributes) {
- if ((object.nodeName === Shape.POLYGON || object.nodeName === Shape.POLYLINE) && attributes.indexOf('transform') === -1) {
- var _object$parsedStyle = object.parsedStyle,
- defX = _object$parsedStyle.defX,
- defY = _object$parsedStyle.defY;
- object.setLocalPosition(defX, defY);
- }
- };
- return CSSPropertyPoints;
- }();
- var CSSPropertyShadowBlur = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
- _inheritsLoose(CSSPropertyShadowBlur, _CSSPropertyLengthOrP);
- function CSSPropertyShadowBlur() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _CSSPropertyLengthOrP.call.apply(_CSSPropertyLengthOrP, [this].concat(args)) || this;
- _this.mixer = clampedMergeNumbers(0, Infinity);
- return _this;
- }
- return CSSPropertyShadowBlur;
- }(CSSPropertyLengthOrPercentage);
- var CSSPropertyText = /*#__PURE__*/function () {
- function CSSPropertyText() {}
- var _proto = CSSPropertyText.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- if (parsed instanceof CSSKeywordValue) {
- if (parsed.value === 'unset') {
- return '';
- } else {
- return parsed.value;
- }
- }
- // allow number as valid text content
- return "" + parsed;
- };
- _proto.postProcessor = function postProcessor(object) {
- object.nodeValue = "" + object.parsedStyle.text || '';
- };
- return CSSPropertyText;
- }();
- /**
- * it must transform after text get parsed
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform
- */
- var CSSPropertyTextTransform = /*#__PURE__*/function () {
- function CSSPropertyTextTransform() {}
- var _proto = CSSPropertyTextTransform.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- var rawText = object.getAttribute('text');
- if (rawText) {
- var transformedText = rawText;
- if (parsed.value === 'capitalize') {
- transformedText = rawText.charAt(0).toUpperCase() + rawText.slice(1);
- } else if (parsed.value === 'lowercase') {
- transformedText = rawText.toLowerCase();
- } else if (parsed.value === 'uppercase') {
- transformedText = rawText.toUpperCase();
- }
- object.parsedStyle.text = transformedText;
- }
- return parsed.value;
- };
- return CSSPropertyTextTransform;
- }();
- /**
- * @see /zh/docs/api/animation#支持变换的属性
- *
- * support the following formats like CSS Transform:
- *
- * scale
- * * scale(x, y)
- * * scaleX(x)
- * * scaleY(x)
- * * scaleZ(z)
- * * scale3d(x, y, z)
- *
- * translate (unit: none, px, %(relative to its bounds))
- * * translate(x, y) eg. translate(0, 0) translate(0, 30px) translate(100%, 100%)
- * * translateX(0)
- * * translateY(0)
- * * translateZ(0)
- * * translate3d(0, 0, 0)
- *
- * rotate (unit: deg rad turn)
- * * rotate(0.5turn) rotate(30deg) rotate(1rad)
- *
- * none
- *
- * unsupported for now:
- * * calc() eg. translate(calc(100% + 10px))
- * * matrix/matrix3d()
- * * skew/skewX/skewY
- * * perspective
- */
- var CSSPropertyTransform = /*#__PURE__*/function () {
- function CSSPropertyTransform() {
- this.parser = parseTransform;
- this.parserWithCSSDisabled = parseTransform;
- this.mixer = mergeTransforms;
- }
- var _proto = CSSPropertyTransform.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- // 'none'
- if (parsed instanceof CSSKeywordValue) {
- return [];
- }
- return parsed;
- };
- _proto.postProcessor = function postProcessor(object) {
- var transform = object.parsedStyle.transform;
- parsedTransformToMat4(transform, object);
- };
- return CSSPropertyTransform;
- }();
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
- * @example
- * [10px, 10px] [10%, 10%]
- */
- var CSSPropertyTransformOrigin = function CSSPropertyTransformOrigin() {
- this.parser = parseTransformOrigin;
- };
- /**
- * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
- */
- var Strategy;
- (function (Strategy) {
- Strategy[Strategy["Standard"] = 0] = "Standard";
- })(Strategy || (Strategy = {}));
- var SortReason;
- (function (SortReason) {
- SortReason[SortReason["ADDED"] = 0] = "ADDED";
- SortReason[SortReason["REMOVED"] = 1] = "REMOVED";
- SortReason[SortReason["Z_INDEX_CHANGED"] = 2] = "Z_INDEX_CHANGED";
- })(SortReason || (SortReason = {}));
- var CSSPropertyZIndex = /*#__PURE__*/function () {
- function CSSPropertyZIndex() {
- this.parser = parseNumber;
- }
- var _proto = CSSPropertyZIndex.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed, object) {
- return computed.value;
- };
- _proto.postProcessor = function postProcessor(object) {
- if (object.parentNode) {
- var parentEntity = object.parentNode;
- var parentRenderable = parentEntity.renderable;
- var parentSortable = parentEntity.sortable;
- if (parentRenderable) {
- parentRenderable.dirty = true;
- }
- // need re-sort on parent
- if (parentSortable) {
- parentSortable.dirty = true;
- parentSortable.dirtyReason = SortReason.Z_INDEX_CHANGED;
- }
- }
- };
- return CSSPropertyZIndex;
- }();
- /**
- * canvas.customElements
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
- */
- var CustomElementRegistry = /*#__PURE__*/function () {
- function CustomElementRegistry() {
- this.registry = {};
- this.define(Shape.CIRCLE, Circle);
- this.define(Shape.ELLIPSE, Ellipse);
- this.define(Shape.RECT, Rect);
- this.define(Shape.IMAGE, Image);
- this.define(Shape.LINE, Line);
- this.define(Shape.GROUP, Group);
- this.define(Shape.PATH, Path);
- this.define(Shape.POLYGON, Polygon);
- this.define(Shape.POLYLINE, Polyline);
- this.define(Shape.TEXT, Text);
- this.define(Shape.HTML, HTML);
- }
- var _proto = CustomElementRegistry.prototype;
- _proto.define = function define(name, constructor) {
- this.registry[name] = constructor;
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/get
- */;
- _proto.get = function get(name) {
- return this.registry[name];
- };
- return CustomElementRegistry;
- }();
- function isFederatedEvent(value) {
- return !!value.type;
- }
- /**
- * An DOM-compatible synthetic event implementation that is "forwarded" on behalf of an original
- * FederatedEvent or native {@link https://dom.spec.whatwg.org/#event Event}.
- */
- var FederatedEvent = /*#__PURE__*/function () {
- /**
- * The event boundary which manages this event. Propagation can only occur
- * within the boundary's jurisdiction.
- */
- function FederatedEvent(manager) {
- /**
- * The type of event, supports the following:
- * * pointerdown
- * * touchstart
- * * mousedown
- * * rightdown
- * * ...
- */
- this.type = void 0;
- /**
- * The propagation phase.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
- */
- this.eventPhase = FederatedEvent.prototype.NONE;
- /**
- * can be used to implement event delegation
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
- */
- this.target = void 0;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles
- */
- this.bubbles = true;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/cancelBubble
- */
- this.cancelBubble = true;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
- */
- this.cancelable = false;
- /** the event target when listeners binded */
- this.currentTarget = void 0;
- /** Flags whether the default response of the user agent was prevent through this event. */
- this.defaultPrevented = false;
- /**
- * timestamp when the event created
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/timeStamp
- */
- this.timeStamp = void 0;
- /**
- * the original event.
- */
- this.nativeEvent = void 0;
- /** The original event that caused this event, if any. */
- this.originalEvent = void 0;
- /** Flags whether propagation was stopped. */
- this.propagationStopped = false;
- /** Flags whether propagation was immediately stopped. */
- this.propagationImmediatelyStopped = false;
- this.manager = void 0;
- /** Event-specific detail */
- this.detail = void 0;
- /**
- * The coordinates of the evnet relative to the nearest DOM layer.
- * This is a non-standard property.
- */
- this.layer = new Point();
- /**
- * The coordinates of the event relative to the DOM document.
- * This is a non-standard property.
- * relative to the DOM document.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/pageX
- */
- this.page = new Point();
- /**
- * relative to Canvas, origin is left-top
- */
- this.canvas = new Point();
- /**
- * relative to Viewport, account for Camera
- */
- this.viewport = new Point();
- this.path = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
- */
- this.view = void 0;
- this.which = void 0;
- this.returnValue = void 0;
- this.srcElement = void 0;
- this.composed = false;
- this.isTrusted = void 0;
- this.NONE = 0;
- this.CAPTURING_PHASE = 1;
- this.AT_TARGET = 2;
- this.BUBBLING_PHASE = 3;
- this.manager = manager;
- }
- var _proto = FederatedEvent.prototype;
- /**
- * The propagation path for this event
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/composedPath
- *
- * So composedPath()[0] represents the original target.
- * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events#retargeting
- */
- _proto.composedPath = function composedPath() {
- if (this.manager && (!this.path || this.path[0] !== this.target)) {
- this.path = this.target ? this.manager.propagationPath(this.target) : [];
- }
- return this.path;
- }
- /**
- * @deprecated
- */;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
- */
- _proto.preventDefault = function preventDefault() {
- if (this.nativeEvent instanceof Event && this.nativeEvent.cancelable) {
- this.nativeEvent.preventDefault();
- }
- this.defaultPrevented = true;
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopImmediatePropagation
- */;
- _proto.stopImmediatePropagation = function stopImmediatePropagation() {
- this.propagationImmediatelyStopped = true;
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation
- */;
- _proto.stopPropagation = function stopPropagation() {
- this.propagationStopped = true;
- };
- /**
- * added for compatibility with DOM Event,
- * deprecated props and methods
- */
- _proto.initEvent = function initEvent() {};
- _proto.initUIEvent = function initUIEvent() {};
- _proto.clone = function clone() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _createClass(FederatedEvent, [{
- key: "name",
- get:
- /**
- * @deprecated
- */
- function get() {
- return this.type;
- }
- }, {
- key: "layerX",
- get: function get() {
- return this.layer.x;
- }
- }, {
- key: "layerY",
- get: function get() {
- return this.layer.y;
- }
- }, {
- key: "pageX",
- get: function get() {
- return this.page.x;
- }
- }, {
- key: "pageY",
- get: function get() {
- return this.page.y;
- }
- }, {
- key: "x",
- get: function get() {
- return this.canvas.x;
- }
- }, {
- key: "y",
- get: function get() {
- return this.canvas.y;
- }
- }, {
- key: "canvasX",
- get: function get() {
- return this.canvas.x;
- }
- }, {
- key: "canvasY",
- get: function get() {
- return this.canvas.y;
- }
- }, {
- key: "viewportX",
- get: function get() {
- return this.viewport.x;
- }
- }, {
- key: "viewportY",
- get: function get() {
- return this.viewport.y;
- }
- }, {
- key: "propagationPath",
- get: function get() {
- return this.composedPath();
- }
- }]);
- return FederatedEvent;
- }();
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
- *
- * @example
- const event = new CustomEvent('build', { detail: { prop1: 'xx' } });
- circle.addEventListener('build', (e) => {
- e.target; // circle
- e.detail; // { prop1: 'xx' }
- });
- circle.dispatchEvent(event);
- */
- var CustomEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose(CustomEvent, _FederatedEvent);
- // eslint-disable-next-line @typescript-eslint/ban-types
- function CustomEvent(eventName, object) {
- var _this;
- _this = _FederatedEvent.call(this, null) || this;
- _this.type = eventName;
- _this.detail = object;
- // compatible with G 3.0
- Object.assign(_assertThisInitialized(_this), object);
- return _this;
- }
- return CustomEvent;
- }(FederatedEvent);
- var DELEGATION_SPLITTER = ':';
- /**
- * Objects that can receive events and may have listeners for them.
- * eg. Element, Canvas, DisplayObject
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
- */
- var EventTarget = /*#__PURE__*/function () {
- function EventTarget() {
- /**
- * event emitter
- */
- this.emitter = new EventEmitter();
- }
- var _proto = EventTarget.prototype;
- /**
- * @deprecated
- * @alias addEventListener
- */
- _proto.on = function on(type, listener, options) {
- this.addEventListener(type, listener, options);
- return this;
- }
- /**
- * support `capture` & `once` in options
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
- */;
- _proto.addEventListener = function addEventListener(type, listener, options) {
- var capture = isBoolean(options) && options || isObject(options) && options.capture;
- var once = isObject(options) && options.once;
- var context = isFunction(listener) ? undefined : listener;
- // compatible with G 3.0
- // support using delegate name in event type, eg. 'node:click'
- var useDelegatedName = false;
- var delegatedName = '';
- if (type.indexOf(DELEGATION_SPLITTER) > -1) {
- var _type$split = type.split(DELEGATION_SPLITTER),
- name = _type$split[0],
- eventType = _type$split[1];
- type = eventType;
- delegatedName = name;
- useDelegatedName = true;
- }
- type = capture ? type + "capture" : type;
- listener = isFunction(listener) ? listener : listener.handleEvent;
- // compatible with G 3.0
- if (useDelegatedName) {
- var originListener = listener;
- listener = function listener() {
- var _args$0$target;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- if (((_args$0$target = args[0].target) === null || _args$0$target === void 0 ? void 0 : _args$0$target.name) !== delegatedName) {
- return;
- }
- // @ts-ignore
- originListener.apply(void 0, args);
- };
- }
- if (once) {
- this.emitter.once(type, listener, context);
- } else {
- this.emitter.on(type, listener, context);
- }
- return this;
- }
- /**
- * @deprecated
- * @alias removeEventListener
- */;
- _proto.off = function off(type, listener, options) {
- if (type) {
- this.removeEventListener(type, listener, options);
- } else {
- // remove all listeners
- this.removeAllEventListeners();
- }
- return this;
- };
- _proto.removeAllEventListeners = function removeAllEventListeners() {
- this.emitter.removeAllListeners();
- };
- _proto.removeEventListener = function removeEventListener(type, listener, options) {
- var _listener;
- var capture = isBoolean(options) && options || isObject(options) && options.capture;
- var context = isFunction(listener) ? undefined : listener;
- type = capture ? type + "capture" : type;
- listener = isFunction(listener) ? listener : (_listener = listener) === null || _listener === void 0 ? void 0 : _listener.handleEvent;
- this.emitter.off(type, listener, context);
- return this;
- }
- /**
- * @deprecated
- * @alias dispatchEvent
- */
- // eslint-disable-next-line @typescript-eslint/ban-types
- ;
- _proto.emit = function emit(eventName, object) {
- this.dispatchEvent(new CustomEvent(eventName, object));
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
- */;
- _proto.dispatchEvent = function dispatchEvent(e, skipPropagate) {
- if (skipPropagate === void 0) {
- skipPropagate = false;
- }
- if (!isFederatedEvent(e)) {
- throw new Error('DisplayObject cannot propagate events outside of the Federated Events API');
- }
- // should account for Element / Document / Canvas
- var canvas;
- // @ts-ignore
- if (this.document) {
- canvas = this;
- // @ts-ignore
- } else if (this.defaultView) {
- canvas = this.defaultView;
- } else {
- var _this$ownerDocument;
- canvas = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView;
- }
- // assign event manager
- if (canvas) {
- var _e$manager;
- e.manager = canvas.getEventService() || null;
- if (!e.manager) {
- return false;
- }
- e.defaultPrevented = false;
- e.path = [];
- if (!skipPropagate) {
- e.target = this;
- }
- (_e$manager = e.manager) === null || _e$manager === void 0 ? void 0 : _e$manager.dispatchEvent(e, e.type, skipPropagate);
- }
- return !e.defaultPrevented;
- };
- return EventTarget;
- }();
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node
- */
- var Node = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose(Node, _EventTarget);
- function Node() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
- _this.shadow = false;
- /**
- * points to canvas.document
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument
- */
- _this.ownerDocument = null;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isConnected
- * @example
- circle.isConnected; // false
- canvas.appendChild(circle);
- circle.isConnected; // true
- */
- _this.isConnected = false;
- /**
- * Returns node's node document's document base URL.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node
- */
- _this.baseURI = '';
- /**
- * Returns the children.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
- */
- _this.childNodes = [];
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
- */
- _this.nodeType = 0;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeName
- */
- _this.nodeName = '';
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeValue
- */
- _this.nodeValue = null;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode
- */
- _this.parentNode = null;
- return _this;
- }
- Node.isNode = function isNode(target) {
- return !!target.childNodes;
- };
- var _proto = Node.prototype;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/getRootNode
- */
- _proto.getRootNode = function getRootNode(opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (this.parentNode) {
- return this.parentNode.getRootNode(opts);
- }
- if (opts.composed && this.host) {
- return this.host.getRootNode(opts);
- }
- return this;
- };
- _proto.hasChildNodes = function hasChildNodes() {
- return this.childNodes.length > 0;
- };
- _proto.isDefaultNamespace = function isDefaultNamespace(namespace) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.lookupNamespaceURI = function lookupNamespaceURI(prefix) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.lookupPrefix = function lookupPrefix(namespace) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.normalize = function normalize() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isEqualNode
- */;
- _proto.isEqualNode = function isEqualNode(otherNode) {
- // TODO: compare 2 nodes, not sameness
- return this === otherNode;
- };
- _proto.isSameNode = function isSameNode(otherNode) {
- return this.isEqualNode(otherNode);
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
- * @see https://github.com/b-fuze/deno-dom/blob/master/src/dom/node.ts#L338
- */
- _proto.compareDocumentPosition = function compareDocumentPosition(other) {
- if (other === this) {
- // same node
- return 0;
- }
- // if (!(other instanceof Node)) {
- // throw new TypeError(
- // 'Node.compareDocumentPosition: Argument 1 does not implement interface Node.',
- // );
- // }
- var node1Root = other;
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- var node2Root = this;
- var node1Hierarchy = [node1Root];
- var node2Hierarchy = [node2Root];
- while ((_node1Root$parentNode = node1Root.parentNode) !== null && _node1Root$parentNode !== void 0 ? _node1Root$parentNode : node2Root.parentNode) {
- var _node1Root$parentNode;
- node1Root = node1Root.parentNode ? (node1Hierarchy.push(node1Root.parentNode), node1Root.parentNode) : node1Root;
- node2Root = node2Root.parentNode ? (node2Hierarchy.push(node2Root.parentNode), node2Root.parentNode) : node2Root;
- }
- // Check if they don't share the same root node
- if (node1Root !== node2Root) {
- return Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | Node.DOCUMENT_POSITION_PRECEDING;
- }
- var longerHierarchy = node1Hierarchy.length > node2Hierarchy.length ? node1Hierarchy : node2Hierarchy;
- var shorterHierarchy = longerHierarchy === node1Hierarchy ? node2Hierarchy : node1Hierarchy;
- // Check if either is a container of the other
- if (longerHierarchy[longerHierarchy.length - shorterHierarchy.length] === shorterHierarchy[0]) {
- return longerHierarchy === node1Hierarchy ?
- // other is a child of this
- Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING :
- // this is a child of other
- Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING;
- }
- // Find their first common ancestor and see whether they
- // are preceding or following
- var longerStart = longerHierarchy.length - shorterHierarchy.length;
- for (var i = shorterHierarchy.length - 1; i >= 0; i--) {
- var shorterHierarchyNode = shorterHierarchy[i];
- var longerHierarchyNode = longerHierarchy[longerStart + i];
- // We found the first common ancestor
- if (longerHierarchyNode !== shorterHierarchyNode) {
- var siblings = shorterHierarchyNode.parentNode.childNodes;
- if (siblings.indexOf(shorterHierarchyNode) < siblings.indexOf(longerHierarchyNode)) {
- // Shorter is before longer
- if (shorterHierarchy === node1Hierarchy) {
- // Other is before this
- return Node.DOCUMENT_POSITION_PRECEDING;
- } else {
- // This is before other
- return Node.DOCUMENT_POSITION_FOLLOWING;
- }
- } else {
- // Longer is before shorter
- if (longerHierarchy === node1Hierarchy) {
- // Other is before this
- return Node.DOCUMENT_POSITION_PRECEDING;
- } else {
- // Other is after this
- return Node.DOCUMENT_POSITION_FOLLOWING;
- }
- }
- }
- }
- return Node.DOCUMENT_POSITION_FOLLOWING;
- }
- /**
- * @deprecated
- * @alias contains
- */;
- _proto.contain = function contain(other) {
- return this.contains(other);
- };
- _proto.contains = function contains(other) {
- // the node itself, one of its direct children
- var tmp = other;
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
- while (tmp && this !== tmp) {
- tmp = tmp.parentNode;
- }
- return !!tmp;
- };
- _proto.getAncestor = function getAncestor(n) {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- var temp = this;
- while (n > 0 && temp) {
- temp = temp.parentNode;
- n--;
- }
- return temp;
- };
- _proto.forEach = function forEach(callback, assigned) {
- if (assigned === void 0) {
- assigned = false;
- }
- if (!callback(this)) {
- (assigned ? this.childNodes.slice() : this.childNodes).forEach(function (child) {
- child.forEach(callback);
- });
- }
- };
- _createClass(Node, [{
- key: "textContent",
- get:
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent
- */
- function get() {
- var out = '';
- if (this.nodeName === Shape.TEXT) {
- // @ts-ignore
- out += this.style.text;
- }
- for (var _iterator = _createForOfIteratorHelperLoose(this.childNodes), _step; !(_step = _iterator()).done;) {
- var child = _step.value;
- if (child.nodeName === Shape.TEXT) {
- out += child.nodeValue;
- } else {
- out += child.textContent;
- }
- }
- return out;
- },
- set: function set(content) {
- var _this2 = this;
- // remove all children
- this.childNodes.slice().forEach(function (child) {
- _this2.removeChild(child);
- });
- if (this.nodeName === Shape.TEXT) {
- // @ts-ignore
- this.style.text = "" + content;
- }
- }
- }, {
- key: "parent",
- get:
- /**
- * @deprecated
- * @alias parentNode
- */
- function get() {
- return this.parentNode;
- }
- }, {
- key: "parentElement",
- get: function get() {
- return null;
- }
- }, {
- key: "nextSibling",
- get: function get() {
- return null;
- }
- }, {
- key: "previousSibling",
- get: function get() {
- return null;
- }
- }, {
- key: "firstChild",
- get: function get() {
- return this.childNodes.length > 0 ? this.childNodes[0] : null;
- }
- }, {
- key: "lastChild",
- get: function get() {
- return this.childNodes.length > 0 ? this.childNodes[this.childNodes.length - 1] : null;
- }
- }]);
- return Node;
- }(EventTarget);
- /**
- * Both nodes are in different documents or different trees in the same document.
- */
- Node.DOCUMENT_POSITION_DISCONNECTED = 1;
- /**
- * otherNode precedes the node in either a pre-order depth-first traversal
- * 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.
- */
- Node.DOCUMENT_POSITION_PRECEDING = 2;
- /**
- * 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.
- */
- Node.DOCUMENT_POSITION_FOLLOWING = 4;
- /**
- * otherNode is an ancestor of the node.
- */
- Node.DOCUMENT_POSITION_CONTAINS = 8;
- /**
- * otherNode is a descendant of the node.
- */
- Node.DOCUMENT_POSITION_CONTAINED_BY = 16;
- /**
- * The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable.
- */
- Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
- /**
- * the entry of DOM tree
- * Document -> Node -> EventTarget
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
- */
- var Document = /*#__PURE__*/function (_Node) {
- _inheritsLoose(Document, _Node);
- function Document() {
- var _this;
- _this = _Node.call(this) || this;
- /**
- * only document has defaultView, points to canvas,
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView
- */
- _this.defaultView = null;
- /**
- * the root element of document, eg. <html>
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement
- */
- _this.documentElement = void 0;
- /**
- * document.timeline in WAAPI
- */
- _this.timeline = void 0;
- _this.ownerDocument = null;
- _this.nodeName = 'document';
- // create timeline
- try {
- _this.timeline = new runtime.AnimationTimeline(_assertThisInitialized(_this));
- } catch (e) {}
- /**
- * for inherited properties, the initial value is used on the root element only,
- * as long as no specified value is supplied.
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value
- */
- var initialStyle = {};
- BUILT_IN_PROPERTIES.forEach(function (_ref) {
- var n = _ref.n,
- inh = _ref.inh,
- d = _ref.d;
- if (inh && d) {
- initialStyle[n] = isFunction(d) ? d(Shape.GROUP) : d;
- }
- });
- // like <html> in DOM tree
- _this.documentElement = new Group({
- id: 'g-root',
- style: initialStyle
- });
- _this.documentElement.ownerDocument = _assertThisInitialized(_this);
- _this.documentElement.parentNode = _assertThisInitialized(_this);
- _this.childNodes = [_this.documentElement];
- return _this;
- }
- var _proto = Document.prototype;
- /**
- * @example const circle = document.createElement('circle', { style: { r: 10 } });
- */
- _proto.createElement = function createElement(tagName, options) {
- // @observablehq/plot will create <svg>
- if (tagName === 'svg') {
- return this.documentElement;
- }
- // d3 will use <tspan>
- var clazz = this.defaultView.customElements.get(tagName);
- if (!clazz) {
- console.warn('Unsupported tagName: ', tagName);
- clazz = tagName === 'tspan' ? Text : Group;
- }
- var shape = new clazz(options);
- shape.ownerDocument = this;
- return shape;
- };
- _proto.createElementNS = function createElementNS(namespaceURI, tagName, options) {
- return this.createElement(tagName, options);
- };
- _proto.cloneNode = function cloneNode(deep) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.destroy = function destroy() {
- try {
- this.documentElement.destroyChildren();
- this.timeline.destroy();
- } catch (e) {}
- }
- /**
- * Picking 2D graphics with RBush based on BBox, fast but inaccurate.
- */;
- _proto.elementsFromBBox = function elementsFromBBox(minX, minY, maxX, maxY) {
- var rBush = this.defaultView.context.rBushRoot;
- var rBushNodes = rBush.search({
- minX: minX,
- minY: minY,
- maxX: maxX,
- maxY: maxY
- });
- var hitTestList = [];
- rBushNodes.forEach(function (_ref2) {
- var displayObject = _ref2.displayObject;
- var pointerEvents = displayObject.parsedStyle.pointerEvents;
- // account for `visibility`
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
- var isVisibilityAffected = ['auto', 'visiblepainted', 'visiblefill', 'visiblestroke', 'visible'].includes(pointerEvents);
- if ((!isVisibilityAffected || isVisibilityAffected && displayObject.isVisible()) && !displayObject.isCulled() && displayObject.isInteractive()) {
- hitTestList.push(displayObject);
- }
- });
- // find group with max z-index
- hitTestList.sort(function (a, b) {
- return b.sortable.renderOrder - a.sortable.renderOrder;
- });
- return hitTestList;
- };
- _proto.elementFromPointSync = function elementFromPointSync(x, y) {
- var _this$defaultView$can = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }),
- viewportX = _this$defaultView$can.x,
- viewportY = _this$defaultView$can.y;
- var _this$defaultView$get = this.defaultView.getConfig(),
- width = _this$defaultView$get.width,
- height = _this$defaultView$get.height;
- // outside canvas' viewport
- if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
- return null;
- }
- var _this$defaultView$vie = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }),
- clientX = _this$defaultView$vie.x,
- clientY = _this$defaultView$vie.y;
- var _this$defaultView$get2 = this.defaultView.getRenderingService().hooks.pickSync.call({
- topmost: true,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- }),
- picked = _this$defaultView$get2.picked;
- return picked && picked[0] || this.documentElement;
- }
- /**
- * Do picking with API instead of triggering interactive events.
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementFromPoint
- */;
- _proto.elementFromPoint =
- /*#__PURE__*/
- function () {
- var _elementFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(x, y) {
- var _this$defaultView$can2, viewportX, viewportY, _this$defaultView$get3, width, height, _this$defaultView$vie2, clientX, clientY, _yield$this$defaultVi, picked;
- return _regeneratorRuntime().wrap(function _callee$(_context) {
- while (1) switch (_context.prev = _context.next) {
- case 0:
- _this$defaultView$can2 = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }), viewportX = _this$defaultView$can2.x, viewportY = _this$defaultView$can2.y;
- _this$defaultView$get3 = this.defaultView.getConfig(), width = _this$defaultView$get3.width, height = _this$defaultView$get3.height; // outside canvas' viewport
- if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
- _context.next = 4;
- break;
- }
- return _context.abrupt("return", null);
- case 4:
- _this$defaultView$vie2 = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }), clientX = _this$defaultView$vie2.x, clientY = _this$defaultView$vie2.y;
- _context.next = 7;
- return this.defaultView.getRenderingService().hooks.pick.promise({
- topmost: true,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- });
- case 7:
- _yield$this$defaultVi = _context.sent;
- picked = _yield$this$defaultVi.picked;
- return _context.abrupt("return", picked && picked[0] || this.documentElement);
- case 10:
- case "end":
- return _context.stop();
- }
- }, _callee, this);
- }));
- function elementFromPoint(_x, _x2) {
- return _elementFromPoint.apply(this, arguments);
- }
- return elementFromPoint;
- }();
- _proto.elementsFromPointSync = function elementsFromPointSync(x, y) {
- var _this$defaultView$can3 = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }),
- viewportX = _this$defaultView$can3.x,
- viewportY = _this$defaultView$can3.y;
- var _this$defaultView$get4 = this.defaultView.getConfig(),
- width = _this$defaultView$get4.width,
- height = _this$defaultView$get4.height;
- // outside canvas' viewport
- if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
- return [];
- }
- var _this$defaultView$vie3 = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }),
- clientX = _this$defaultView$vie3.x,
- clientY = _this$defaultView$vie3.y;
- var _this$defaultView$get5 = this.defaultView.getRenderingService().hooks.pickSync.call({
- topmost: false,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- }),
- picked = _this$defaultView$get5.picked;
- if (picked[picked.length - 1] !== this.documentElement) {
- picked.push(this.documentElement);
- }
- return picked;
- }
- /**
- * Do picking with API instead of triggering interactive events.
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementsFromPoint
- */;
- _proto.elementsFromPoint =
- /*#__PURE__*/
- function () {
- var _elementsFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(x, y) {
- var _this$defaultView$can4, viewportX, viewportY, _this$defaultView$get6, width, height, _this$defaultView$vie4, clientX, clientY, _yield$this$defaultVi2, picked;
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
- while (1) switch (_context2.prev = _context2.next) {
- case 0:
- _this$defaultView$can4 = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }), viewportX = _this$defaultView$can4.x, viewportY = _this$defaultView$can4.y;
- _this$defaultView$get6 = this.defaultView.getConfig(), width = _this$defaultView$get6.width, height = _this$defaultView$get6.height; // outside canvas' viewport
- if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
- _context2.next = 4;
- break;
- }
- return _context2.abrupt("return", []);
- case 4:
- _this$defaultView$vie4 = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }), clientX = _this$defaultView$vie4.x, clientY = _this$defaultView$vie4.y;
- _context2.next = 7;
- return this.defaultView.getRenderingService().hooks.pick.promise({
- topmost: false,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- });
- case 7:
- _yield$this$defaultVi2 = _context2.sent;
- picked = _yield$this$defaultVi2.picked;
- if (picked[picked.length - 1] !== this.documentElement) {
- picked.push(this.documentElement);
- }
- return _context2.abrupt("return", picked);
- case 11:
- case "end":
- return _context2.stop();
- }
- }, _callee2, this);
- }));
- function elementsFromPoint(_x3, _x4) {
- return _elementsFromPoint.apply(this, arguments);
- }
- return elementsFromPoint;
- }()
- /**
- * eg. Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
- */
- ;
- _proto.appendChild = function appendChild(newChild, index) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.insertBefore = function insertBefore(newChild, refChild) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.removeChild = function removeChild(oldChild, destroy) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.replaceChild = function replaceChild(newChild, oldChild, destroy) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.append = function append() {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.prepend = function prepend() {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- }
- /**
- * Execute query on documentElement.
- */;
- _proto.getElementById = function getElementById(id) {
- return this.documentElement.getElementById(id);
- };
- _proto.getElementsByName = function getElementsByName(name) {
- return this.documentElement.getElementsByName(name);
- };
- _proto.getElementsByTagName = function getElementsByTagName(tagName) {
- return this.documentElement.getElementsByTagName(tagName);
- };
- _proto.getElementsByClassName = function getElementsByClassName(className) {
- return this.documentElement.getElementsByClassName(className);
- };
- _proto.querySelector = function querySelector(selectors) {
- return this.documentElement.querySelector(selectors);
- };
- _proto.querySelectorAll = function querySelectorAll(selectors) {
- return this.documentElement.querySelectorAll(selectors);
- };
- _proto.find = function find(filter) {
- return this.documentElement.find(filter);
- };
- _proto.findAll = function findAll(filter) {
- return this.documentElement.findAll(filter);
- };
- _createClass(Document, [{
- key: "children",
- get: function get() {
- return this.childNodes;
- }
- }, {
- key: "childElementCount",
- get: function get() {
- return this.childNodes.length;
- }
- }, {
- key: "firstElementChild",
- get: function get() {
- return this.firstChild;
- }
- }, {
- key: "lastElementChild",
- get: function get() {
- return this.lastChild;
- }
- }]);
- return Document;
- }(Node);
- /**
- * built-in events for element
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
- *
- * TODO: use MutationObserver instead
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
- */
- var ElementEvent;
- (function (ElementEvent) {
- ElementEvent["REPARENT"] = "reparent";
- ElementEvent["DESTROY"] = "destroy";
- /**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified
- */
- ElementEvent["ATTR_MODIFIED"] = "DOMAttrModified";
- /**
- * it has been inserted
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted
- */
- ElementEvent["INSERTED"] = "DOMNodeInserted";
- /**
- * it is being removed
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved
- */
- ElementEvent["REMOVED"] = "removed";
- /**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnodeinsertedintodocument
- */
- ElementEvent["MOUNTED"] = "DOMNodeInsertedIntoDocument";
- /**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnoderemovedfromdocument
- */
- ElementEvent["UNMOUNTED"] = "DOMNodeRemovedFromDocument";
- ElementEvent["BOUNDS_CHANGED"] = "bounds-changed";
- ElementEvent["CULLED"] = "culled";
- })(ElementEvent || (ElementEvent = {}));
- var MutationEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose(MutationEvent, _FederatedEvent);
- function MutationEvent(typeArg, relatedNode, prevValue, newValue, attrName, attrChange, prevParsedValue, newParsedValue) {
- var _this;
- _this = _FederatedEvent.call(this, null) || this;
- _this.relatedNode = void 0;
- _this.prevValue = void 0;
- _this.newValue = void 0;
- _this.attrName = void 0;
- _this.attrChange = void 0;
- _this.prevParsedValue = void 0;
- _this.newParsedValue = void 0;
- _this.relatedNode = relatedNode;
- _this.prevValue = prevValue;
- _this.newValue = newValue;
- _this.attrName = attrName;
- _this.attrChange = attrChange;
- _this.prevParsedValue = prevParsedValue;
- _this.newParsedValue = newParsedValue;
- _this.type = typeArg;
- return _this;
- }
- return MutationEvent;
- }(FederatedEvent);
- MutationEvent.ADDITION = 2;
- MutationEvent.MODIFICATION = 1;
- MutationEvent.REMOVAL = 3;
- var entityCounter = 0;
- function resetEntityCounter() {
- entityCounter = 0;
- }
- var insertedEvent = new MutationEvent(ElementEvent.INSERTED, null, '', '', '', 0, '', '');
- var removedEvent = new MutationEvent(ElementEvent.REMOVED, null, '', '', '', 0, '', '');
- var destroyEvent = new CustomEvent(ElementEvent.DESTROY);
- /**
- * Has following capabilities:
- * * Node insert/remove, eg. appendChild, removeChild, remove...
- * * Query eg. querySelector getElementById...
- * * Animation
- */
- var Element = /*#__PURE__*/function (_Node) {
- _inheritsLoose(Element, _Node);
- function Element() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _Node.call.apply(_Node, [this].concat(args)) || this;
- /**
- * Unique id.
- */
- _this.entity = entityCounter++;
- _this.renderable = {
- bounds: undefined,
- boundsDirty: true,
- renderBounds: undefined,
- renderBoundsDirty: true,
- dirtyRenderBounds: undefined,
- dirty: false,
- proxyNodeName: undefined
- };
- _this.cullable = {
- strategy: Strategy.Standard,
- visibilityPlaneMask: -1,
- visible: true,
- enable: true
- };
- _this.transformable = {
- dirtyFlag: false,
- localDirtyFlag: false,
- frozen: false,
- localPosition: [0, 0, 0],
- localRotation: [0, 0, 0, 1],
- localScale: [1, 1, 1],
- localTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
- localSkew: [0, 0],
- position: [0, 0, 0],
- rotation: [0, 0, 0, 1],
- scaling: [1, 1, 1],
- worldTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
- origin: [0, 0, 0]
- };
- _this.sortable = {
- dirty: false,
- sorted: undefined,
- renderOrder: 0,
- dirtyChildren: [],
- dirtyReason: undefined
- };
- _this.geometry = {
- contentBounds: undefined,
- renderBounds: undefined
- };
- _this.rBushNode = {
- aabb: undefined
- };
- /**
- * used with `getElementById()`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/id
- */
- _this.id = void 0;
- /**
- * used in `getElementsByName`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
- */
- _this.name = void 0;
- /**
- * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/namespaceURI
- */
- _this.namespaceURI = 'g';
- _this.scrollLeft = 0;
- _this.scrollTop = 0;
- /**
- * We don't support border now
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
- */
- _this.clientTop = 0;
- _this.clientLeft = 0;
- /**
- * is destroyed or not
- */
- _this.destroyed = false;
- /**
- * compatible with `style`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
- */
- _this.style = {};
- _this.computedStyle = runtime.enableCSSParsing ? {
- anchor: unsetKeywordValue,
- opacity: unsetKeywordValue,
- fillOpacity: unsetKeywordValue,
- strokeOpacity: unsetKeywordValue,
- fill: unsetKeywordValue,
- stroke: unsetKeywordValue,
- transform: unsetKeywordValue,
- transformOrigin: unsetKeywordValue,
- visibility: unsetKeywordValue,
- pointerEvents: unsetKeywordValue,
- lineWidth: unsetKeywordValue,
- lineCap: unsetKeywordValue,
- lineJoin: unsetKeywordValue,
- increasedLineWidthForHitTesting: unsetKeywordValue,
- fontSize: unsetKeywordValue,
- fontFamily: unsetKeywordValue,
- fontStyle: unsetKeywordValue,
- fontWeight: unsetKeywordValue,
- fontVariant: unsetKeywordValue,
- textAlign: unsetKeywordValue,
- textBaseline: unsetKeywordValue,
- textTransform: unsetKeywordValue,
- zIndex: unsetKeywordValue,
- filter: unsetKeywordValue,
- shadowType: unsetKeywordValue
- } : null;
- /**
- * Renderers will use these used values.
- */
- _this.parsedStyle = {
- // opacity: '',
- // fillOpacity: '',
- // strokeOpacity: '',
- // transformOrigin: '',
- // visibility: '',
- // pointerEvents: '',
- // lineWidth: '',
- // lineCap: '',
- // lineJoin: '',
- // increasedLineWidthForHitTesting: '',
- // fontSize: '',
- // fontFamily: '',
- // fontStyle: '',
- // fontWeight: '',
- // fontVariant: '',
- // textAlign: '',
- // textBaseline: '',
- // textTransform: '',
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
- */
- _this.attributes = {};
- return _this;
- }
- Element.isElement = function isElement(target) {
- return !!target.getAttribute;
- };
- var _proto = Element.prototype;
- _proto.cloneNode = function cloneNode(deep) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.appendChild = function appendChild(child, index) {
- var _this$ownerDocument;
- if (child.destroyed) {
- throw new Error(ERROR_MSG_APPEND_DESTROYED_ELEMENT);
- }
- runtime.sceneGraphService.attach(child, this, index);
- if ((_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView) {
- this.ownerDocument.defaultView.mountChildren(child);
- }
- insertedEvent.relatedNode = this;
- child.dispatchEvent(insertedEvent);
- return child;
- };
- _proto.insertBefore = function insertBefore(newChild, refChild) {
- if (!refChild) {
- this.appendChild(newChild);
- } else {
- var index = this.childNodes.indexOf(refChild);
- this.appendChild(newChild, index - 1);
- }
- return newChild;
- };
- _proto.replaceChild = function replaceChild(newChild, oldChild) {
- var index = this.childNodes.indexOf(oldChild);
- this.removeChild(oldChild);
- this.appendChild(newChild, index);
- return oldChild;
- };
- _proto.removeChild = function removeChild(child) {
- var _child$ownerDocument;
- // should emit on itself before detach
- removedEvent.relatedNode = this;
- child.dispatchEvent(removedEvent);
- if ((_child$ownerDocument = child.ownerDocument) === null || _child$ownerDocument === void 0 ? void 0 : _child$ownerDocument.defaultView) {
- child.ownerDocument.defaultView.unmountChildren(child);
- }
- // remove from scene graph
- runtime.sceneGraphService.detach(child);
- return child;
- }
- /**
- * Remove all children which can be appended to its original parent later again.
- */;
- _proto.removeChildren = function removeChildren() {
- for (var i = this.childNodes.length - 1; i >= 0; i--) {
- var child = this.childNodes[i];
- this.removeChild(child);
- }
- }
- /**
- * Recursively destroy all children which can not be appended to its original parent later again.
- */;
- _proto.destroyChildren = function destroyChildren() {
- for (var i = this.childNodes.length - 1; i >= 0; i--) {
- var child = this.childNodes[i];
- if (child.childNodes.length) {
- child.destroyChildren();
- }
- child.destroy();
- }
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
- */;
- _proto.matches = function matches(selector) {
- return runtime.sceneGraphService.matches(selector, this);
- };
- _proto.getElementById = function getElementById(id) {
- return runtime.sceneGraphService.querySelector("#" + id, this);
- };
- _proto.getElementsByName = function getElementsByName(name) {
- return runtime.sceneGraphService.querySelectorAll("[name=\"" + name + "\"]", this);
- };
- _proto.getElementsByClassName = function getElementsByClassName(className) {
- return runtime.sceneGraphService.querySelectorAll("." + className, this);
- };
- _proto.getElementsByTagName = function getElementsByTagName(tagName) {
- return runtime.sceneGraphService.querySelectorAll(tagName, this);
- };
- _proto.querySelector = function querySelector(selectors) {
- return runtime.sceneGraphService.querySelector(selectors, this);
- };
- _proto.querySelectorAll = function querySelectorAll(selectors) {
- return runtime.sceneGraphService.querySelectorAll(selectors, this);
- }
- /**
- * should traverses the element and its parents (heading toward the document root)
- * until it finds a node that matches the specified CSS selector.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill
- */;
- _proto.closest = function closest(selectors) {
- var el = this;
- do {
- if (runtime.sceneGraphService.matches(selectors, el)) return el;
- el = el.parentElement;
- } while (el !== null);
- return null;
- }
- /**
- * search in scene group, but should not include itself
- */;
- _proto.find = function find(filter) {
- var _this2 = this;
- var target = null;
- this.forEach(function (object) {
- if (object !== _this2 && filter(object)) {
- target = object;
- return true;
- }
- return false;
- });
- return target;
- };
- _proto.findAll = function findAll(filter) {
- var _this3 = this;
- var objects = [];
- this.forEach(function (object) {
- if (object !== _this3 && filter(object)) {
- objects.push(object);
- }
- });
- return objects;
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/after
- */;
- _proto.after = function after() {
- var _this4 = this;
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- nodes[_key2] = arguments[_key2];
- }
- nodes.forEach(function (node, i) {
- var _this4$parentNode;
- return (_this4$parentNode = _this4.parentNode) === null || _this4$parentNode === void 0 ? void 0 : _this4$parentNode.appendChild(node, index + i + 1);
- });
- }
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/before
- */;
- _proto.before = function before() {
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- nodes[_key3] = arguments[_key3];
- }
- var first = nodes[0],
- rest = nodes.slice(1);
- this.parentNode.appendChild(first, index);
- first.after.apply(first, rest);
- }
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceWith
- */;
- _proto.replaceWith = function replaceWith() {
- this.after.apply(this, arguments);
- this.remove();
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/append
- */;
- _proto.append = function append() {
- var _this5 = this;
- for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
- nodes[_key4] = arguments[_key4];
- }
- nodes.forEach(function (node) {
- return _this5.appendChild(node);
- });
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/prepend
- */;
- _proto.prepend = function prepend() {
- var _this6 = this;
- for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
- nodes[_key5] = arguments[_key5];
- }
- nodes.forEach(function (node, i) {
- return _this6.appendChild(node, i);
- });
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceChildren
- */;
- _proto.replaceChildren = function replaceChildren() {
- while (this.childNodes.length && this.firstChild) {
- this.removeChild(this.firstChild);
- }
- this.append.apply(this, arguments);
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/remove
- */;
- _proto.remove = function remove() {
- if (this.parentNode) {
- return this.parentNode.removeChild(this);
- }
- return this;
- };
- _proto.destroy = function destroy() {
- // destroy itself before remove
- this.dispatchEvent(destroyEvent);
- // remove from scenegraph first
- this.remove();
- // remove event listeners
- this.emitter.removeAllListeners();
- this.destroyed = true;
- };
- _proto.getGeometryBounds = function getGeometryBounds() {
- return runtime.sceneGraphService.getGeometryBounds(this);
- };
- _proto.getRenderBounds = function getRenderBounds() {
- return runtime.sceneGraphService.getBounds(this, true);
- }
- /**
- * get bounds in world space, account for children
- */;
- _proto.getBounds = function getBounds() {
- return runtime.sceneGraphService.getBounds(this);
- }
- /**
- * get bounds in local space, account for children
- */;
- _proto.getLocalBounds = function getLocalBounds() {
- return runtime.sceneGraphService.getLocalBounds(this);
- }
- /**
- * account for context's bounds in client space,
- * but not accounting for children
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
- */;
- _proto.getBoundingClientRect = function getBoundingClientRect() {
- return runtime.sceneGraphService.getBoundingClientRect(this);
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getClientRects
- */;
- _proto.getClientRects = function getClientRects() {
- return [this.getBoundingClientRect()];
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap
- * eg. circle.computedStyleMap().get('fill');
- */
- _proto.computedStyleMap = function computedStyleMap() {
- return new Map(Object.entries(this.computedStyle));
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
- */
- _proto.getAttributeNames = function getAttributeNames() {
- return Object.keys(this.attributes);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
- */;
- _proto.getAttribute = function getAttribute(name) {
- // @see https://github.com/antvis/G/issues/1267
- if (isSymbol(name)) {
- return runtime.enableCSSParsing ? null : undefined;
- }
- var value = this.attributes[name];
- if (value === undefined) {
- var attributeName = formatAttributeName(name);
- value = this.attributes[attributeName];
- // if the given attribute does not exist, the value returned will either be null or ""
- return runtime.enableCSSParsing ? isNil(value) ? null : value : value;
- } else {
- return value;
- }
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
- */;
- _proto.hasAttribute = function hasAttribute(qualifiedName) {
- return this.getAttributeNames().includes(qualifiedName);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
- */;
- _proto.hasAttributes = function hasAttributes() {
- return !!this.getAttributeNames().length;
- }
- /**
- * 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.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
- */;
- _proto.removeAttribute = function removeAttribute(attributeName) {
- this.setAttribute(attributeName, null);
- delete this.attributes[attributeName];
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
- */;
- _proto.setAttribute = function setAttribute(attributeName, value, force) {
- this.attributes[attributeName] = value;
- };
- _proto.getAttributeNS = function getAttributeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.getAttributeNode = function getAttributeNode(qualifiedName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.getAttributeNodeNS = function getAttributeNodeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.hasAttributeNS = function hasAttributeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.removeAttributeNS = function removeAttributeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.removeAttributeNode = function removeAttributeNode(attr) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.setAttributeNS = function setAttributeNS(namespace, qualifiedName, value) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.setAttributeNode = function setAttributeNode(attr) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.setAttributeNodeNS = function setAttributeNodeNS(attr) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.toggleAttribute = function toggleAttribute(qualifiedName, force) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _createClass(Element, [{
- key: "className",
- get:
- /**
- * used in `getElementsByClassName`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
- */
- function get() {
- // @ts-ignore
- return this.getAttribute('class') || '';
- },
- set: function set(className) {
- this.setAttribute('class', className);
- }
- }, {
- key: "classList",
- get:
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
- */
- function get() {
- return this.className.split(' ').filter(function (c) {
- return c !== '';
- });
- }
- }, {
- key: "tagName",
- get: function get() {
- return this.nodeName;
- }
- }, {
- key: "children",
- get: function get() {
- return this.childNodes;
- }
- }, {
- key: "childElementCount",
- get: function get() {
- return this.childNodes.length;
- }
- }, {
- key: "firstElementChild",
- get: function get() {
- return this.firstChild;
- }
- }, {
- key: "lastElementChild",
- get: function get() {
- return this.lastChild;
- }
- }, {
- key: "parentElement",
- get: function get() {
- return this.parentNode;
- }
- }, {
- key: "nextSibling",
- get: function get() {
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- return this.parentNode.childNodes[index + 1] || null;
- }
- return null;
- }
- }, {
- key: "previousSibling",
- get: function get() {
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- return this.parentNode.childNodes[index - 1] || null;
- }
- return null;
- }
- }]);
- return Element;
- }(Node);
- var FederatedMouseEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose(FederatedMouseEvent, _FederatedEvent);
- function FederatedMouseEvent() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _FederatedEvent.call.apply(_FederatedEvent, [this].concat(args)) || this;
- /** Whether the "alt" key was pressed when this mouse event occurred. */
- _this.altKey = void 0;
- /** The specific button that was pressed in this mouse event. */
- _this.button = void 0;
- /** The button depressed when this event occurred. */
- _this.buttons = void 0;
- /** Whether the "control" key was pressed when this mouse event occurred. */
- _this.ctrlKey = void 0;
- /** Whether the "meta" key was pressed when this mouse event occurred. */
- _this.metaKey = void 0;
- /** This is currently not implemented in the Federated Events API. */
- _this.relatedTarget = void 0;
- /** Whether the "shift" key was pressed when this mouse event occurred. */
- _this.shiftKey = void 0;
- /**
- * The coordinates of the mouse event relative to the canvas.
- */
- _this.client = new Point();
- /**
- * The movement in this pointer relative to the last `mousemove` event.
- */
- _this.movement = new Point();
- /**
- * The offset of the pointer coordinates w.r.t. target DisplayObject in world space. This is
- * not supported at the moment.
- */
- _this.offset = new Point();
- /**
- * The pointer coordinates in world space.
- */
- _this.global = new Point();
- /**
- * The pointer coordinates in sceen space.
- */
- _this.screen = new Point();
- return _this;
- }
- var _proto = FederatedMouseEvent.prototype;
- _proto.getModifierState = function getModifierState(key) {
- return 'getModifierState' in this.nativeEvent && this.nativeEvent.getModifierState(key);
- };
- _proto.initMouseEvent = function initMouseEvent() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _createClass(FederatedMouseEvent, [{
- key: "clientX",
- get: function get() {
- return this.client.x;
- }
- }, {
- key: "clientY",
- get: function get() {
- return this.client.y;
- }
- }, {
- key: "movementX",
- get: function get() {
- return this.movement.x;
- }
- }, {
- key: "movementY",
- get: function get() {
- return this.movement.y;
- }
- }, {
- key: "offsetX",
- get: function get() {
- return this.offset.x;
- }
- }, {
- key: "offsetY",
- get: function get() {
- return this.offset.y;
- }
- }, {
- key: "globalX",
- get: function get() {
- return this.global.x;
- }
- }, {
- key: "globalY",
- get: function get() {
- return this.global.y;
- }
- }, {
- key: "screenX",
- get: function get() {
- return this.screen.x;
- }
- }, {
- key: "screenY",
- get: function get() {
- return this.screen.y;
- }
- }]);
- return FederatedMouseEvent;
- }(FederatedEvent);
- var FederatedPointerEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
- _inheritsLoose(FederatedPointerEvent, _FederatedMouseEvent);
- function FederatedPointerEvent() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
- /**
- * The unique identifier of the pointer.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
- */
- _this.pointerId = void 0;
- /**
- * The width of the pointer's contact along the x-axis, measured in CSS pixels.
- * radiusX of TouchEvents will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
- */
- _this.width = 0;
- /**
- * The height of the pointer's contact along the y-axis, measured in CSS pixels.
- * radiusY of TouchEvents will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
- */
- _this.height = 0;
- /**
- * Indicates whether or not the pointer device that created the event is the primary pointer.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
- */
- _this.isPrimary = false;
- /**
- * The type of pointer that triggered the event.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
- */
- _this.pointerType = void 0;
- /**
- * Pressure applied by the pointing device during the event.
- *s
- * A Touch's force property will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
- */
- _this.pressure = void 0;
- /**
- * Barrel pressure on a stylus pointer.
- *
- * @see https://w3c.github.io/pointerevents/#pointerevent-interface
- */
- _this.tangentialPressure = void 0;
- /**
- * The angle, in degrees, between the pointer device and the screen.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
- */
- _this.tiltX = void 0;
- /**
- * The angle, in degrees, between the pointer device and the screen.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
- */
- _this.tiltY = void 0;
- /**
- * Twist of a stylus pointer.
- *
- * @see https://w3c.github.io/pointerevents/#pointerevent-interface
- */
- _this.twist = void 0;
- return _this;
- }
- var _proto = FederatedPointerEvent.prototype;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents
- */
- _proto.getCoalescedEvents = function getCoalescedEvents() {
- if (this.type === 'pointermove' || this.type === 'mousemove' || this.type === 'touchmove') {
- return [this];
- }
- return [];
- }
- /**
- * @see https://chromestatus.com/feature/5765569655603200
- */;
- _proto.getPredictedEvents = function getPredictedEvents() {
- throw new Error('getPredictedEvents is not supported!');
- }
- /**
- * @see https://github.com/antvis/G/issues/1115
- * We currently reuses event objects in the event system,
- * avoiding the creation of a large number of event objects.
- * Reused objects are only used to carry different data,
- * such as coordinate information, native event objects,
- * and therefore the lifecycle is limited to the event handler,
- * which can lead to unintended consequences if an attempt is made to cache the entire event object.
- *
- * 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.
- */;
- _proto.clone = function clone() {
- return this.manager.clonePointerEvent(this);
- };
- return FederatedPointerEvent;
- }(FederatedMouseEvent);
- var FederatedWheelEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
- _inheritsLoose(FederatedWheelEvent, _FederatedMouseEvent);
- function FederatedWheelEvent() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
- /**
- * The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
- * `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
- */
- _this.deltaMode = void 0;
- /** Horizontal scroll amount */
- _this.deltaX = void 0;
- /** Vertical scroll amount */
- _this.deltaY = void 0;
- /** z-axis scroll amount. */
- _this.deltaZ = void 0;
- /** Units specified in lines. */
- _this.DOM_DELTA_LINE = 0;
- /** Units specified in pages. */
- _this.DOM_DELTA_PAGE = 1;
- /** Units specified in pixels. */
- _this.DOM_DELTA_PIXEL = 2;
- return _this;
- }
- var _proto = FederatedWheelEvent.prototype;
- _proto.clone = function clone() {
- return this.manager.cloneWheelEvent(this);
- };
- return FederatedWheelEvent;
- }(FederatedMouseEvent);
- function isDisplayObject(value) {
- return !!(value === null || value === void 0 ? void 0 : value.nodeName);
- }
- var mutationEvent = new MutationEvent(ElementEvent.ATTR_MODIFIED, null, null, null, null, MutationEvent.MODIFICATION, null, null);
- var DEFAULT_STYLE_PROPS = {
- anchor: '',
- opacity: '',
- fillOpacity: '',
- strokeOpacity: '',
- fill: '',
- stroke: '',
- transform: '',
- transformOrigin: '',
- visibility: '',
- pointerEvents: '',
- lineWidth: '',
- lineCap: '',
- lineJoin: '',
- increasedLineWidthForHitTesting: '',
- fontSize: '',
- fontFamily: '',
- fontStyle: '',
- fontWeight: '',
- fontVariant: '',
- textAlign: '',
- textBaseline: '',
- textTransform: '',
- zIndex: '',
- filter: '',
- shadowType: ''
- };
- var DEFAULT_PARSED_STYLE_PROPS = {
- anchor: [0, 0],
- fill: noneColor,
- stroke: noneColor,
- transform: [],
- zIndex: 0,
- filter: [],
- shadowType: 'outer',
- miterLimit: 10
- };
- var DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED = _extends({}, DEFAULT_PARSED_STYLE_PROPS, {
- opacity: 1,
- fillOpacity: 1,
- strokeOpacity: 1,
- visibility: 'visible',
- pointerEvents: 'auto',
- lineWidth: 1,
- lineCap: 'butt',
- lineJoin: 'miter',
- increasedLineWidthForHitTesting: 0,
- fillRule: 'nonzero'
- // TODO: transformOrigin
- });
- var INHERITABLE_BASE_STYLE_PROPS = ['opacity', 'fillOpacity', 'strokeOpacity', 'transformOrigin', 'visibility', 'pointerEvents', 'lineWidth', 'lineCap', 'lineJoin', 'increasedLineWidthForHitTesting'];
- var INHERITABLE_STYLE_PROPS = [].concat(INHERITABLE_BASE_STYLE_PROPS, ['fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'fontVariant', 'textAlign', 'textBaseline', 'textTransform']);
- var DATASET_PREFIX = 'data-';
- /**
- * prototype chains: DisplayObject -> Element -> Node -> EventTarget
- *
- * mixins: Animatable, Transformable, Visible
- * @see https://github.com/tannerntannern/ts-mixer/blob/master/README.md#mixing-generic-classes
- *
- * Provide abilities in scene graph, such as:
- * * transform `translate/rotate/scale`
- * * add/remove child
- * * visibility and z-index
- *
- * Those abilities are implemented with those components: `Transform/Sortable/Visible`.
- *
- * Emit following events:
- * * init
- * * destroy
- * * attributeChanged
- */
- var DisplayObject = /*#__PURE__*/function (_Element) {
- _inheritsLoose(DisplayObject, _Element);
- function DisplayObject(config) {
- var _this$config$capture;
- var _this;
- _this = _Element.call(this) || this;
- // assign name, id to config
- // eg. group.get('name')
- /**
- * contains style props in constructor's params, eg. fill, stroke...
- */
- _this.config = void 0;
- _this.isCustomElement = false;
- _this.isMutationObserved = false;
- /**
- * push to active animations after calling `animate()`
- */
- _this.activeAnimations = [];
- /**
- * Use data-* attribute.
- * @see https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
- * @example
- * group.dataset.prop1 = 1;
- * group.getAttribute('data-prop1'); // 1
- */
- _this.dataset = void 0;
- /**
- * Use `this.style.clipPath` instead.
- * @deprecated
- */
- _this.getClip = function () {
- return this.style.clipPath || null;
- };
- _this.config = config;
- // compatible with G 3.0
- _this.config.interactive = (_this$config$capture = _this.config.capture) !== null && _this$config$capture !== void 0 ? _this$config$capture : _this.config.interactive;
- // init scene graph node
- _this.id = _this.config.id || '';
- _this.name = _this.config.name || '';
- if (_this.config.className || _this.config.class) {
- _this.className = _this.config.className || _this.config.class;
- }
- _this.nodeName = _this.config.type || Shape.GROUP;
- // compatible with G 3.0
- _this.config.style = _this.config.style || _this.config.attrs || {};
- Object.assign(_this.config.style, _this.config.attrs);
- // this.config.style = {
- // // ...DEFAULT_STYLE_PROPS,
- // ...this.config.style,
- // ...this.config.attrs,
- // };
- if (_this.config.visible != null) {
- _this.config.style.visibility = _this.config.visible === false ? 'hidden' : 'visible';
- }
- if (_this.config.interactive != null) {
- _this.config.style.pointerEvents = _this.config.interactive === false ? 'none' : 'auto';
- }
- // merge parsed value
- Object.assign(_this.parsedStyle, runtime.enableCSSParsing ? DEFAULT_PARSED_STYLE_PROPS : DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED, _this.config.initialParsedStyle);
- if (runtime.enableCSSParsing) {
- Object.assign(_this.attributes, DEFAULT_STYLE_PROPS);
- }
- // start to process attributes
- _this.initAttributes(_this.config.style);
- var Proxy = runtime.globalThis.Proxy ? runtime.globalThis.Proxy : function () {};
- if (runtime.enableDataset) {
- _this.dataset = new Proxy({}, {
- get: function get(target, name) {
- var formattedName = "" + DATASET_PREFIX + kebabize(name);
- if (target[formattedName] !== undefined) {
- return target[formattedName];
- }
- return _this.getAttribute(formattedName);
- },
- set: function set(_, prop, value) {
- _this.setAttribute("" + DATASET_PREFIX + kebabize(prop), value);
- return true;
- }
- });
- }
- if (runtime.enableStyleSyntax) {
- _this.style = new Proxy(
- // @ts-ignore
- {
- // ...this.attributes,
- setProperty: function setProperty(propertyName, value) {
- _this.setAttribute(propertyName, value);
- },
- getPropertyValue: function getPropertyValue(propertyName) {
- return _this.getAttribute(propertyName);
- },
- removeProperty: function removeProperty(propertyName) {
- _this.removeAttribute(propertyName);
- },
- item: function item() {
- return '';
- }
- }, {
- get: function get(target, name) {
- if (target[name] !== undefined) {
- // if (name in target) {
- return target[name];
- }
- return _this.getAttribute(name);
- },
- set: function set(_, prop, value) {
- _this.setAttribute(prop, value);
- return true;
- }
- });
- }
- return _this;
- }
- var _proto = DisplayObject.prototype;
- _proto.destroy = function destroy() {
- _Element.prototype.destroy.call(this);
- // stop all active animations
- this.getAnimations().forEach(function (animation) {
- animation.cancel();
- });
- // FIXME
- // this.renderable = null;
- // this.cullable = null;
- // this.transformable = null;
- // this.rBushNode = null;
- // this.geometry = null;
- // this.sortable = null;
- };
- _proto.cloneNode = function cloneNode(deep, customCloneFunc) {
- var clonedStyle = _extends({}, this.attributes);
- for (var attributeName in clonedStyle) {
- var attribute = clonedStyle[attributeName];
- // @see https://github.com/antvis/G/issues/1095
- if (isDisplayObject(attribute) &&
- // share the same clipPath if possible
- attributeName !== 'clipPath' && attributeName !== 'offsetPath' && attributeName !== 'textPath') {
- clonedStyle[attributeName] = attribute.cloneNode(deep);
- }
- // TODO: clone other type
- if (customCloneFunc) {
- clonedStyle[attributeName] = customCloneFunc(attributeName, attribute);
- }
- }
- var cloned = new this.constructor({
- // copy id & name
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode#notes
- id: this.id,
- name: this.name,
- className: this.name,
- interactive: this.interactive,
- style: clonedStyle
- });
- // apply transform
- cloned.setLocalTransform(this.getLocalTransform());
- if (deep) {
- this.children.forEach(function (child) {
- // skip marker
- if (!child.style.isMarker) {
- var clonedChild = child.cloneNode(deep);
- cloned.appendChild(clonedChild);
- }
- });
- }
- return cloned;
- };
- _proto.initAttributes = function initAttributes(attributes) {
- if (attributes === void 0) {
- attributes = {};
- }
- var renderable = this.renderable;
- var options = {
- forceUpdateGeometry: true
- // usedAttributes:
- // // only Group / Text should account for text relative props
- // this.tagName === Shape.GROUP || this.tagName === Shape.TEXT
- // ? INHERITABLE_STYLE_PROPS
- // : INHERITABLE_BASE_STYLE_PROPS,
- };
- if (runtime.enableCSSParsing) {
- // @ts-ignore
- options.usedAttributes = INHERITABLE_STYLE_PROPS;
- }
- // account for FCP, process properties as less as possible
- var formattedAttributes = {};
- for (var name in attributes) {
- var attributeName = formatAttributeName(name);
- formattedAttributes[attributeName] = attributes[name];
- }
- runtime.styleValueRegistry.processProperties(this, formattedAttributes, options);
- // redraw at next frame
- renderable.dirty = true;
- };
- _proto.setAttribute = function setAttribute(name, value, force) {
- if (force === void 0) {
- force = false;
- }
- var attributeName = formatAttributeName(name);
- // ignore undefined value
- if (isUndefined(value)) {
- return;
- }
- if (force || value !== this.attributes[attributeName]) {
- this.internalSetAttribute(attributeName, value);
- _Element.prototype.setAttribute.call(this, attributeName, value);
- }
- }
- /**
- * called when attributes get changed or initialized
- */;
- _proto.internalSetAttribute = function internalSetAttribute(name, value, parseOptions) {
- var _runtime$styleValueRe;
- if (parseOptions === void 0) {
- parseOptions = {};
- }
- var renderable = this.renderable;
- var oldValue = this.attributes[name];
- var oldParsedValue = this.parsedStyle[name];
- runtime.styleValueRegistry.processProperties(this, (_runtime$styleValueRe = {}, _runtime$styleValueRe[name] = value, _runtime$styleValueRe), parseOptions);
- // redraw at next frame
- renderable.dirty = true;
- var newParsedValue = this.parsedStyle[name];
- if (this.isConnected) {
- mutationEvent.relatedNode = this;
- mutationEvent.prevValue = oldValue;
- mutationEvent.newValue = value;
- mutationEvent.attrName = name;
- mutationEvent.prevParsedValue = oldParsedValue;
- mutationEvent.newParsedValue = newParsedValue;
- if (this.isMutationObserved) {
- this.dispatchEvent(mutationEvent);
- } else {
- mutationEvent.target = this;
- this.ownerDocument.defaultView.dispatchEvent(mutationEvent, true);
- }
- }
- if ((this.isCustomElement && this.isConnected || !this.isCustomElement) && this.attributeChangedCallback) {
- this.attributeChangedCallback(name, oldValue, value, oldParsedValue, newParsedValue);
- }
- }
- // #region transformable
- /**
- * returns different values than getBoundingClientRect(), as the latter returns value relative to the viewport
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
- *
- * FIXME: It is worth noting that getBBox responds to original untransformed values of a drawn object.
- * @see https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox
- */;
- _proto.getBBox = function getBBox() {
- var aabb = this.getBounds();
- var _aabb$getMin = aabb.getMin(),
- left = _aabb$getMin[0],
- top = _aabb$getMin[1];
- var _aabb$getMax = aabb.getMax(),
- right = _aabb$getMax[0],
- bottom = _aabb$getMax[1];
- return new Rectangle(left, top, right - left, bottom - top);
- };
- _proto.setOrigin = function setOrigin(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.setOrigin(this, createVec3(position, y, z));
- return this;
- };
- _proto.getOrigin = function getOrigin() {
- return runtime.sceneGraphService.getOrigin(this);
- }
- /**
- * set position in world space
- */;
- _proto.setPosition = function setPosition(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.setPosition(this, createVec3(position, y, z));
- return this;
- }
- /**
- * set position in local space
- */;
- _proto.setLocalPosition = function setLocalPosition(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.setLocalPosition(this, createVec3(position, y, z));
- return this;
- }
- /**
- * translate in world space
- */;
- _proto.translate = function translate(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.translate(this, createVec3(position, y, z));
- return this;
- }
- /**
- * translate in local space
- */;
- _proto.translateLocal = function translateLocal(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.translateLocal(this, createVec3(position, y, z));
- return this;
- };
- _proto.getPosition = function getPosition() {
- return runtime.sceneGraphService.getPosition(this);
- };
- _proto.getLocalPosition = function getLocalPosition() {
- return runtime.sceneGraphService.getLocalPosition(this);
- }
- /**
- * compatible with G 3.0
- *
- * scaling in local space
- * scale(10) = scale(10, 10, 10)
- *
- * we can't set scale in world space
- */;
- _proto.scale = function scale(scaling, y, z) {
- return this.scaleLocal(scaling, y, z);
- };
- _proto.scaleLocal = function scaleLocal(scaling, y, z) {
- if (typeof scaling === 'number') {
- y = y || scaling;
- z = z || scaling;
- scaling = createVec3(scaling, y, z);
- }
- runtime.sceneGraphService.scaleLocal(this, scaling);
- return this;
- }
- /**
- * set scaling in local space
- */;
- _proto.setLocalScale = function setLocalScale(scaling, y, z) {
- if (typeof scaling === 'number') {
- y = y || scaling;
- z = z || scaling;
- scaling = createVec3(scaling, y, z);
- }
- runtime.sceneGraphService.setLocalScale(this, scaling);
- return this;
- }
- /**
- * get scaling in local space
- */;
- _proto.getLocalScale = function getLocalScale() {
- return runtime.sceneGraphService.getLocalScale(this);
- }
- /**
- * get scaling in world space
- */;
- _proto.getScale = function getScale() {
- return runtime.sceneGraphService.getScale(this);
- }
- /**
- * only return degrees of Z axis in world space
- */;
- _proto.getEulerAngles = function getEulerAngles() {
- var _getEuler = getEuler(vec3.create(), runtime.sceneGraphService.getWorldTransform(this)),
- ez = _getEuler[2];
- return rad2deg(ez);
- }
- /**
- * only return degrees of Z axis in local space
- */;
- _proto.getLocalEulerAngles = function getLocalEulerAngles() {
- var _getEuler2 = getEuler(vec3.create(), runtime.sceneGraphService.getLocalRotation(this)),
- ez = _getEuler2[2];
- return rad2deg(ez);
- }
- /**
- * set euler angles(degrees) in world space
- */;
- _proto.setEulerAngles = function setEulerAngles(z) {
- runtime.sceneGraphService.setEulerAngles(this, 0, 0, z);
- return this;
- }
- /**
- * set euler angles(degrees) in local space
- */;
- _proto.setLocalEulerAngles = function setLocalEulerAngles(z) {
- runtime.sceneGraphService.setLocalEulerAngles(this, 0, 0, z);
- return this;
- };
- _proto.rotateLocal = function rotateLocal(x, y, z) {
- if (isNil(y) && isNil(z)) {
- runtime.sceneGraphService.rotateLocal(this, 0, 0, x);
- } else {
- runtime.sceneGraphService.rotateLocal(this, x, y, z);
- }
- return this;
- };
- _proto.rotate = function rotate(x, y, z) {
- if (isNil(y) && isNil(z)) {
- runtime.sceneGraphService.rotate(this, 0, 0, x);
- } else {
- runtime.sceneGraphService.rotate(this, x, y, z);
- }
- return this;
- };
- _proto.setRotation = function setRotation(rotation, y, z, w) {
- runtime.sceneGraphService.setRotation(this, rotation, y, z, w);
- return this;
- };
- _proto.setLocalRotation = function setLocalRotation(rotation, y, z, w) {
- runtime.sceneGraphService.setLocalRotation(this, rotation, y, z, w);
- return this;
- };
- _proto.setLocalSkew = function setLocalSkew(skew, y) {
- runtime.sceneGraphService.setLocalSkew(this, skew, y);
- return this;
- };
- _proto.getRotation = function getRotation() {
- return runtime.sceneGraphService.getRotation(this);
- };
- _proto.getLocalRotation = function getLocalRotation() {
- return runtime.sceneGraphService.getLocalRotation(this);
- };
- _proto.getLocalSkew = function getLocalSkew() {
- return runtime.sceneGraphService.getLocalSkew(this);
- };
- _proto.getLocalTransform = function getLocalTransform() {
- return runtime.sceneGraphService.getLocalTransform(this);
- };
- _proto.getWorldTransform = function getWorldTransform() {
- return runtime.sceneGraphService.getWorldTransform(this);
- };
- _proto.setLocalTransform = function setLocalTransform(transform) {
- runtime.sceneGraphService.setLocalTransform(this, transform);
- return this;
- };
- _proto.resetLocalTransform = function resetLocalTransform() {
- runtime.sceneGraphService.resetLocalTransform(this);
- }
- // #endregion transformable
- // #region animatable
- /**
- * returns an array of all Animation objects affecting this element
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
- */;
- _proto.getAnimations = function getAnimations() {
- return this.activeAnimations;
- }
- /**
- * create an animation with WAAPI
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/animate
- */;
- _proto.animate = function animate(keyframes, options) {
- var _this$ownerDocument;
- var timeline = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.timeline;
- if (timeline) {
- return timeline.play(this, keyframes, options);
- }
- return null;
- }
- // #endregion animatable
- // #region visible
- /**
- * shortcut for Used value of `visibility`
- */;
- _proto.isVisible = function isVisible() {
- var _this$parsedStyle;
- return ((_this$parsedStyle = this.parsedStyle) === null || _this$parsedStyle === void 0 ? void 0 : _this$parsedStyle.visibility) === 'visible';
- };
- _proto.isInteractive = function isInteractive() {
- var _this$parsedStyle2;
- return ((_this$parsedStyle2 = this.parsedStyle) === null || _this$parsedStyle2 === void 0 ? void 0 : _this$parsedStyle2.pointerEvents) !== 'none';
- };
- _proto.isCulled = function isCulled() {
- return !!(this.cullable && this.cullable.enable && !this.cullable.visible);
- }
- /**
- * bring to front in current group
- */;
- _proto.toFront = function toFront() {
- if (this.parentNode) {
- this.style.zIndex = Math.max.apply(Math, this.parentNode.children.map(function (child) {
- return Number(child.style.zIndex);
- })) + 1;
- }
- return this;
- }
- /**
- * send to back in current group
- */;
- _proto.toBack = function toBack() {
- if (this.parentNode) {
- this.style.zIndex = Math.min.apply(Math, this.parentNode.children.map(function (child) {
- return Number(child.style.zIndex);
- })) - 1;
- }
- return this;
- }
- // #endregion visible
- // #region deprecated
- /**
- * compatible with G 3.0
- * @alias object.config
- * @deprecated
- */;
- _proto.getConfig = function getConfig() {
- return this.config;
- };
- _proto.attr = function attr() {
- var _this2 = this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- var name = args[0],
- value = args[1];
- if (!name) {
- return this.attributes;
- }
- if (isObject(name)) {
- Object.keys(name).forEach(function (key) {
- _this2.setAttribute(key, name[key]);
- });
- return this;
- }
- if (args.length === 2) {
- this.setAttribute(name, value);
- return this;
- }
- return this.attributes[name];
- }
- /**
- * return 3x3 matrix in world space
- * @deprecated
- */;
- _proto.getMatrix = function getMatrix(transformMat4) {
- var transform = transformMat4 || this.getWorldTransform();
- var _mat4$getTranslation = mat4.getTranslation(vec3.create(), transform),
- tx = _mat4$getTranslation[0],
- ty = _mat4$getTranslation[1];
- var _mat4$getScaling = mat4.getScaling(vec3.create(), transform),
- sx = _mat4$getScaling[0],
- sy = _mat4$getScaling[1];
- var rotation = mat4.getRotation(quat$1.create(), transform);
- var _getEuler3 = getEuler(vec3.create(), rotation),
- eux = _getEuler3[0],
- euz = _getEuler3[2];
- // gimbal lock at 90 degrees
- return fromRotationTranslationScale(eux || euz, tx, ty, sx, sy);
- }
- /**
- * return 3x3 matrix in local space
- * @deprecated
- */;
- _proto.getLocalMatrix = function getLocalMatrix() {
- return this.getMatrix(this.getLocalTransform());
- }
- /**
- * set 3x3 matrix in world space
- * @deprecated
- */;
- _proto.setMatrix = function setMatrix(mat) {
- var _decompose = decompose(mat),
- tx = _decompose[0],
- ty = _decompose[1],
- scalingX = _decompose[2],
- scalingY = _decompose[3],
- angle = _decompose[4];
- this.setEulerAngles(angle).setPosition(tx, ty).setLocalScale(scalingX, scalingY);
- }
- /**
- * set 3x3 matrix in local space
- * @deprecated
- */;
- _proto.setLocalMatrix = function setLocalMatrix(mat) {
- var _decompose2 = decompose(mat),
- tx = _decompose2[0],
- ty = _decompose2[1],
- scalingX = _decompose2[2],
- scalingY = _decompose2[3],
- angle = _decompose2[4];
- this.setLocalEulerAngles(angle).setLocalPosition(tx, ty).setLocalScale(scalingX, scalingY);
- }
- /**
- * Use `visibility: visible` instead.
- * @deprecated
- */;
- _proto.show = function show() {
- if (runtime.enableCSSParsing) {
- this.style.visibility = 'visible';
- } else {
- this.forEach(function (object) {
- object.style.visibility = 'visible';
- });
- }
- }
- /**
- * Use `visibility: hidden` instead.
- * @deprecated
- */;
- _proto.hide = function hide() {
- if (runtime.enableCSSParsing) {
- this.style.visibility = 'hidden';
- } else {
- this.forEach(function (object) {
- object.style.visibility = 'hidden';
- });
- }
- }
- /**
- * Use `childElementCount` instead.
- * @deprecated
- */;
- _proto.getCount = function getCount() {
- return this.childElementCount;
- }
- /**
- * Use `parentElement` instead.
- * @deprecated
- */;
- _proto.getParent = function getParent() {
- return this.parentElement;
- }
- /**
- * Use `children` instead.
- * @deprecated
- */;
- _proto.getChildren = function getChildren() {
- return this.children;
- }
- /**
- * Use `firstElementChild` instead.
- * @deprecated
- */;
- _proto.getFirst = function getFirst() {
- return this.firstElementChild;
- }
- /**
- * Use `lastElementChild` instead.
- * @deprecated
- */;
- _proto.getLast = function getLast() {
- return this.lastElementChild;
- }
- /**
- * Use `this.children[index]` instead.
- * @deprecated
- */;
- _proto.getChildByIndex = function getChildByIndex(index) {
- return this.children[index] || null;
- }
- /**
- * Use `appendChild` instead.
- * @deprecated
- */;
- _proto.add = function add(child, index) {
- return this.appendChild(child, index);
- }
- /**
- * Use `this.style.clipPath` instead.
- * @deprecated
- */;
- _proto.setClip = function setClip(clipPath) {
- this.style.clipPath = clipPath;
- };
- /**
- * @deprecated
- */
- _proto.set = function set(name, value) {
- // @ts-ignore
- this.config[name] = value;
- }
- /**
- * @deprecated
- */;
- _proto.get = function get(name) {
- return this.config[name];
- }
- /**
- * Use `setPosition` instead.
- * @deprecated
- */;
- _proto.moveTo = function moveTo(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- this.setPosition(position, y, z);
- return this;
- }
- /**
- * Use `setPosition` instead.
- * @deprecated
- */;
- _proto.move = function move(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- this.setPosition(position, y, z);
- return this;
- }
- /**
- * Use `this.style.zIndex` instead.
- * @deprecated
- */;
- _proto.setZIndex = function setZIndex(zIndex) {
- this.style.zIndex = zIndex;
- return this;
- };
- _createClass(DisplayObject, [{
- key: "interactive",
- get: function get() {
- return this.isInteractive();
- },
- set: function set(b) {
- this.style.pointerEvents = b ? 'auto' : 'none';
- }
- }]);
- return DisplayObject;
- }(Element);
- var _excluded = ["style"];
- var Circle = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Circle, _DisplayObject);
- function Circle(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded);
- return _DisplayObject.call(this, _extends({
- type: Shape.CIRCLE,
- style: runtime.enableCSSParsing ? _extends({
- cx: '',
- cy: '',
- r: ''
- }, style) : _extends({}, style),
- initialParsedStyle: {
- anchor: [0.5, 0.5],
- transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
- }
- }, rest)) || this;
- }
- return Circle;
- }(DisplayObject);
- var _excluded$1 = ["style"];
- /**
- * shadow root
- * @see https://yuque.antfin-inc.com/antv/czqvg5/pgqipg
- */
- var CustomElement = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(CustomElement, _DisplayObject);
- // private shadowNodes: DisplayObject[] = [];
- function CustomElement(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$1);
- _this = _DisplayObject.call(this, _extends({
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- // static get observedAttributes(): string[] {
- // return [];
- // }
- _this.isCustomElement = true;
- return _this;
- }
- return CustomElement;
- }(DisplayObject);
- var _excluded$2 = ["style"];
- var Ellipse = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Ellipse, _DisplayObject);
- function Ellipse(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$2);
- return _DisplayObject.call(this, _extends({
- type: Shape.ELLIPSE,
- style: runtime.enableCSSParsing ? _extends({
- cx: '',
- cy: '',
- rx: '',
- ry: ''
- }, style) : _extends({}, style),
- initialParsedStyle: {
- anchor: [0.5, 0.5],
- transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
- }
- }, rest)) || this;
- }
- return Ellipse;
- }(DisplayObject);
- var _excluded$3 = ["style"];
- /**
- * its attributes are inherited by its children.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g
- *
- * @example
- * <g fill="white" stroke="green" stroke-width="5">
- <circle cx="40" cy="40" r="25" />
- <circle cx="60" cy="60" r="25" />
- </g>
- */
- var Group = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Group, _DisplayObject);
- function Group(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$3);
- return _DisplayObject.call(this, _extends({
- type: Shape.GROUP,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- width: '',
- height: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- }
- return Group;
- }(DisplayObject);
- var _excluded$4 = ["style"];
- /**
- * HTML container
- * @see https://github.com/pmndrs/drei#html
- */
- var HTML = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(HTML, _DisplayObject);
- function HTML(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$4);
- _this = _DisplayObject.call(this, _extends({
- type: Shape.HTML,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- width: 'auto',
- height: 'auto',
- innerHTML: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- _this.cullable.enable = false;
- return _this;
- }
- /**
- * return wrapper HTMLElement
- * * <div> in g-webgl/canvas
- * * <foreignObject> in g-svg
- */
- var _proto = HTML.prototype;
- _proto.getDomElement = function getDomElement() {
- return this.parsedStyle.$el;
- }
- /**
- * override with $el.getBoundingClientRect
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
- */;
- _proto.getBoundingClientRect = function getBoundingClientRect() {
- return this.parsedStyle.$el.getBoundingClientRect();
- };
- _proto.getClientRects = function getClientRects() {
- return [this.getBoundingClientRect()];
- };
- _proto.getBounds = function getBounds() {
- var _this$ownerDocument, _this$ownerDocument$d;
- var clientRect = this.getBoundingClientRect();
- // calc context's offset
- // @ts-ignore
- 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();
- if (canvasRect) {
- var minX = clientRect.left - canvasRect.left;
- var minY = clientRect.top - canvasRect.top;
- var aabb = new AABB();
- // aabb.setMinMax(
- // vec3.fromValues(minX, minY, 0),
- // vec3.fromValues(minX + clientRect.width, minY + clientRect.height, 0),
- // );
- aabb.setMinMax([minX, minY, 0], [minX + clientRect.width, minY + clientRect.height, 0]);
- return aabb;
- }
- return null;
- };
- _proto.getLocalBounds = function getLocalBounds() {
- if (this.parentNode) {
- var parentInvert = mat4.invert(mat4.create(), this.parentNode.getWorldTransform());
- var bounds = this.getBounds();
- if (!AABB.isEmpty(bounds)) {
- var localBounds = new AABB();
- localBounds.setFromTransformedAABB(bounds, parentInvert);
- return localBounds;
- }
- }
- return this.getBounds();
- };
- return HTML;
- }(DisplayObject);
- var _excluded$5 = ["style"];
- var Image = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Image, _DisplayObject);
- function Image(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$5);
- return _DisplayObject.call(this, _extends({
- type: Shape.IMAGE,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- img: '',
- width: '',
- height: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- }
- return Image;
- }(DisplayObject);
- var _excluded$6 = ["style"];
- /**
- * Create a line connecting two points.
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line
- *
- * Also support for using marker.
- */
- var Line = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Line, _DisplayObject);
- function Line(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$6);
- _this = _DisplayObject.call(this, _extends({
- type: Shape.LINE,
- style: _extends({
- x1: 0,
- y1: 0,
- x2: 0,
- y2: 0,
- z1: 0,
- z2: 0,
- isBillboard: false
- }, style)
- }, rest)) || this;
- _this.markerStartAngle = 0;
- _this.markerEndAngle = 0;
- var _this$parsedStyle = _this.parsedStyle,
- markerStart = _this$parsedStyle.markerStart,
- markerEnd = _this$parsedStyle.markerEnd;
- if (markerStart && isDisplayObject(markerStart)) {
- _this.markerStartAngle = markerStart.getLocalEulerAngles();
- _this.appendChild(markerStart);
- }
- if (markerEnd && isDisplayObject(markerEnd)) {
- _this.markerEndAngle = markerEnd.getLocalEulerAngles();
- _this.appendChild(markerEnd);
- }
- _this.transformMarker(true);
- _this.transformMarker(false);
- return _this;
- }
- var _proto = Line.prototype;
- _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
- if (attrName === 'x1' || attrName === 'y1' || attrName === 'x2' || attrName === 'y2' || attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
- this.transformMarker(true);
- this.transformMarker(false);
- } else if (attrName === 'markerStart') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerStartAngle = 0;
- prevParsedValue.remove();
- }
- // CSSKeyword 'unset'
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerStartAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(true);
- }
- } else if (attrName === 'markerEnd') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerEndAngle = 0;
- prevParsedValue.remove();
- }
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerEndAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(false);
- }
- }
- };
- _proto.transformMarker = function transformMarker(isStart) {
- var _this$parsedStyle2 = this.parsedStyle,
- markerStart = _this$parsedStyle2.markerStart,
- markerEnd = _this$parsedStyle2.markerEnd,
- markerStartOffset = _this$parsedStyle2.markerStartOffset,
- markerEndOffset = _this$parsedStyle2.markerEndOffset,
- x1 = _this$parsedStyle2.x1,
- x2 = _this$parsedStyle2.x2,
- y1 = _this$parsedStyle2.y1,
- y2 = _this$parsedStyle2.y2,
- defX = _this$parsedStyle2.defX,
- defY = _this$parsedStyle2.defY;
- var marker = isStart ? markerStart : markerEnd;
- if (!marker || !isDisplayObject(marker)) {
- return;
- }
- var rad = 0;
- var x;
- var y;
- var ox;
- var oy;
- var offset;
- var originalAngle;
- if (isStart) {
- ox = x1 - defX;
- oy = y1 - defY;
- x = x2 - x1;
- y = y2 - y1;
- offset = markerStartOffset || 0;
- originalAngle = this.markerStartAngle;
- } else {
- ox = x2 - defX;
- oy = y2 - defY;
- x = x1 - x2;
- y = y1 - y2;
- offset = markerEndOffset || 0;
- originalAngle = this.markerEndAngle;
- }
- rad = Math.atan2(y, x);
- // account for markerOffset
- marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
- marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
- };
- _proto.getPoint = function getPoint(ratio, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- // TODO: account for z1/z2 in 3D line
- var _this$parsedStyle3 = this.parsedStyle,
- x1 = _this$parsedStyle3.x1,
- y1 = _this$parsedStyle3.y1,
- x2 = _this$parsedStyle3.x2,
- y2 = _this$parsedStyle3.y2,
- defX = _this$parsedStyle3.defX,
- defY = _this$parsedStyle3.defY;
- var _LineUtil$pointAt = Line$1.pointAt(x1, y1, x2, y2, ratio),
- x = _LineUtil$pointAt.x,
- y = _LineUtil$pointAt.y;
- var transformed = vec3.transformMat4(vec3.create(), vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
- // apply local transformation
- return new Point(transformed[0], transformed[1]);
- };
- _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
- };
- _proto.getTotalLength = function getTotalLength() {
- // TODO: account for z1/z2 in 3D line
- var _this$parsedStyle4 = this.parsedStyle,
- x1 = _this$parsedStyle4.x1,
- y1 = _this$parsedStyle4.y1,
- x2 = _this$parsedStyle4.x2,
- y2 = _this$parsedStyle4.y2;
- return Line$1.length(x1, y1, x2, y2);
- };
- return Line;
- }(DisplayObject);
- var _excluded$7 = ["style"];
- var EMPTY_PARSED_PATH = {
- absolutePath: [],
- hasArc: false,
- segments: [],
- polygons: [],
- polylines: [],
- curve: null,
- totalLength: 0,
- rect: new Rectangle(0, 0, 0, 0)
- };
- var Path = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Path, _DisplayObject);
- function Path(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$7);
- _this = _DisplayObject.call(this, _extends({
- type: Shape.PATH,
- style: runtime.enableCSSParsing ? _extends({
- path: '',
- miterLimit: ''
- }, style) : _extends({}, style),
- initialParsedStyle: runtime.enableCSSParsing ? null : {
- miterLimit: 4,
- path: _extends({}, EMPTY_PARSED_PATH)
- }
- }, rest)) || this;
- _this.markerStartAngle = 0;
- _this.markerEndAngle = 0;
- /**
- * markers placed at the mid
- */
- _this.markerMidList = [];
- var _this$parsedStyle = _this.parsedStyle,
- markerStart = _this$parsedStyle.markerStart,
- markerEnd = _this$parsedStyle.markerEnd,
- markerMid = _this$parsedStyle.markerMid;
- if (markerStart && isDisplayObject(markerStart)) {
- _this.markerStartAngle = markerStart.getLocalEulerAngles();
- _this.appendChild(markerStart);
- }
- if (markerMid && isDisplayObject(markerMid)) {
- _this.placeMarkerMid(markerMid);
- }
- if (markerEnd && isDisplayObject(markerEnd)) {
- _this.markerEndAngle = markerEnd.getLocalEulerAngles();
- _this.appendChild(markerEnd);
- }
- _this.transformMarker(true);
- _this.transformMarker(false);
- return _this;
- }
- var _proto = Path.prototype;
- _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
- if (attrName === 'path') {
- // recalc markers
- this.transformMarker(true);
- this.transformMarker(false);
- this.placeMarkerMid(this.parsedStyle.markerMid);
- } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
- this.transformMarker(true);
- this.transformMarker(false);
- } else if (attrName === 'markerStart') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerStartAngle = 0;
- prevParsedValue.remove();
- }
- // CSSKeyword 'unset'
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerStartAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(true);
- }
- } else if (attrName === 'markerEnd') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerEndAngle = 0;
- prevParsedValue.remove();
- }
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerEndAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(false);
- }
- } else if (attrName === 'markerMid') {
- this.placeMarkerMid(newParsedValue);
- }
- };
- _proto.transformMarker = function transformMarker(isStart) {
- var _this$parsedStyle2 = this.parsedStyle,
- markerStart = _this$parsedStyle2.markerStart,
- markerEnd = _this$parsedStyle2.markerEnd,
- markerStartOffset = _this$parsedStyle2.markerStartOffset,
- markerEndOffset = _this$parsedStyle2.markerEndOffset,
- defX = _this$parsedStyle2.defX,
- defY = _this$parsedStyle2.defY;
- var marker = isStart ? markerStart : markerEnd;
- if (!marker || !isDisplayObject(marker)) {
- return;
- }
- var rad = 0;
- var x;
- var y;
- var ox;
- var oy;
- var offset;
- var originalAngle;
- if (isStart) {
- var _this$getStartTangent = this.getStartTangent(),
- p1 = _this$getStartTangent[0],
- p2 = _this$getStartTangent[1];
- ox = p2[0] - defX;
- oy = p2[1] - defY;
- x = p1[0] - p2[0];
- y = p1[1] - p2[1];
- offset = markerStartOffset || 0;
- originalAngle = this.markerStartAngle;
- } else {
- var _this$getEndTangent = this.getEndTangent(),
- _p = _this$getEndTangent[0],
- _p2 = _this$getEndTangent[1];
- ox = _p2[0] - defX;
- oy = _p2[1] - defY;
- x = _p[0] - _p2[0];
- y = _p[1] - _p2[1];
- offset = markerEndOffset || 0;
- originalAngle = this.markerEndAngle;
- }
- rad = Math.atan2(y, x);
- // account for markerOffset
- marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
- marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
- };
- _proto.placeMarkerMid = function placeMarkerMid(marker) {
- var _this$parsedStyle3 = this.parsedStyle,
- segments = _this$parsedStyle3.path.segments,
- defX = _this$parsedStyle3.defX,
- defY = _this$parsedStyle3.defY;
- // clear all existed markers
- this.markerMidList.forEach(function (marker) {
- marker.remove();
- });
- if (marker && isDisplayObject(marker)) {
- for (var i = 1; i < segments.length - 1; i++) {
- var _segments$i$currentPo = segments[i].currentPoint,
- ox = _segments$i$currentPo[0],
- oy = _segments$i$currentPo[1];
- var cloned = i === 1 ? marker : marker.cloneNode(true);
- this.markerMidList.push(cloned);
- this.appendChild(cloned);
- cloned.setLocalPosition(ox - defX, oy - defY);
- // TODO: orient of marker
- }
- }
- }
- /**
- * Returns the total length of the path.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
- */;
- _proto.getTotalLength = function getTotalLength() {
- return getOrCalculatePathTotalLength(this);
- }
- /**
- * Returns the point at a given distance along the path.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getPointAtLength
- */;
- _proto.getPointAtLength = function getPointAtLength$1(distance, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- var _this$parsedStyle4 = this.parsedStyle,
- defX = _this$parsedStyle4.defX,
- defY = _this$parsedStyle4.defY,
- absolutePath = _this$parsedStyle4.path.absolutePath;
- var _getPointAtLength2 = getPointAtLength(absolutePath, distance),
- x = _getPointAtLength2.x,
- y = _getPointAtLength2.y;
- var transformed = vec3.transformMat4(vec3.create(), vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
- // apply local transformation
- return new Point(transformed[0], transformed[1]);
- }
- /**
- * Returns the point at a given ratio of the total length in path.
- */;
- _proto.getPoint = function getPoint(ratio, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- return this.getPointAtLength(ratio * getOrCalculatePathTotalLength(this), inWorldSpace);
- }
- /**
- * Get start tangent vector
- */;
- _proto.getStartTangent = function getStartTangent() {
- var segments = this.parsedStyle.path.segments;
- var result = [];
- if (segments.length > 1) {
- var startPoint = segments[0].currentPoint;
- var endPoint = segments[1].currentPoint;
- var tangent = segments[1].startTangent;
- result = [];
- if (tangent) {
- result.push([startPoint[0] - tangent[0], startPoint[1] - tangent[1]]);
- result.push([startPoint[0], startPoint[1]]);
- } else {
- result.push([endPoint[0], endPoint[1]]);
- result.push([startPoint[0], startPoint[1]]);
- }
- }
- return result;
- }
- /**
- * Get end tangent vector
- */;
- _proto.getEndTangent = function getEndTangent() {
- var segments = this.parsedStyle.path.segments;
- var length = segments.length;
- var result = [];
- if (length > 1) {
- var startPoint = segments[length - 2].currentPoint;
- var endPoint = segments[length - 1].currentPoint;
- var tangent = segments[length - 1].endTangent;
- result = [];
- if (tangent) {
- result.push([endPoint[0] - tangent[0], endPoint[1] - tangent[1]]);
- result.push([endPoint[0], endPoint[1]]);
- } else {
- result.push([startPoint[0], startPoint[1]]);
- result.push([endPoint[0], endPoint[1]]);
- }
- }
- return result;
- };
- return Path;
- }(DisplayObject);
- var _excluded$8 = ["style"];
- var Polygon = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Polygon, _DisplayObject);
- function Polygon(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$8);
- _this = _DisplayObject.call(this, _extends({
- type: Shape.POLYGON,
- style: runtime.enableCSSParsing ? _extends({
- points: '',
- miterLimit: '',
- isClosed: true
- }, style) : _extends({}, style),
- initialParsedStyle: runtime.enableCSSParsing ? null : {
- points: {
- points: [],
- totalLength: 0,
- segments: []
- },
- miterLimit: 4,
- isClosed: true
- }
- }, rest)) || this;
- _this.markerStartAngle = 0;
- _this.markerEndAngle = 0;
- /**
- * markers placed at the mid
- */
- _this.markerMidList = [];
- var _this$parsedStyle = _this.parsedStyle,
- markerStart = _this$parsedStyle.markerStart,
- markerEnd = _this$parsedStyle.markerEnd,
- markerMid = _this$parsedStyle.markerMid;
- if (markerStart && isDisplayObject(markerStart)) {
- _this.markerStartAngle = markerStart.getLocalEulerAngles();
- _this.appendChild(markerStart);
- }
- if (markerMid && isDisplayObject(markerMid)) {
- _this.placeMarkerMid(markerMid);
- }
- if (markerEnd && isDisplayObject(markerEnd)) {
- _this.markerEndAngle = markerEnd.getLocalEulerAngles();
- _this.appendChild(markerEnd);
- }
- _this.transformMarker(true);
- _this.transformMarker(false);
- return _this;
- }
- var _proto = Polygon.prototype;
- _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
- if (attrName === 'points') {
- // recalc markers
- this.transformMarker(true);
- this.transformMarker(false);
- this.placeMarkerMid(this.parsedStyle.markerMid);
- } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
- this.transformMarker(true);
- this.transformMarker(false);
- } else if (attrName === 'markerStart') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerStartAngle = 0;
- prevParsedValue.remove();
- }
- // CSSKeyword 'unset'
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerStartAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(true);
- }
- } else if (attrName === 'markerEnd') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerEndAngle = 0;
- prevParsedValue.remove();
- }
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerEndAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(false);
- }
- } else if (attrName === 'markerMid') {
- this.placeMarkerMid(newParsedValue);
- }
- };
- _proto.transformMarker = function transformMarker(isStart) {
- var _this$parsedStyle2 = this.parsedStyle,
- markerStart = _this$parsedStyle2.markerStart,
- markerEnd = _this$parsedStyle2.markerEnd,
- markerStartOffset = _this$parsedStyle2.markerStartOffset,
- markerEndOffset = _this$parsedStyle2.markerEndOffset,
- points = _this$parsedStyle2.points.points,
- defX = _this$parsedStyle2.defX,
- defY = _this$parsedStyle2.defY;
- var marker = isStart ? markerStart : markerEnd;
- if (!marker || !isDisplayObject(marker)) {
- return;
- }
- var rad = 0;
- var x;
- var y;
- var ox;
- var oy;
- var offset;
- var originalAngle;
- ox = points[0][0] - defX;
- oy = points[0][1] - defY;
- if (isStart) {
- x = points[1][0] - points[0][0];
- y = points[1][1] - points[0][1];
- offset = markerStartOffset || 0;
- originalAngle = this.markerStartAngle;
- } else {
- var length = points.length;
- if (!this.parsedStyle.isClosed) {
- ox = points[length - 1][0] - defX;
- oy = points[length - 1][1] - defY;
- x = points[length - 2][0] - points[length - 1][0];
- y = points[length - 2][1] - points[length - 1][1];
- } else {
- x = points[length - 1][0] - points[0][0];
- y = points[length - 1][1] - points[0][1];
- }
- offset = markerEndOffset || 0;
- originalAngle = this.markerEndAngle;
- }
- rad = Math.atan2(y, x);
- // account for markerOffset
- marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
- marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
- };
- _proto.placeMarkerMid = function placeMarkerMid(marker) {
- var _this$parsedStyle3 = this.parsedStyle,
- points = _this$parsedStyle3.points.points,
- defX = _this$parsedStyle3.defX,
- defY = _this$parsedStyle3.defY;
- // clear all existed markers
- this.markerMidList.forEach(function (marker) {
- marker.remove();
- });
- this.markerMidList = [];
- if (marker && isDisplayObject(marker)) {
- for (var i = 1; i < (this.parsedStyle.isClosed ? points.length : points.length - 1); i++) {
- var ox = points[i][0] - defX;
- var oy = points[i][1] - defY;
- var cloned = i === 1 ? marker : marker.cloneNode(true);
- this.markerMidList.push(cloned);
- this.appendChild(cloned);
- cloned.setLocalPosition(ox, oy);
- // TODO: orient of marker
- }
- }
- };
- return Polygon;
- }(DisplayObject);
- var _excluded$9 = ["style"];
- /**
- * Polyline inherits the marker-related capabilities of Polygon.
- */
- var Polyline = /*#__PURE__*/function (_Polygon) {
- _inheritsLoose(Polyline, _Polygon);
- function Polyline(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$9);
- return _Polygon.call(this, _extends({
- type: Shape.POLYLINE,
- style: runtime.enableCSSParsing ? _extends({
- points: '',
- miterLimit: '',
- isClosed: false
- }, style) : _extends({}, style),
- initialParsedStyle: runtime.enableCSSParsing ? null : {
- points: {
- points: [],
- totalLength: 0,
- segments: []
- },
- miterLimit: 4,
- isClosed: false
- }
- }, rest)) || this;
- }
- var _proto = Polyline.prototype;
- _proto.getTotalLength = function getTotalLength() {
- return this.parsedStyle.points.totalLength;
- };
- _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
- };
- _proto.getPoint = function getPoint(ratio, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- var _this$parsedStyle = this.parsedStyle,
- defX = _this$parsedStyle.defX,
- defY = _this$parsedStyle.defY,
- _this$parsedStyle$poi = _this$parsedStyle.points,
- points = _this$parsedStyle$poi.points,
- segments = _this$parsedStyle$poi.segments;
- var subt = 0;
- var index = 0;
- segments.forEach(function (v, i) {
- if (ratio >= v[0] && ratio <= v[1]) {
- subt = (ratio - v[0]) / (v[1] - v[0]);
- index = i;
- }
- });
- var _LineUtil$pointAt = Line$1.pointAt(points[index][0], points[index][1], points[index + 1][0], points[index + 1][1], subt),
- x = _LineUtil$pointAt.x,
- y = _LineUtil$pointAt.y;
- var transformed = vec3.transformMat4(vec3.create(), vec3.fromValues(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
- // apply local transformation
- return new Point(transformed[0], transformed[1]);
- };
- _proto.getStartTangent = function getStartTangent() {
- var points = this.parsedStyle.points.points;
- var result = [];
- result.push([points[1][0], points[1][1]]);
- result.push([points[0][0], points[0][1]]);
- return result;
- };
- _proto.getEndTangent = function getEndTangent() {
- var points = this.parsedStyle.points.points;
- var l = points.length - 1;
- var result = [];
- result.push([points[l - 1][0], points[l - 1][1]]);
- result.push([points[l][0], points[l][1]]);
- return result;
- };
- return Polyline;
- }(Polygon);
- var _excluded$a = ["style"];
- var Rect = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Rect, _DisplayObject);
- function Rect(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$a);
- return _DisplayObject.call(this, _extends({
- type: Shape.RECT,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- width: '',
- height: '',
- radius: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- }
- return Rect;
- }(DisplayObject);
- var _excluded$b = ["style"];
- /**
- * <text> @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextElement
- */
- var Text = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Text, _DisplayObject);
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement#constants
- */
- // LENGTHADJUST_SPACING: number = 1;
- // LENGTHADJUST_SPACINGANDGLYPHS: number = 2;
- // LENGTHADJUST_UNKNOWN: number = 0;
- function Text(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$b);
- return _DisplayObject.call(this, _extends({
- type: Shape.TEXT,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- text: '',
- fontSize: '',
- fontFamily: '',
- fontStyle: '',
- fontWeight: '',
- fontVariant: '',
- textAlign: '',
- textBaseline: '',
- textTransform: '',
- fill: 'black',
- letterSpacing: '',
- lineHeight: '',
- miterLimit: '',
- // whiteSpace: 'pre',
- wordWrap: false,
- wordWrapWidth: 0,
- leading: 0,
- dx: '',
- dy: '',
- isBillboard: false,
- sizeAttenuation: true
- }, style) : _extends({
- fill: 'black'
- }, style),
- initialParsedStyle: runtime.enableCSSParsing ? {} : {
- x: 0,
- y: 0,
- fontSize: 16,
- fontFamily: 'sans-serif',
- fontStyle: 'normal',
- fontWeight: 'normal',
- fontVariant: 'normal',
- lineHeight: 0,
- letterSpacing: 0,
- textBaseline: 'alphabetic',
- textAlign: 'start',
- wordWrap: false,
- wordWrapWidth: 0,
- leading: 0,
- dx: 0,
- dy: 0,
- isBillboard: false,
- sizeAttenuation: true
- }
- }, rest)) || this;
- }
- // lengthAdjust: SVGAnimatedEnumeration;
- // textLength: SVGAnimatedLength;
- // getCharNumAtPosition(point?: DOMPointInit): number {
- // throw new Error('Method not implemented.');
- // }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement
- */
- var _proto = Text.prototype;
- _proto.getComputedTextLength = function getComputedTextLength() {
- var _this$parsedStyle$met;
- return ((_this$parsedStyle$met = this.parsedStyle.metrics) === null || _this$parsedStyle$met === void 0 ? void 0 : _this$parsedStyle$met.maxLineWidth) || 0;
- }
- // getEndPositionOfChar(charnum: number): DOMPoint {
- // throw new Error('Method not implemented.');
- // }
- // getExtentOfChar(charnum: number): DOMRect {
- // throw new Error('Method not implemented.');
- // }
- // getNumberOfChars(): number {
- // throw new Error('Method not implemented.');
- // }
- // getRotationOfChar(charnum: number): number {
- // throw new Error('Method not implemented.');
- // }
- // getStartPositionOfChar(charnum: number): DOMPoint {
- // throw new Error('Method not implemented.');
- // }
- // getSubStringLength(charnum: number, nchars: number): number {
- // throw new Error('Method not implemented.');
- // }
- // selectSubString(charnum: number, nchars: number): void {
- // throw new Error('Method not implemented.');
- // }
- ;
- _proto.getLineBoundingRects = function getLineBoundingRects() {
- var _this$parsedStyle$met2;
- return ((_this$parsedStyle$met2 = this.parsedStyle.metrics) === null || _this$parsedStyle$met2 === void 0 ? void 0 : _this$parsedStyle$met2.lineMetrics) || [];
- };
- _proto.isOverflowing = function isOverflowing() {
- return !!this.parsedStyle.isOverflowing;
- };
- return Text;
- }(DisplayObject);
- /**
- * Blink used them in code generation(css_properties.json5)
- */
- var BUILT_IN_PROPERTIES = [{
- /**
- * used in CSS Layout API
- * eg. `display: 'flex'`
- */
- n: 'display',
- k: ['none']
- }, {
- /**
- * range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity
- */
- n: 'opacity',
- int: true,
- inh: true,
- d: '1',
- syntax: PropertySyntax.OPACITY_VALUE
- }, {
- /**
- * inheritable, range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity
- * @see https://svgwg.org/svg2-draft/painting.html#FillOpacity
- */
- n: 'fillOpacity',
- int: true,
- inh: true,
- d: '1',
- syntax: PropertySyntax.OPACITY_VALUE
- }, {
- /**
- * inheritable, range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity
- * @see https://svgwg.org/svg2-draft/painting.html#StrokeOpacity
- */
- n: 'strokeOpacity',
- int: true,
- inh: true,
- d: '1',
- syntax: PropertySyntax.OPACITY_VALUE
- }, {
- /**
- * background-color is not inheritable
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
- */
- n: 'fill',
- int: true,
- k: ['none'],
- d: 'none',
- syntax: PropertySyntax.PAINT
- }, {
- n: 'fillRule',
- k: ['nonzero', 'evenodd'],
- d: 'nonzero'
- },
- /**
- * default to none
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke#usage_notes
- */
- {
- n: 'stroke',
- int: true,
- k: ['none'],
- d: 'none',
- syntax: PropertySyntax.PAINT,
- /**
- * Stroke 'none' won't affect geometry but others will.
- */
- l: true
- }, {
- n: 'shadowType',
- k: ['inner', 'outer', 'both'],
- d: 'outer',
- l: true
- }, {
- n: 'shadowColor',
- int: true,
- syntax: PropertySyntax.COLOR
- }, {
- n: 'shadowOffsetX',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'shadowOffsetY',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'shadowBlur',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.SHADOW_BLUR
- }, {
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width
- */
- n: 'lineWidth',
- int: true,
- inh: true,
- d: '1',
- l: true,
- a: ['strokeWidth'],
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'increasedLineWidthForHitTesting',
- inh: true,
- d: '0',
- l: true,
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'lineJoin',
- inh: true,
- l: true,
- a: ['strokeLinejoin'],
- k: ['miter', 'bevel', 'round'],
- d: 'miter'
- }, {
- n: 'lineCap',
- inh: true,
- l: true,
- a: ['strokeLinecap'],
- k: ['butt', 'round', 'square'],
- d: 'butt'
- }, {
- n: 'lineDash',
- int: true,
- inh: true,
- k: ['none'],
- a: ['strokeDasharray'],
- syntax: PropertySyntax.LENGTH_PERCENTAGE_12
- }, {
- n: 'lineDashOffset',
- int: true,
- inh: true,
- d: '0',
- a: ['strokeDashoffset'],
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'offsetPath',
- syntax: PropertySyntax.DEFINED_PATH
- }, {
- n: 'offsetDistance',
- int: true,
- syntax: PropertySyntax.OFFSET_DISTANCE
- }, {
- n: 'dx',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'dy',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'zIndex',
- ind: true,
- int: true,
- d: '0',
- k: ['auto'],
- syntax: PropertySyntax.Z_INDEX
- }, {
- n: 'visibility',
- k: ['visible', 'hidden'],
- ind: true,
- inh: true,
- /**
- * support interpolation
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#interpolation
- */
- int: true,
- d: 'visible'
- }, {
- n: 'pointerEvents',
- inh: true,
- k: ['none', 'auto', 'stroke', 'fill', 'painted', 'visible', 'visiblestroke', 'visiblefill', 'visiblepainted',
- // 'bounding-box',
- 'all'],
- d: 'auto'
- }, {
- n: 'filter',
- ind: true,
- l: true,
- k: ['none'],
- d: 'none',
- syntax: PropertySyntax.FILTER
- }, {
- n: 'clipPath',
- syntax: PropertySyntax.DEFINED_PATH
- }, {
- n: 'textPath',
- syntax: PropertySyntax.DEFINED_PATH
- }, {
- n: 'textPathSide',
- k: ['left', 'right'],
- d: 'left'
- }, {
- n: 'textPathStartOffset',
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'transform',
- p: 100,
- int: true,
- k: ['none'],
- d: 'none',
- syntax: PropertySyntax.TRANSFORM
- }, {
- n: 'transformOrigin',
- p: 100,
- // int: true,
- d: function d(nodeName) {
- if (nodeName === Shape.CIRCLE || nodeName === Shape.ELLIPSE) {
- return 'center';
- }
- if (nodeName === Shape.TEXT) {
- return 'text-anchor';
- }
- return 'left top';
- },
- l: true,
- syntax: PropertySyntax.TRANSFORM_ORIGIN
- }, {
- n: 'anchor',
- p: 99,
- d: function d(nodeName) {
- if (nodeName === Shape.CIRCLE || nodeName === Shape.ELLIPSE) {
- return '0.5 0.5';
- }
- return '0 0';
- },
- l: true,
- syntax: PropertySyntax.LENGTH_PERCENTAGE_12
- },
- // <circle> & <ellipse>
- {
- n: 'cx',
- int: true,
- d: '0',
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'cy',
- int: true,
- d: '0',
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'cz',
- int: true,
- d: '0',
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'r',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'rx',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'ry',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- },
- // Rect Image Group
- {
- // x in local space
- n: 'x',
- int: true,
- d: '0',
- syntax: PropertySyntax.COORDINATE
- }, {
- // y in local space
- n: 'y',
- int: true,
- d: '0',
- syntax: PropertySyntax.COORDINATE
- }, {
- // z in local space
- n: 'z',
- int: true,
- d: '0',
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'width',
- int: true,
- l: true,
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
- */
- k: ['auto', 'fit-content', 'min-content', 'max-content'],
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'height',
- int: true,
- l: true,
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/height
- */
- k: ['auto', 'fit-content', 'min-content', 'max-content'],
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'radius',
- int: true,
- l: true,
- d: '0',
- syntax: PropertySyntax.LENGTH_PERCENTAGE_14
- },
- // Line
- {
- n: 'x1',
- int: true,
- l: true,
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'y1',
- int: true,
- l: true,
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'z1',
- int: true,
- l: true,
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'x2',
- int: true,
- l: true,
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'y2',
- int: true,
- l: true,
- syntax: PropertySyntax.COORDINATE
- }, {
- n: 'z2',
- int: true,
- l: true,
- syntax: PropertySyntax.COORDINATE
- },
- // Path
- {
- n: 'path',
- int: true,
- l: true,
- d: '',
- a: ['d'],
- syntax: PropertySyntax.PATH,
- p: 50
- },
- // Polyline & Polygon
- {
- n: 'points',
- /**
- * support interpolation
- */
- int: true,
- l: true,
- syntax: PropertySyntax.LIST_OF_POINTS,
- p: 50
- },
- // Text
- {
- n: 'text',
- l: true,
- d: '',
- syntax: PropertySyntax.TEXT,
- p: 50
- }, {
- n: 'textTransform',
- l: true,
- inh: true,
- k: ['capitalize', 'uppercase', 'lowercase', 'none'],
- d: 'none',
- syntax: PropertySyntax.TEXT_TRANSFORM,
- p: 51 // it must get parsed after text
- }, {
- n: 'font',
- l: true
- }, {
- n: 'fontSize',
- int: true,
- inh: true,
- /**
- * @see https://www.w3schools.com/css/css_font_size.asp
- */
- d: '16px',
- l: true,
- syntax: PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'fontFamily',
- l: true,
- inh: true,
- d: 'sans-serif'
- }, {
- n: 'fontStyle',
- l: true,
- inh: true,
- k: ['normal', 'italic', 'oblique'],
- d: 'normal'
- }, {
- n: 'fontWeight',
- l: true,
- inh: true,
- k: ['normal', 'bold', 'bolder', 'lighter'],
- d: 'normal'
- }, {
- n: 'fontVariant',
- l: true,
- inh: true,
- k: ['normal', 'small-caps'],
- d: 'normal'
- }, {
- n: 'lineHeight',
- l: true,
- syntax: PropertySyntax.LENGTH,
- int: true,
- d: '0'
- }, {
- n: 'letterSpacing',
- l: true,
- syntax: PropertySyntax.LENGTH,
- int: true,
- d: '0'
- }, {
- n: 'miterLimit',
- l: true,
- syntax: PropertySyntax.NUMBER,
- d: function d(nodeName) {
- if (nodeName === Shape.PATH || nodeName === Shape.POLYGON || nodeName === Shape.POLYLINE) {
- return '4';
- }
- return '10';
- }
- }, {
- n: 'wordWrap',
- l: true
- }, {
- n: 'wordWrapWidth',
- l: true
- }, {
- n: 'maxLines',
- l: true
- }, {
- n: 'textOverflow',
- l: true,
- d: 'clip'
- }, {
- n: 'leading',
- l: true
- }, {
- n: 'textBaseline',
- l: true,
- inh: true,
- k: ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'],
- d: 'alphabetic'
- }, {
- n: 'textAlign',
- l: true,
- inh: true,
- k: ['start', 'center', 'middle', 'end', 'left', 'right'],
- d: 'start'
- },
- // {
- // n: 'whiteSpace',
- // l: true,
- // },
- {
- n: 'markerStart',
- syntax: PropertySyntax.MARKER
- }, {
- n: 'markerEnd',
- syntax: PropertySyntax.MARKER
- }, {
- n: 'markerMid',
- syntax: PropertySyntax.MARKER
- }, {
- n: 'markerStartOffset',
- syntax: PropertySyntax.LENGTH,
- l: true,
- int: true,
- d: '0'
- }, {
- n: 'markerEndOffset',
- syntax: PropertySyntax.LENGTH,
- l: true,
- int: true,
- d: '0'
- }];
- var GEOMETRY_ATTRIBUTE_NAMES = BUILT_IN_PROPERTIES.filter(function (n) {
- return !!n.l;
- }).map(function (n) {
- return n.n;
- });
- var propertyMetadataCache = {};
- var unresolvedProperties = new WeakMap();
- // const uniqueAttributeSet = new Set<string>();
- // const tmpVec3a = vec3.create();
- // const tmpVec3b = vec3.create();
- // const tmpVec3c = vec3.create();
- var isPropertyResolved = function isPropertyResolved(object, name) {
- var properties = unresolvedProperties.get(object);
- if (!properties || properties.length === 0) {
- return true;
- }
- return properties.includes(name);
- };
- var DefaultStyleValueRegistry = /*#__PURE__*/function () {
- /**
- * need recalc later
- */
- // dirty = false;
- function DefaultStyleValueRegistry() {
- var _this = this;
- BUILT_IN_PROPERTIES.forEach(function (property) {
- _this.registerMetadata(property);
- });
- }
- var _proto = DefaultStyleValueRegistry.prototype;
- _proto.registerMetadata = function registerMetadata(metadata) {
- [metadata.n].concat(metadata.a || []).forEach(function (name) {
- propertyMetadataCache[name] = metadata;
- });
- };
- _proto.unregisterMetadata = function unregisterMetadata(name) {
- delete propertyMetadataCache[name];
- };
- _proto.getPropertySyntax = function getPropertySyntax(syntax) {
- return runtime.CSSPropertySyntaxFactory[syntax];
- }
- /**
- * * parse value, eg.
- * fill: 'red' => CSSRGB
- * translateX: '10px' => CSSUnitValue { unit: 'px', value: 10 }
- * fontSize: '2em' => { unit: 'px', value: 32 }
- *
- * * calculate used value
- * * post process
- */;
- _proto.processProperties = function processProperties(object, attributes, options) {
- var _this2 = this;
- if (options === void 0) {
- options = {
- skipUpdateAttribute: false,
- skipParse: false,
- forceUpdateGeometry: false,
- usedAttributes: []
- };
- }
- if (!runtime.enableCSSParsing) {
- Object.assign(object.attributes, attributes);
- var _attributeNames = Object.keys(attributes);
- // clipPath
- var oldClipPath = object.parsedStyle.clipPath;
- var oldOffsetPath = object.parsedStyle.offsetPath;
- object.parsedStyle = Object.assign(object.parsedStyle, attributes);
- var _needUpdateGeometry = !!options.forceUpdateGeometry;
- if (!_needUpdateGeometry) {
- for (var i = 0; i < GEOMETRY_ATTRIBUTE_NAMES.length; i++) {
- if (GEOMETRY_ATTRIBUTE_NAMES[i] in attributes) {
- _needUpdateGeometry = true;
- break;
- }
- }
- }
- if (attributes.fill) {
- object.parsedStyle.fill = parseColor(attributes.fill);
- }
- if (attributes.stroke) {
- object.parsedStyle.stroke = parseColor(attributes.stroke);
- }
- if (attributes.shadowColor) {
- object.parsedStyle.shadowColor = parseColor(attributes.shadowColor);
- }
- if (attributes.filter) {
- object.parsedStyle.filter = parseFilter(attributes.filter);
- }
- // Rect
- // @ts-ignore
- if (!isNil(attributes.radius)) {
- // @ts-ignore
- object.parsedStyle.radius = parseDimensionArrayFormat(
- // @ts-ignore
- attributes.radius, 4);
- }
- // Polyline
- if (!isNil(attributes.lineDash)) {
- object.parsedStyle.lineDash = parseDimensionArrayFormat(attributes.lineDash, 2);
- }
- // @ts-ignore
- if (attributes.points) {
- // @ts-ignore
- object.parsedStyle.points = parsePoints(attributes.points, object);
- }
- // Path
- // @ts-ignore
- if (attributes.path === '') {
- object.parsedStyle.path = _extends({}, EMPTY_PARSED_PATH);
- }
- // @ts-ignore
- if (attributes.path) {
- object.parsedStyle.path = parsePath(
- // @ts-ignore
- attributes.path, object);
- }
- // Text
- if (attributes.textTransform) {
- runtime.CSSPropertySyntaxFactory['<text-transform>'].calculator(null, null, {
- value: attributes.textTransform
- }, object, null);
- }
- if (attributes.clipPath) {
- runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('clipPath', oldClipPath, attributes.clipPath, object, this);
- }
- if (attributes.offsetPath) {
- runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('offsetPath', oldOffsetPath, attributes.offsetPath, object, this);
- }
- if (attributes.anchor) {
- object.parsedStyle.anchor = parseDimensionArrayFormat(
- // @ts-ignorex
- attributes.anchor, 2);
- }
- if (attributes.transform) {
- object.parsedStyle.transform = parseTransform(attributes.transform);
- }
- if (attributes.transformOrigin) {
- object.parsedStyle.transformOrigin = parseTransformOrigin(attributes.transformOrigin);
- }
- // Marker
- // @ts-ignore
- if (attributes.markerStart) {
- // @ts-ignore
- object.parsedStyle.markerStart = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
- // @ts-ignore
- attributes.markerStart,
- // @ts-ignore
- attributes.markerStart, null, null);
- }
- // @ts-ignore
- if (attributes.markerEnd) {
- // @ts-ignore
- object.parsedStyle.markerEnd = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
- // @ts-ignore
- attributes.markerEnd,
- // @ts-ignore
- attributes.markerEnd, null, null);
- }
- // @ts-ignore
- if (attributes.markerMid) {
- // @ts-ignore
- object.parsedStyle.markerMid = runtime.CSSPropertySyntaxFactory['<marker>'].calculator('',
- // @ts-ignore
- attributes.markerMid,
- // @ts-ignore
- attributes.markerMid, null, null);
- }
- if (
- // Circle & Ellipse
- (object.nodeName === Shape.CIRCLE || object.nodeName === Shape.ELLIPSE) && (
- // @ts-ignore
- !isNil(attributes.cx) ||
- // @ts-ignore
- !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) && (
- // @ts-ignore
- !isNil(attributes.x) ||
- // @ts-ignore
- !isNil(attributes.y) ||
- // @ts-ignore
- !isNil(attributes.z)) ||
- // Line
- object.nodeName === Shape.LINE && (
- // @ts-ignore
- !isNil(attributes.x1) ||
- // @ts-ignore
- !isNil(attributes.y1) ||
- // @ts-ignore
- !isNil(attributes.z1) ||
- // @ts-ignore
- !isNil(attributes.x2) ||
- // @ts-ignore
- !isNil(attributes.y2) ||
- // @ts-ignore
- !isNil(attributes.z2))) {
- runtime.CSSPropertySyntaxFactory['<coordinate>'].postProcessor(object, _attributeNames);
- }
- if (!isNil(attributes.zIndex)) {
- runtime.CSSPropertySyntaxFactory['<z-index>'].postProcessor(object, _attributeNames);
- }
- // @ts-ignore
- if (attributes.path) {
- runtime.CSSPropertySyntaxFactory['<path>'].postProcessor(object, _attributeNames);
- }
- // @ts-ignore
- if (attributes.points) {
- runtime.CSSPropertySyntaxFactory['<list-of-points>'].postProcessor(object, _attributeNames);
- }
- if (!isNil(attributes.offsetDistance)) {
- runtime.CSSPropertySyntaxFactory['<offset-distance>'].postProcessor(object, _attributeNames);
- }
- if (attributes.transform) {
- runtime.CSSPropertySyntaxFactory['<transform>'].postProcessor(object, _attributeNames);
- }
- if (_needUpdateGeometry) {
- this.updateGeometry(object);
- }
- return;
- }
- var _options = options,
- skipUpdateAttribute = _options.skipUpdateAttribute,
- skipParse = _options.skipParse,
- forceUpdateGeometry = _options.forceUpdateGeometry,
- usedAttributes = _options.usedAttributes;
- var needUpdateGeometry = forceUpdateGeometry;
- var attributeNames = Object.keys(attributes);
- attributeNames.forEach(function (attributeName) {
- var _propertyMetadataCach;
- if (!skipUpdateAttribute) {
- object.attributes[attributeName] = attributes[attributeName];
- }
- if (!needUpdateGeometry && ((_propertyMetadataCach = propertyMetadataCache[attributeName]) === null || _propertyMetadataCach === void 0 ? void 0 : _propertyMetadataCach.l)) {
- needUpdateGeometry = true;
- }
- });
- if (!skipParse) {
- attributeNames.forEach(function (name) {
- object.computedStyle[name] = _this2.parseProperty(name, object.attributes[name], object);
- });
- }
- // let hasUnresolvedProperties = false;
- // parse according to priority
- // path 50
- // points 50
- // text 50
- // textTransform 51
- // anchor 99
- // transform 100
- // transformOrigin 100
- if (usedAttributes === null || usedAttributes === void 0 ? void 0 : usedAttributes.length) {
- // uniqueAttributeSet.clear();
- attributeNames = Array.from(new Set(attributeNames.concat(usedAttributes)));
- }
- // [
- // 'path',
- // 'points',
- // 'text',
- // 'textTransform',
- // 'anchor',
- // 'transform',
- // 'transformOrigin',
- // ].forEach((name) => {
- // const index = attributeNames.indexOf(name);
- // if (index > -1) {
- // attributeNames.splice(index, 1);
- // attributeNames.push(name);
- // }
- // });
- attributeNames.forEach(function (name) {
- // some style props maybe deleted after parsing such as `anchor` in Text
- if (name in object.computedStyle) {
- object.parsedStyle[name] = _this2.computeProperty(name, object.computedStyle[name], object);
- }
- });
- // if (hasUnresolvedProperties) {
- // this.dirty = true;
- // return;
- // }
- // update geometry
- if (needUpdateGeometry) {
- // object.geometry.dirty = true;
- // runtime.sceneGraphService.dirtifyToRoot(object);
- this.updateGeometry(object);
- }
- attributeNames.forEach(function (name) {
- if (name in object.parsedStyle) {
- _this2.postProcessProperty(name, object, attributeNames);
- }
- });
- if (runtime.enableCSSParsing && object.children.length) {
- attributeNames.forEach(function (name) {
- if (name in object.parsedStyle && _this2.isPropertyInheritable(name)) {
- // update children's inheritable
- object.children.forEach(function (child) {
- child.internalSetAttribute(name, null, {
- skipUpdateAttribute: true,
- skipParse: true
- });
- });
- }
- });
- }
- }
- /**
- * string -> parsed value
- */;
- _proto.parseProperty = function parseProperty(name, value, object) {
- var metadata = propertyMetadataCache[name];
- var computed = value;
- if (value === '' || isNil(value)) {
- value = 'unset';
- }
- if (value === 'unset' || value === 'initial' || value === 'inherit') {
- // computed = new CSSKeywordValue(value);
- computed = getOrCreateKeyword(value);
- } else {
- if (metadata) {
- var keywords = metadata.k,
- syntax = metadata.syntax;
- var handler = syntax && this.getPropertySyntax(syntax);
- // use keywords
- if (keywords && keywords.indexOf(value) > -1) {
- // computed = new CSSKeywordValue(value);
- computed = getOrCreateKeyword(value);
- } else if (handler && handler.parser) {
- // try to parse it to CSSStyleValue, eg. '10px' -> CSS.px(10)
- computed = handler.parser(value, object);
- }
- }
- }
- return computed;
- }
- /**
- * computed value -> used value
- */;
- _proto.computeProperty = function computeProperty(name, computed, object) {
- var metadata = propertyMetadataCache[name];
- var isDocumentElement = object.id === 'g-root';
- // let used: CSSStyleValue = computed instanceof CSSStyleValue ? computed.clone() : computed;
- var used = computed;
- if (metadata) {
- var syntax = metadata.syntax,
- inherited = metadata.inh,
- defaultValue = metadata.d;
- if (computed instanceof CSSKeywordValue) {
- var value = computed.value;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/unset
- */
- if (value === 'unset') {
- if (inherited && !isDocumentElement) {
- value = 'inherit';
- } else {
- value = 'initial';
- }
- }
- if (value === 'initial') {
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial
- if (!isNil(defaultValue)) {
- computed = this.parseProperty(name, isFunction(defaultValue) ? defaultValue(object.nodeName) : defaultValue, object);
- }
- } else if (value === 'inherit') {
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/inherit
- // behave like `inherit`
- var resolved = this.tryToResolveProperty(object, name, {
- inherited: true
- });
- if (!isNil(resolved)) {
- // object.parsedStyle[name] = resolved;
- // return false;
- return resolved;
- } else {
- this.addUnresolveProperty(object, name);
- return;
- }
- }
- }
- var handler = syntax && this.getPropertySyntax(syntax);
- if (handler && handler.calculator) {
- // convert computed value to used value
- var oldParsedValue = object.parsedStyle[name];
- used = handler.calculator(name, oldParsedValue, computed, object, this);
- } else if (computed instanceof CSSKeywordValue) {
- used = computed.value;
- } else {
- used = computed;
- }
- }
- // object.parsedStyle[name] = used;
- // return false;
- return used;
- };
- _proto.postProcessProperty = function postProcessProperty(name, object, attributes) {
- var metadata = propertyMetadataCache[name];
- if (metadata && metadata.syntax) {
- var handler = metadata.syntax && this.getPropertySyntax(metadata.syntax);
- var propertyHandler = handler;
- if (propertyHandler && propertyHandler.postProcessor) {
- propertyHandler.postProcessor(object, attributes);
- }
- }
- }
- /**
- * resolve later
- */;
- _proto.addUnresolveProperty = function addUnresolveProperty(object, name) {
- var properties = unresolvedProperties.get(object);
- if (!properties) {
- unresolvedProperties.set(object, []);
- properties = unresolvedProperties.get(object);
- }
- if (properties.indexOf(name) === -1) {
- properties.push(name);
- }
- };
- _proto.tryToResolveProperty = function tryToResolveProperty(object, name, options) {
- if (options === void 0) {
- options = {};
- }
- var _options2 = options,
- inherited = _options2.inherited;
- if (inherited) {
- if (object.parentElement && isPropertyResolved(object.parentElement, name)) {
- // const computedValue = object.parentElement.computedStyle[name];
- var usedValue = object.parentElement.parsedStyle[name];
- if (
- // usedValue instanceof CSSKeywordValue &&
- usedValue === 'unset' || usedValue === 'initial' || usedValue === 'inherit') {
- return;
- }
- // else if (
- // usedValue instanceof CSSUnitValue &&
- // CSSUnitValue.isRelativeUnit(usedValue.unit)
- // ) {
- // return false;
- // }
- return usedValue;
- }
- }
- return;
- };
- _proto.recalc = function recalc(object) {
- var properties = unresolvedProperties.get(object);
- if (properties && properties.length) {
- var attributes = {};
- properties.forEach(function (property) {
- attributes[property] = object.attributes[property];
- });
- this.processProperties(object, attributes);
- unresolvedProperties.delete(object);
- }
- }
- /**
- * update geometry when relative props changed,
- * eg. r of Circle, width/height of Rect
- */;
- _proto.updateGeometry = function updateGeometry(object) {
- var nodeName = object.nodeName;
- var geometryUpdater = runtime.geometryUpdaterFactory[nodeName];
- if (geometryUpdater) {
- var geometry = object.geometry;
- if (!geometry.contentBounds) {
- geometry.contentBounds = new AABB();
- }
- if (!geometry.renderBounds) {
- geometry.renderBounds = new AABB();
- }
- var parsedStyle = object.parsedStyle;
- var _geometryUpdater$upda = geometryUpdater.update(parsedStyle, object),
- width = _geometryUpdater$upda.width,
- height = _geometryUpdater$upda.height,
- _geometryUpdater$upda2 = _geometryUpdater$upda.depth,
- depth = _geometryUpdater$upda2 === void 0 ? 0 : _geometryUpdater$upda2,
- _geometryUpdater$upda3 = _geometryUpdater$upda.offsetX,
- offsetX = _geometryUpdater$upda3 === void 0 ? 0 : _geometryUpdater$upda3,
- _geometryUpdater$upda4 = _geometryUpdater$upda.offsetY,
- offsetY = _geometryUpdater$upda4 === void 0 ? 0 : _geometryUpdater$upda4,
- _geometryUpdater$upda5 = _geometryUpdater$upda.offsetZ,
- offsetZ = _geometryUpdater$upda5 === void 0 ? 0 : _geometryUpdater$upda5;
- // init with content box
- var halfExtents = [Math.abs(width) / 2, Math.abs(height) / 2, depth / 2];
- // const halfExtents = vec3.set(
- // tmpVec3a,
- // Math.abs(width) / 2,
- // Math.abs(height) / 2,
- // depth / 2,
- // );
- // anchor is center by default, don't account for lineWidth here
- var stroke = parsedStyle.stroke,
- lineWidth = parsedStyle.lineWidth,
- increasedLineWidthForHitTesting = parsedStyle.increasedLineWidthForHitTesting,
- shadowType = parsedStyle.shadowType,
- shadowColor = parsedStyle.shadowColor,
- _parsedStyle$filter = parsedStyle.filter,
- filter = _parsedStyle$filter === void 0 ? [] : _parsedStyle$filter,
- transformOrigin = parsedStyle.transformOrigin;
- var anchor = parsedStyle.anchor;
- // <Text> use textAlign & textBaseline instead of anchor
- if (nodeName === Shape.TEXT) {
- delete parsedStyle.anchor;
- } else if (nodeName === Shape.MESH) {
- parsedStyle.anchor[2] = 0.5;
- }
- 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];
- // const center = vec3.set(
- // tmpVec3b,
- // ((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,
- // );
- // update geometry's AABB
- geometry.contentBounds.update(center, halfExtents);
- // @see https://github.molgen.mpg.de/git-mirror/cairo/blob/master/src/cairo-stroke-style.c#L97..L128
- var expansion = nodeName === Shape.POLYLINE || nodeName === Shape.POLYGON || nodeName === Shape.PATH ? Math.SQRT2 : 0.5;
- // if (lineCap?.value === 'square') {
- // expansion = Math.SQRT1_2;
- // }
- // if (lineJoin?.value === 'miter' && expansion < Math.SQRT2 * miterLimit) {
- // expansion = Math.SQRT1_2 * miterLimit;
- // }
- // append border only if stroke existed
- var hasStroke = stroke && !stroke.isNone;
- if (hasStroke) {
- var halfLineWidth = ((lineWidth || 0) + (increasedLineWidthForHitTesting || 0)) * expansion;
- // halfExtents[0] += halfLineWidth[0];
- // halfExtents[1] += halfLineWidth[1];
- halfExtents[0] += halfLineWidth;
- halfExtents[1] += halfLineWidth;
- // vec3.add(
- // halfExtents,
- // halfExtents,
- // vec3.set(tmpVec3c, halfLineWidth, halfLineWidth, 0),
- // );
- }
- geometry.renderBounds.update(center, halfExtents);
- // account for shadow, only support constant value now
- if (shadowColor && shadowType && shadowType !== 'inner') {
- var _geometry$renderBound = geometry.renderBounds,
- min = _geometry$renderBound.min,
- max = _geometry$renderBound.max;
- var shadowBlur = parsedStyle.shadowBlur,
- shadowOffsetX = parsedStyle.shadowOffsetX,
- shadowOffsetY = parsedStyle.shadowOffsetY;
- var shadowBlurInPixels = shadowBlur || 0;
- var shadowOffsetXInPixels = shadowOffsetX || 0;
- var shadowOffsetYInPixels = shadowOffsetY || 0;
- var shadowLeft = min[0] - shadowBlurInPixels + shadowOffsetXInPixels;
- var shadowRight = max[0] + shadowBlurInPixels + shadowOffsetXInPixels;
- var shadowTop = min[1] - shadowBlurInPixels + shadowOffsetYInPixels;
- var shadowBottom = max[1] + shadowBlurInPixels + shadowOffsetYInPixels;
- min[0] = Math.min(min[0], shadowLeft);
- max[0] = Math.max(max[0], shadowRight);
- min[1] = Math.min(min[1], shadowTop);
- max[1] = Math.max(max[1], shadowBottom);
- geometry.renderBounds.setMinMax(min, max);
- }
- // account for filter, eg. blur(5px), drop-shadow()
- filter.forEach(function (_ref) {
- var name = _ref.name,
- params = _ref.params;
- if (name === 'blur') {
- var blurRadius = params[0].value;
- geometry.renderBounds.update(geometry.renderBounds.center, addVec3(geometry.renderBounds.halfExtents, geometry.renderBounds.halfExtents, [blurRadius, blurRadius, 0]));
- } else if (name === 'drop-shadow') {
- var _shadowOffsetX = params[0].value;
- var _shadowOffsetY = params[1].value;
- var _shadowBlur = params[2].value;
- var _geometry$renderBound2 = geometry.renderBounds,
- _min = _geometry$renderBound2.min,
- _max = _geometry$renderBound2.max;
- var _shadowLeft = _min[0] - _shadowBlur + _shadowOffsetX;
- var _shadowRight = _max[0] + _shadowBlur + _shadowOffsetX;
- var _shadowTop = _min[1] - _shadowBlur + _shadowOffsetY;
- var _shadowBottom = _max[1] + _shadowBlur + _shadowOffsetY;
- _min[0] = Math.min(_min[0], _shadowLeft);
- _max[0] = Math.max(_max[0], _shadowRight);
- _min[1] = Math.min(_min[1], _shadowTop);
- _max[1] = Math.max(_max[1], _shadowBottom);
- geometry.renderBounds.setMinMax(_min, _max);
- }
- });
- anchor = parsedStyle.anchor;
- // if (nodeName === Shape.RECT) {
- // account for negative width / height of Rect
- // @see https://github.com/antvis/g/issues/957
- var flipY = width < 0;
- var flipX = height < 0;
- // } else {
- // }
- // set transform origin
- var usedOriginXValue = (flipY ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[0], 0, object) : 0);
- var usedOriginYValue = (flipX ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[1], 1, object) : 0);
- usedOriginXValue = usedOriginXValue - (flipY ? -1 : 1) * (anchor && anchor[0] || 0) * geometry.contentBounds.halfExtents[0] * 2;
- usedOriginYValue = usedOriginYValue - (flipX ? -1 : 1) * (anchor && anchor[1] || 0) * geometry.contentBounds.halfExtents[1] * 2;
- object.setOrigin(usedOriginXValue, usedOriginYValue);
- // FIXME setOrigin may have already dirtified to root.
- runtime.sceneGraphService.dirtifyToRoot(object);
- }
- };
- _proto.isPropertyInheritable = function isPropertyInheritable(name) {
- var metadata = propertyMetadataCache[name];
- if (!metadata) {
- return false;
- }
- return metadata.inh;
- };
- return DefaultStyleValueRegistry;
- }();
- /**
- * Different type of cameras, eg. simple camera used in 2D scene or
- * advanced camera which can do actions & switch between landmarks.
- */
- var CameraType;
- (function (CameraType) {
- /**
- * Performs all the rotational operations with the focal point instead of the camera position.
- * This type of camera is useful in applications(like CAD) where 3D objects are being designed or explored.
- * Camera cannot orbits over the north & south poles.
- * @see http://voxelent.com/tutorial-cameras/
- *
- * In Three.js it's used in OrbitControls.
- * @see https://threejs.org/docs/#examples/zh/controls/OrbitControls
- */
- CameraType[CameraType["ORBITING"] = 0] = "ORBITING";
- /**
- * It's similar to the ORBITING camera, but it allows the camera to orbit over the north or south poles.
- *
- * In Three.js it's used in OrbitControls.
- * @see https://threejs.org/docs/#examples/en/controls/TrackballControls
- */
- CameraType[CameraType["EXPLORING"] = 1] = "EXPLORING";
- /**
- * Performs all the rotational operations with the camera position.
- * It's useful in first person shooting games.
- * Camera cannot orbits over the north & south poles.
- *
- * In Three.js it's used in FirstPersonControls.
- * @see https://threejs.org/docs/#examples/en/controls/FirstPersonControls
- */
- CameraType[CameraType["TRACKING"] = 2] = "TRACKING";
- })(CameraType || (CameraType = {}));
- /**
- * CameraType must be TRACKING
- */
- var CameraTrackingMode;
- (function (CameraTrackingMode) {
- CameraTrackingMode[CameraTrackingMode["DEFAULT"] = 0] = "DEFAULT";
- CameraTrackingMode[CameraTrackingMode["ROTATIONAL"] = 1] = "ROTATIONAL";
- CameraTrackingMode[CameraTrackingMode["TRANSLATIONAL"] = 2] = "TRANSLATIONAL";
- CameraTrackingMode[CameraTrackingMode["CINEMATIC"] = 3] = "CINEMATIC";
- })(CameraTrackingMode || (CameraTrackingMode = {}));
- var CameraProjectionMode;
- (function (CameraProjectionMode) {
- CameraProjectionMode[CameraProjectionMode["ORTHOGRAPHIC"] = 0] = "ORTHOGRAPHIC";
- CameraProjectionMode[CameraProjectionMode["PERSPECTIVE"] = 1] = "PERSPECTIVE";
- })(CameraProjectionMode || (CameraProjectionMode = {}));
- var CameraEvent = {
- UPDATED: 'updated'
- };
- var MIN_DISTANCE = 0.0002;
- /**
- * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计
- * @see https://github.com/d13g0/nucleo.js/blob/master/source/camera/Camera.js
- *
- * 保存相机参数,定义相机动作:
- * 1. dolly 沿 n 轴移动
- * 2. pan 沿 u v 轴移动
- * 3. rotate 以方位角旋转
- * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互
- */
- var Camera = /*#__PURE__*/function () {
- function Camera() {
- this.canvas = void 0;
- this.eventEmitter = new EventEmitter();
- /**
- * 相机矩阵
- */
- this.matrix = mat4.create();
- /**
- * u 轴
- * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition
- */
- this.right = vec3.fromValues(1, 0, 0);
- /**
- * v 轴 +Y is down
- */
- this.up = vec3.fromValues(0, 1, 0);
- /**
- * n 轴 +Z is inside
- */
- this.forward = vec3.fromValues(0, 0, 1);
- /**
- * 相机位置
- */
- this.position = vec3.fromValues(0, 0, 1);
- /**
- * 视点位置
- */
- this.focalPoint = vec3.fromValues(0, 0, 0);
- /**
- * 视点到相机位置的向量
- * focalPoint - position
- */
- this.distanceVector = vec3.fromValues(0, 0, -1);
- /**
- * 相机位置到视点距离
- * length(focalPoint - position)
- */
- this.distance = 1;
- /**
- * @see https://en.wikipedia.org/wiki/Azimuth
- */
- this.azimuth = 0;
- this.elevation = 0;
- this.roll = 0;
- this.relAzimuth = 0;
- this.relElevation = 0;
- this.relRoll = 0;
- /**
- * 沿 n 轴移动时,保证移动速度从快到慢
- */
- this.dollyingStep = 0;
- this.maxDistance = Infinity;
- this.minDistance = -Infinity;
- /**
- * zoom factor of the camera, default is 1
- * eg. https://threejs.org/docs/#api/en/cameras/OrthographicCamera.zoom
- */
- this.zoom = 1;
- /**
- * invert the horizontal coordinate system HCS
- */
- this.rotateWorld = false;
- /**
- * 投影矩阵参数
- */
- /**
- * field of view [0-360]
- * @see http://en.wikipedia.org/wiki/Angle_of_view
- */
- this.fov = 30;
- this.near = 0.1;
- this.far = 1000;
- this.aspect = 1;
- this.left = void 0;
- this.rright = void 0;
- this.top = void 0;
- this.bottom = void 0;
- this.projectionMatrix = mat4.create();
- this.projectionMatrixInverse = mat4.create();
- this.jitteredProjectionMatrix = undefined;
- this.view = void 0;
- this.enableUpdate = true;
- // protected following = undefined;
- this.type = CameraType.EXPLORING;
- this.trackingMode = CameraTrackingMode.DEFAULT;
- this.projectionMode = CameraProjectionMode.PERSPECTIVE;
- /**
- * for culling use
- */
- this.frustum = new Frustum();
- /**
- * ortho matrix for Canvas2D & SVG
- */
- this.orthoMatrix = mat4.create();
- }
- var _proto = Camera.prototype;
- // constructor(type = CameraType.EXPLORING, trackingMode = CameraTrackingMode.DEFAULT) {
- // this.setType(type, trackingMode);
- // }
- _proto.isOrtho = function isOrtho() {
- return this.projectionMode === CameraProjectionMode.ORTHOGRAPHIC;
- };
- _proto.getProjectionMode = function getProjectionMode() {
- return this.projectionMode;
- };
- _proto.getPerspective = function getPerspective() {
- // account for TAA
- return this.jitteredProjectionMatrix || this.projectionMatrix;
- };
- _proto.getPerspectiveInverse = function getPerspectiveInverse() {
- return this.projectionMatrixInverse;
- };
- _proto.getFrustum = function getFrustum() {
- return this.frustum;
- };
- _proto.getPosition = function getPosition() {
- return this.position;
- };
- _proto.getFocalPoint = function getFocalPoint() {
- return this.focalPoint;
- };
- _proto.getDollyingStep = function getDollyingStep() {
- return this.dollyingStep;
- };
- _proto.getNear = function getNear() {
- return this.near;
- };
- _proto.getFar = function getFar() {
- return this.far;
- };
- _proto.getZoom = function getZoom() {
- return this.zoom;
- };
- _proto.getOrthoMatrix = function getOrthoMatrix() {
- return this.orthoMatrix;
- };
- _proto.getView = function getView() {
- return this.view;
- };
- _proto.setEnableUpdate = function setEnableUpdate(enabled) {
- this.enableUpdate = enabled;
- };
- _proto.setType = function setType(type, trackingMode) {
- this.type = type;
- if (this.type === CameraType.EXPLORING) {
- this.setWorldRotation(true);
- } else {
- this.setWorldRotation(false);
- }
- this._getAngles();
- if (this.type === CameraType.TRACKING && trackingMode !== undefined) {
- this.setTrackingMode(trackingMode);
- }
- return this;
- };
- _proto.setProjectionMode = function setProjectionMode(projectionMode) {
- this.projectionMode = projectionMode;
- return this;
- };
- _proto.setTrackingMode = function setTrackingMode(trackingMode) {
- if (this.type !== CameraType.TRACKING) {
- throw new Error('Impossible to set a tracking mode if the camera is not of tracking type');
- }
- this.trackingMode = trackingMode;
- return this;
- }
- /**
- * If flag is true, it reverses the azimuth and elevation angles.
- * Subsequent calls to rotate, setAzimuth, setElevation,
- * changeAzimuth or changeElevation will cause the inverted effect.
- * setRoll or changeRoll is not affected by this method.
- *
- * This inversion is useful when one wants to simulate that the world
- * is moving, instead of the camera.
- *
- * By default the camera angles are not reversed.
- * @param {Boolean} flag the boolean flag to reverse the angles.
- */;
- _proto.setWorldRotation = function setWorldRotation(flag) {
- this.rotateWorld = flag;
- this._getAngles();
- return this;
- }
- /**
- * 计算 MV 矩阵,为相机矩阵的逆矩阵
- */;
- _proto.getViewTransform = function getViewTransform() {
- return mat4.invert(mat4.create(), this.matrix);
- };
- _proto.getWorldTransform = function getWorldTransform() {
- return this.matrix;
- };
- _proto.jitterProjectionMatrix = function jitterProjectionMatrix(x, y) {
- var translation = mat4.fromTranslation(mat4.create(), [x, y, 0]);
- this.jitteredProjectionMatrix = mat4.multiply(mat4.create(), translation, this.projectionMatrix);
- };
- _proto.clearJitterProjectionMatrix = function clearJitterProjectionMatrix() {
- this.jitteredProjectionMatrix = undefined;
- }
- /**
- * 设置相机矩阵
- */;
- _proto.setMatrix = function setMatrix(matrix) {
- this.matrix = matrix;
- this._update();
- return this;
- };
- _proto.setFov = function setFov(fov) {
- this.setPerspective(this.near, this.far, fov, this.aspect);
- return this;
- };
- _proto.setAspect = function setAspect(aspect) {
- this.setPerspective(this.near, this.far, this.fov, aspect);
- return this;
- };
- _proto.setNear = function setNear(near) {
- if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(near, this.far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, near, this.far);
- }
- return this;
- };
- _proto.setFar = function setFar(far) {
- if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, far);
- }
- return this;
- }
- /**
- * Sets an offset in a larger frustum, used in PixelPicking
- */;
- _proto.setViewOffset = function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
- this.aspect = fullWidth / fullHeight;
- if (this.view === undefined) {
- this.view = {
- enabled: true,
- fullWidth: 1,
- fullHeight: 1,
- offsetX: 0,
- offsetY: 0,
- width: 1,
- height: 1
- };
- }
- this.view.enabled = true;
- this.view.fullWidth = fullWidth;
- this.view.fullHeight = fullHeight;
- this.view.offsetX = x;
- this.view.offsetY = y;
- this.view.width = width;
- this.view.height = height;
- if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, this.far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
- }
- return this;
- };
- _proto.clearViewOffset = function clearViewOffset() {
- if (this.view !== undefined) {
- this.view.enabled = false;
- }
- if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, this.far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
- }
- return this;
- };
- _proto.setZoom = function setZoom(zoom) {
- this.zoom = zoom;
- if (this.projectionMode === CameraProjectionMode.ORTHOGRAPHIC) {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
- } else if (this.projectionMode === CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, this.far, this.fov, this.aspect);
- }
- return this;
- }
- /**
- * Zoom by specified point in viewport coordinates.
- */;
- _proto.setZoomByViewportPoint = function setZoomByViewportPoint(zoom, viewportPoint) {
- var _this$canvas$viewport = this.canvas.viewport2Canvas({
- x: viewportPoint[0],
- y: viewportPoint[1]
- }),
- ox = _this$canvas$viewport.x,
- oy = _this$canvas$viewport.y;
- var roll = this.roll;
- this.rotate(0, 0, -roll);
- this.setPosition(ox, oy);
- this.setFocalPoint(ox, oy);
- this.setZoom(zoom);
- this.rotate(0, 0, roll);
- var _this$canvas$viewport2 = this.canvas.viewport2Canvas({
- x: viewportPoint[0],
- y: viewportPoint[1]
- }),
- cx = _this$canvas$viewport2.x,
- cy = _this$canvas$viewport2.y;
- // project to rotated axis
- var dvec = vec3.fromValues(cx - ox, cy - oy, 0);
- var dx = vec3.dot(dvec, this.right) / vec3.length(this.right);
- var dy = vec3.dot(dvec, this.up) / vec3.length(this.up);
- this.pan(-dx, -dy);
- return this;
- };
- _proto.setPerspective = function setPerspective(near, far, fov, aspect) {
- var _this$view;
- this.projectionMode = CameraProjectionMode.PERSPECTIVE;
- this.fov = fov;
- this.near = near;
- this.far = far;
- this.aspect = aspect;
- var top = this.near * Math.tan(deg2rad(0.5 * this.fov)) / this.zoom;
- var height = 2 * top;
- var width = this.aspect * height;
- var left = -0.5 * width;
- if ((_this$view = this.view) === null || _this$view === void 0 ? void 0 : _this$view.enabled) {
- var fullWidth = this.view.fullWidth;
- var fullHeight = this.view.fullHeight;
- left += this.view.offsetX * width / fullWidth;
- top -= this.view.offsetY * height / fullHeight;
- width *= this.view.width / fullWidth;
- height *= this.view.height / fullHeight;
- }
- makePerspective(this.projectionMatrix, left, left + width, top, top - height, near, this.far);
- // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
- mat4.scale(this.projectionMatrix, this.projectionMatrix, vec3.fromValues(1, -1, 1));
- mat4.invert(this.projectionMatrixInverse, this.projectionMatrix);
- this.triggerUpdate();
- return this;
- };
- _proto.setOrthographic = function setOrthographic(l, r, t, b, near, far) {
- var _this$view2;
- this.projectionMode = CameraProjectionMode.ORTHOGRAPHIC;
- this.rright = r;
- this.left = l;
- this.top = t;
- this.bottom = b;
- this.near = near;
- this.far = far;
- var dx = (this.rright - this.left) / (2 * this.zoom);
- var dy = (this.top - this.bottom) / (2 * this.zoom);
- var cx = (this.rright + this.left) / 2;
- var cy = (this.top + this.bottom) / 2;
- var left = cx - dx;
- var right = cx + dx;
- var top = cy + dy;
- var bottom = cy - dy;
- if ((_this$view2 = this.view) === null || _this$view2 === void 0 ? void 0 : _this$view2.enabled) {
- var scaleW = (this.rright - this.left) / this.view.fullWidth / this.zoom;
- var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
- left += scaleW * this.view.offsetX;
- right = left + scaleW * this.view.width;
- top -= scaleH * this.view.offsetY;
- bottom = top - scaleH * this.view.height;
- }
- mat4.ortho(this.projectionMatrix, left, right, bottom, top, near, far);
- // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
- mat4.scale(this.projectionMatrix, this.projectionMatrix, vec3.fromValues(1, -1, 1));
- mat4.invert(this.projectionMatrixInverse, this.projectionMatrix);
- this._getOrthoMatrix();
- this.triggerUpdate();
- return this;
- }
- /**
- * Move the camera in world coordinates.
- * It will keep looking at the current focal point.
- *
- * support scalars or vectors.
- * @example
- * setPosition(1, 2, 3);
- * setPosition([1, 2, 3]);
- */;
- _proto.setPosition = function setPosition(x, y, z) {
- if (y === void 0) {
- y = this.position[1];
- }
- if (z === void 0) {
- z = this.position[2];
- }
- var position = createVec3(x, y, z);
- this._setPosition(position);
- this.setFocalPoint(this.focalPoint);
- this.triggerUpdate();
- return this;
- }
- /**
- * Sets the focal point of this camera in world coordinates.
- *
- * support scalars or vectors.
- * @example
- * setFocalPoint(1, 2, 3);
- * setFocalPoint([1, 2, 3]);
- */;
- _proto.setFocalPoint = function setFocalPoint(x, y, z) {
- if (y === void 0) {
- y = this.focalPoint[1];
- }
- if (z === void 0) {
- z = this.focalPoint[2];
- }
- var up = vec3.fromValues(0, 1, 0);
- this.focalPoint = createVec3(x, y, z);
- if (this.trackingMode === CameraTrackingMode.CINEMATIC) {
- var d = vec3.subtract(vec3.create(), this.focalPoint, this.position);
- x = d[0];
- y = d[1];
- z = d[2];
- var r = vec3.length(d);
- var el = rad2deg(Math.asin(y / r));
- var az = 90 + rad2deg(Math.atan2(z, x));
- var m = mat4.create();
- mat4.rotateY(m, m, deg2rad(az));
- mat4.rotateX(m, m, deg2rad(el));
- up = vec3.transformMat4(vec3.create(), [0, 1, 0], m);
- }
- mat4.invert(this.matrix, mat4.lookAt(mat4.create(), this.position, this.focalPoint, up));
- this._getAxes();
- this._getDistance();
- this._getAngles();
- this.triggerUpdate();
- return this;
- };
- _proto.getDistance = function getDistance() {
- return this.distance;
- };
- _proto.getDistanceVector = function getDistanceVector() {
- return this.distanceVector;
- }
- /**
- * Moves the camera towards/from the focal point.
- */;
- _proto.setDistance = function setDistance(d) {
- if (this.distance === d || d < 0) {
- return this;
- }
- this.distance = d;
- if (this.distance < MIN_DISTANCE) {
- this.distance = MIN_DISTANCE;
- }
- this.dollyingStep = this.distance / 100;
- var pos = vec3.create();
- d = this.distance;
- var n = this.forward;
- var f = this.focalPoint;
- pos[0] = d * n[0] + f[0];
- pos[1] = d * n[1] + f[1];
- pos[2] = d * n[2] + f[2];
- this._setPosition(pos);
- this.triggerUpdate();
- return this;
- };
- _proto.setMaxDistance = function setMaxDistance(d) {
- this.maxDistance = d;
- return this;
- };
- _proto.setMinDistance = function setMinDistance(d) {
- this.minDistance = d;
- return this;
- }
- /**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- * the azimuth in degrees
- */;
- _proto.setAzimuth = function setAzimuth(az) {
- this.azimuth = getAngle(az);
- this.computeMatrix();
- this._getAxes();
- if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this.triggerUpdate();
- return this;
- };
- _proto.getAzimuth = function getAzimuth() {
- return this.azimuth;
- }
- /**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- */;
- _proto.setElevation = function setElevation(el) {
- this.elevation = getAngle(el);
- this.computeMatrix();
- this._getAxes();
- if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this.triggerUpdate();
- return this;
- };
- _proto.getElevation = function getElevation() {
- return this.elevation;
- }
- /**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- */;
- _proto.setRoll = function setRoll(angle) {
- this.roll = getAngle(angle);
- this.computeMatrix();
- this._getAxes();
- if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this.triggerUpdate();
- return this;
- };
- _proto.getRoll = function getRoll() {
- return this.roll;
- }
- /**
- * 根据相机矩阵重新计算各种相机参数
- */;
- _proto._update = function _update() {
- this._getAxes();
- this._getPosition();
- this._getDistance();
- this._getAngles();
- this._getOrthoMatrix();
- this.triggerUpdate();
- }
- /**
- * 计算相机矩阵
- */;
- _proto.computeMatrix = function computeMatrix() {
- // 使用四元数描述 3D 旋转
- // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html
- var rotZ = quat$1.setAxisAngle(quat$1.create(), [0, 0, 1], deg2rad(this.roll));
- mat4.identity(this.matrix);
- // only consider HCS for EXPLORING and ORBITING cameras
- 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));
- 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));
- var rotQ = quat$1.multiply(quat$1.create(), rotY, rotX);
- rotQ = quat$1.multiply(quat$1.create(), rotQ, rotZ);
- var rotMatrix = mat4.fromQuat(mat4.create(), rotQ);
- if (this.type === CameraType.ORBITING || this.type === CameraType.EXPLORING) {
- mat4.translate(this.matrix, this.matrix, this.focalPoint);
- mat4.multiply(this.matrix, this.matrix, rotMatrix);
- mat4.translate(this.matrix, this.matrix, [0, 0, this.distance]);
- } else if (this.type === CameraType.TRACKING) {
- mat4.translate(this.matrix, this.matrix, this.position);
- mat4.multiply(this.matrix, this.matrix, rotMatrix);
- }
- }
- /**
- * Sets the camera position in the camera matrix
- */;
- _proto._setPosition = function _setPosition(x, y, z) {
- this.position = createVec3(x, y, z);
- var m = this.matrix;
- m[12] = this.position[0];
- m[13] = this.position[1];
- m[14] = this.position[2];
- m[15] = 1;
- this._getOrthoMatrix();
- }
- /**
- * Recalculates axes based on the current matrix
- */;
- _proto._getAxes = function _getAxes() {
- vec3.copy(this.right, createVec3(vec4.transformMat4(vec4.create(), [1, 0, 0, 0], this.matrix)));
- vec3.copy(this.up, createVec3(vec4.transformMat4(vec4.create(), [0, 1, 0, 0], this.matrix)));
- vec3.copy(this.forward, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 1, 0], this.matrix)));
- vec3.normalize(this.right, this.right);
- vec3.normalize(this.up, this.up);
- vec3.normalize(this.forward, this.forward);
- }
- /**
- * Recalculates euler angles based on the current state
- */;
- _proto._getAngles = function _getAngles() {
- // Recalculates angles
- var x = this.distanceVector[0];
- var y = this.distanceVector[1];
- var z = this.distanceVector[2];
- var r = vec3.length(this.distanceVector);
- // FAST FAIL: If there is no distance we cannot compute angles
- if (r === 0) {
- this.elevation = 0;
- this.azimuth = 0;
- return;
- }
- if (this.type === CameraType.TRACKING) {
- this.elevation = rad2deg(Math.asin(y / r));
- this.azimuth = rad2deg(Math.atan2(-x, -z));
- } else {
- if (this.rotateWorld) {
- this.elevation = rad2deg(Math.asin(y / r));
- this.azimuth = rad2deg(Math.atan2(-x, -z));
- } else {
- this.elevation = -rad2deg(Math.asin(y / r));
- this.azimuth = -rad2deg(Math.atan2(-x, -z));
- }
- }
- }
- /**
- * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化
- */;
- _proto._getPosition = function _getPosition() {
- vec3.copy(this.position, createVec3(vec4.transformMat4(vec4.create(), [0, 0, 0, 1], this.matrix)));
- // 相机位置变化,需要重新计算视距
- this._getDistance();
- }
- /**
- * 重新计算视点,只有 TRACKING 模式视点才会发生变化
- */;
- _proto._getFocalPoint = function _getFocalPoint() {
- vec3.transformMat3(this.distanceVector, [0, 0, -this.distance], mat3.fromMat4(mat3.create(), this.matrix));
- vec3.add(this.focalPoint, this.position, this.distanceVector);
- // 视点变化,需要重新计算视距
- this._getDistance();
- }
- /**
- * 重新计算视距
- */;
- _proto._getDistance = function _getDistance() {
- this.distanceVector = vec3.subtract(vec3.create(), this.focalPoint, this.position);
- this.distance = vec3.length(this.distanceVector);
- this.dollyingStep = this.distance / 100;
- };
- _proto._getOrthoMatrix = function _getOrthoMatrix() {
- if (this.projectionMode !== CameraProjectionMode.ORTHOGRAPHIC) {
- return;
- }
- var position = this.position;
- var rotZ = quat$1.setAxisAngle(quat$1.create(), [0, 0, 1], -this.roll * Math.PI / 180);
- 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);
- };
- _proto.triggerUpdate = function triggerUpdate() {
- if (this.enableUpdate) {
- // update frustum
- var viewMatrix = this.getViewTransform();
- var vpMatrix = mat4.multiply(mat4.create(), this.getPerspective(), viewMatrix);
- this.getFrustum().extractFromVPMatrix(vpMatrix);
- this.eventEmitter.emit(CameraEvent.UPDATED);
- }
- };
- _proto.rotate = function rotate(azimuth, elevation, roll) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.pan = function pan(tx, ty) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.dolly = function dolly(value) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.createLandmark = function createLandmark(name, params) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.gotoLandmark = function gotoLandmark(name, options) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.cancelLandmarkAnimation = function cancelLandmarkAnimation() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- return Camera;
- }();
- var CircleUpdater = /*#__PURE__*/function () {
- function CircleUpdater() {}
- var _proto = CircleUpdater.prototype;
- _proto.update = function update(parsedStyle, object) {
- var r = parsedStyle.r;
- var width = r * 2;
- var height = r * 2;
- return {
- width: width,
- height: height
- };
- };
- return CircleUpdater;
- }();
- var EllipseUpdater = /*#__PURE__*/function () {
- function EllipseUpdater() {}
- var _proto = EllipseUpdater.prototype;
- _proto.update = function update(parsedStyle, object) {
- var rx = parsedStyle.rx,
- ry = parsedStyle.ry;
- var width = rx * 2;
- var height = ry * 2;
- return {
- width: width,
- height: height
- };
- };
- return EllipseUpdater;
- }();
- var LineUpdater = /*#__PURE__*/function () {
- function LineUpdater() {}
- var _proto = LineUpdater.prototype;
- _proto.update = function update(parsedStyle) {
- var x1 = parsedStyle.x1,
- y1 = parsedStyle.y1,
- x2 = parsedStyle.x2,
- y2 = parsedStyle.y2;
- var minX = Math.min(x1, x2);
- var maxX = Math.max(x1, x2);
- var minY = Math.min(y1, y2);
- var maxY = Math.max(y1, y2);
- var width = maxX - minX;
- var height = maxY - minY;
- return {
- width: width,
- height: height
- };
- };
- return LineUpdater;
- }();
- var PathUpdater = /*#__PURE__*/function () {
- function PathUpdater() {}
- var _proto = PathUpdater.prototype;
- _proto.update = function update(parsedStyle) {
- var path = parsedStyle.path;
- var _path$rect = path.rect,
- width = _path$rect.width,
- height = _path$rect.height;
- return {
- width: width,
- height: height
- };
- };
- return PathUpdater;
- }();
- var PolylineUpdater = /*#__PURE__*/function () {
- function PolylineUpdater() {}
- var _proto = PolylineUpdater.prototype;
- _proto.update = function update(parsedStyle) {
- var points = parsedStyle.points.points;
- // FIXME: account for miter lineJoin
- var minX = Math.min.apply(Math, points.map(function (point) {
- return point[0];
- }));
- var maxX = Math.max.apply(Math, points.map(function (point) {
- return point[0];
- }));
- var minY = Math.min.apply(Math, points.map(function (point) {
- return point[1];
- }));
- var maxY = Math.max.apply(Math, points.map(function (point) {
- return point[1];
- }));
- var width = maxX - minX;
- var height = maxY - minY;
- return {
- width: width,
- height: height
- };
- };
- return PolylineUpdater;
- }();
- var RectUpdater = /*#__PURE__*/function () {
- function RectUpdater() {}
- var _proto = RectUpdater.prototype;
- _proto.update = function update(parsedStyle, object) {
- var img = parsedStyle.img,
- _parsedStyle$width = parsedStyle.width,
- width = _parsedStyle$width === void 0 ? 0 : _parsedStyle$width,
- _parsedStyle$height = parsedStyle.height,
- height = _parsedStyle$height === void 0 ? 0 : _parsedStyle$height;
- var contentWidth = width;
- var contentHeight = height;
- // resize with HTMLImageElement's size
- if (img && !isString(img)) {
- if (!contentWidth) {
- contentWidth = img.width;
- parsedStyle.width = contentWidth;
- }
- if (!contentHeight) {
- contentHeight = img.height;
- parsedStyle.height = contentHeight;
- }
- }
- return {
- width: contentWidth,
- height: contentHeight
- };
- };
- return RectUpdater;
- }();
- var TextUpdater = /*#__PURE__*/function () {
- function TextUpdater(globalRuntime) {
- this.globalRuntime = void 0;
- this.globalRuntime = globalRuntime;
- }
- var _proto = TextUpdater.prototype;
- _proto.isReadyToMeasure = function isReadyToMeasure(parsedStyle, object) {
- var text = parsedStyle.text,
- textAlign = parsedStyle.textAlign,
- textBaseline = parsedStyle.textBaseline,
- fontSize = parsedStyle.fontSize,
- fontStyle = parsedStyle.fontStyle,
- fontWeight = parsedStyle.fontWeight,
- fontVariant = parsedStyle.fontVariant,
- lineWidth = parsedStyle.lineWidth;
- return text && fontSize && fontStyle && fontWeight && fontVariant && textAlign && textBaseline && !isNil(lineWidth);
- };
- _proto.update = function update(parsedStyle, object) {
- var _object$ownerDocument, _object$ownerDocument2;
- var text = parsedStyle.text,
- textAlign = parsedStyle.textAlign,
- lineWidth = parsedStyle.lineWidth,
- textBaseline = parsedStyle.textBaseline,
- dx = parsedStyle.dx,
- dy = parsedStyle.dy;
- 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()) || {},
- offscreenCanvas = _ref.offscreenCanvas;
- if (!this.isReadyToMeasure(parsedStyle, object)) {
- parsedStyle.metrics = {
- font: '',
- width: 0,
- height: 0,
- lines: [],
- lineWidths: [],
- lineHeight: 0,
- maxLineWidth: 0,
- fontProperties: {
- ascent: 0,
- descent: 0,
- fontSize: 0
- },
- lineMetrics: []
- };
- return {
- width: 0,
- height: 0,
- x: 0,
- y: 0,
- offsetX: 0,
- offsetY: 0
- };
- }
- var metrics = this.globalRuntime.textService.measureText(text, parsedStyle, offscreenCanvas);
- parsedStyle.metrics = metrics;
- var width = metrics.width,
- height = metrics.height,
- lineHeight = metrics.lineHeight,
- fontProperties = metrics.fontProperties;
- // anchor is left-top by default
- var halfExtents = [width / 2, height / 2, 0];
- // default 'left'
- var anchor = [0, 1];
- var lineXOffset = 0;
- if (textAlign === 'center' || textAlign === 'middle') {
- lineXOffset = lineWidth / 2;
- anchor = [0.5, 1];
- } else if (textAlign === 'right' || textAlign === 'end') {
- lineXOffset = lineWidth;
- anchor = [1, 1];
- }
- var lineYOffset = 0;
- if (textBaseline === 'middle') {
- // eslint-disable-next-line prefer-destructuring
- lineYOffset = halfExtents[1];
- } else if (textBaseline === 'top' || textBaseline === 'hanging') {
- lineYOffset = halfExtents[1] * 2;
- } else if (textBaseline === 'alphabetic') {
- // prevent calling getImageData for ascent metrics
- lineYOffset = runtime.enableCSSParsing ? lineHeight - fontProperties.ascent : 0;
- } else if (textBaseline === 'bottom' || textBaseline === 'ideographic') {
- lineYOffset = 0;
- }
- // TODO: ideographic & bottom
- if (dx) {
- lineXOffset += dx;
- }
- if (dy) {
- lineYOffset += dy;
- }
- // update anchor
- parsedStyle.anchor = [anchor[0], anchor[1], 0];
- return {
- width: halfExtents[0] * 2,
- height: halfExtents[1] * 2,
- offsetX: lineXOffset,
- offsetY: lineYOffset
- };
- };
- return TextUpdater;
- }();
- var PROPAGATION_LIMIT = 2048;
- var EventService = /*#__PURE__*/function () {
- function EventService(globalRuntime, context) {
- var _this = this;
- this.globalRuntime = void 0;
- this.context = void 0;
- this.rootTarget = void 0;
- this.emitter = new EventEmitter();
- this.cursor = 'default';
- this.mappingTable = {};
- this.mappingState = {
- trackingData: {}
- };
- this.eventPool = new Map();
- this.pickHandler = void 0;
- this.tmpMatrix = mat4.create();
- this.tmpVec3 = vec3.create();
- this.onPointerDown = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var e = _this.createPointerEvent(from);
- _this.dispatchEvent(e, 'pointerdown');
- if (e.pointerType === 'touch') {
- _this.dispatchEvent(e, 'touchstart');
- } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- var isRightButton = e.button === 2;
- _this.dispatchEvent(e, isRightButton ? 'rightdown' : 'mousedown');
- }
- var trackingData = _this.trackingData(from.pointerId);
- trackingData.pressTargetsByButton[from.button] = e.composedPath();
- _this.freeEvent(e);
- };
- this.onPointerUp = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var now = performance.now();
- var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
- _this.dispatchEvent(e, 'pointerup');
- if (e.pointerType === 'touch') {
- _this.dispatchEvent(e, 'touchend');
- } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- var isRightButton = e.button === 2;
- _this.dispatchEvent(e, isRightButton ? 'rightup' : 'mouseup');
- }
- var trackingData = _this.trackingData(from.pointerId);
- var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
- var clickTarget = pressTarget;
- // pointerupoutside only bubbles. It only bubbles upto the parent that doesn't contain
- // the pointerup location.
- if (pressTarget && !e.composedPath().includes(pressTarget)) {
- var currentTarget = pressTarget;
- while (currentTarget && !e.composedPath().includes(currentTarget)) {
- e.currentTarget = currentTarget;
- _this.notifyTarget(e, 'pointerupoutside');
- if (e.pointerType === 'touch') {
- _this.notifyTarget(e, 'touchendoutside');
- } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- var _isRightButton = e.button === 2;
- _this.notifyTarget(e, _isRightButton ? 'rightupoutside' : 'mouseupoutside');
- }
- if (Node.isNode(currentTarget)) {
- currentTarget = currentTarget.parentNode;
- }
- }
- delete trackingData.pressTargetsByButton[from.button];
- // currentTarget is the most specific ancestor holding both the pointerdown and pointerup
- // targets. That is - it's our click target!
- clickTarget = currentTarget;
- }
- if (clickTarget) {
- var _e$detail;
- var clickEvent = _this.clonePointerEvent(e, 'click');
- clickEvent.target = clickTarget;
- clickEvent.path = [];
- if (!trackingData.clicksByButton[from.button]) {
- trackingData.clicksByButton[from.button] = {
- clickCount: 0,
- target: clickEvent.target,
- timeStamp: now
- };
- }
- var clickHistory = trackingData.clicksByButton[from.button];
- if (clickHistory.target === clickEvent.target && now - clickHistory.timeStamp < 200) {
- ++clickHistory.clickCount;
- } else {
- clickHistory.clickCount = 1;
- }
- clickHistory.target = clickEvent.target;
- clickHistory.timeStamp = now;
- clickEvent.detail = clickHistory.clickCount;
- // @see https://github.com/antvis/G/issues/1091
- if (!((_e$detail = e.detail) === null || _e$detail === void 0 ? void 0 : _e$detail.preventClick)) {
- if (!_this.context.config.useNativeClickEvent && (clickEvent.pointerType === 'mouse' || clickEvent.pointerType === 'touch')) {
- _this.dispatchEvent(clickEvent, 'click');
- }
- _this.dispatchEvent(clickEvent, 'pointertap');
- }
- _this.freeEvent(clickEvent);
- }
- _this.freeEvent(e);
- };
- this.onPointerMove = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
- var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
- var trackingData = _this.trackingData(from.pointerId);
- var outTarget = _this.findMountedTarget(trackingData.overTargets);
- // First pointerout/pointerleave
- if (trackingData.overTargets && outTarget !== e.target) {
- // pointerout always occurs on the overTarget when the pointer hovers over another element.
- var outType = from.type === 'mousemove' ? 'mouseout' : 'pointerout';
- var outEvent = _this.createPointerEvent(from, outType, outTarget || undefined);
- _this.dispatchEvent(outEvent, 'pointerout');
- if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
- // If the pointer exits overTarget and its descendants, then a pointerleave event is also fired. This event
- // is dispatched to all ancestors that no longer capture the pointer.
- if (!e.composedPath().includes(outTarget)) {
- var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
- leaveEvent.eventPhase = leaveEvent.AT_TARGET;
- while (leaveEvent.target && !e.composedPath().includes(leaveEvent.target)) {
- leaveEvent.currentTarget = leaveEvent.target;
- _this.notifyTarget(leaveEvent);
- if (isMouse) {
- _this.notifyTarget(leaveEvent, 'mouseleave');
- }
- if (Node.isNode(leaveEvent.target)) {
- leaveEvent.target = leaveEvent.target.parentNode;
- }
- }
- _this.freeEvent(leaveEvent);
- }
- _this.freeEvent(outEvent);
- }
- // Then pointerover
- if (outTarget !== e.target) {
- // pointerover always occurs on the new overTarget
- var overType = from.type === 'mousemove' ? 'mouseover' : 'pointerover';
- var overEvent = _this.clonePointerEvent(e, overType); // clone faster
- _this.dispatchEvent(overEvent, 'pointerover');
- if (isMouse) _this.dispatchEvent(overEvent, 'mouseover');
- // Probe whether the newly hovered Node is an ancestor of the original overTarget.
- var overTargetAncestor = outTarget && Node.isNode(outTarget) && outTarget.parentNode;
- while (overTargetAncestor && overTargetAncestor !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- if (overTargetAncestor === e.target) break;
- overTargetAncestor = overTargetAncestor.parentNode;
- }
- // The pointer has entered a non-ancestor of the original overTarget. This means we need a pointerentered
- // event.
- var didPointerEnter = !overTargetAncestor || overTargetAncestor === (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode);
- if (didPointerEnter) {
- var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
- enterEvent.eventPhase = enterEvent.AT_TARGET;
- while (enterEvent.target && enterEvent.target !== outTarget && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- enterEvent.currentTarget = enterEvent.target;
- _this.notifyTarget(enterEvent);
- if (isMouse) _this.notifyTarget(enterEvent, 'mouseenter');
- if (Node.isNode(enterEvent.target)) {
- enterEvent.target = enterEvent.target.parentNode;
- }
- }
- _this.freeEvent(enterEvent);
- }
- _this.freeEvent(overEvent);
- }
- // Then pointermove
- _this.dispatchEvent(e, 'pointermove');
- if (e.pointerType === 'touch') _this.dispatchEvent(e, 'touchmove');
- if (isMouse) {
- _this.dispatchEvent(e, 'mousemove');
- _this.cursor = _this.getCursor(e.target);
- }
- trackingData.overTargets = e.composedPath();
- _this.freeEvent(e);
- };
- this.onPointerOut = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData = _this.trackingData(from.pointerId);
- if (trackingData.overTargets) {
- var isMouse = from.pointerType === 'mouse' || from.pointerType === 'pen';
- var outTarget = _this.findMountedTarget(trackingData.overTargets);
- // pointerout first
- var outEvent = _this.createPointerEvent(from, 'pointerout', outTarget || undefined);
- _this.dispatchEvent(outEvent);
- if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
- // pointerleave(s) are also dispatched b/c the pointer must've left rootTarget and its descendants to
- // get an upstream pointerout event (upstream events do not know rootTarget has descendants).
- var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
- leaveEvent.eventPhase = leaveEvent.AT_TARGET;
- while (leaveEvent.target && leaveEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- leaveEvent.currentTarget = leaveEvent.target;
- _this.notifyTarget(leaveEvent);
- if (isMouse) {
- _this.notifyTarget(leaveEvent, 'mouseleave');
- }
- if (Node.isNode(leaveEvent.target)) {
- leaveEvent.target = leaveEvent.target.parentNode;
- }
- }
- trackingData.overTargets = null;
- _this.freeEvent(outEvent);
- _this.freeEvent(leaveEvent);
- }
- _this.cursor = null;
- };
- this.onPointerOver = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData = _this.trackingData(from.pointerId);
- var e = _this.createPointerEvent(from);
- var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
- _this.dispatchEvent(e, 'pointerover');
- if (isMouse) _this.dispatchEvent(e, 'mouseover');
- if (e.pointerType === 'mouse') _this.cursor = _this.getCursor(e.target);
- // pointerenter events must be fired since the pointer entered from upstream.
- var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
- enterEvent.eventPhase = enterEvent.AT_TARGET;
- while (enterEvent.target && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- enterEvent.currentTarget = enterEvent.target;
- _this.notifyTarget(enterEvent);
- if (isMouse) {
- // mouseenter should not bubble
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event#usage_notes
- _this.notifyTarget(enterEvent, 'mouseenter');
- }
- if (Node.isNode(enterEvent.target)) {
- enterEvent.target = enterEvent.target.parentNode;
- }
- }
- trackingData.overTargets = e.composedPath();
- _this.freeEvent(e);
- _this.freeEvent(enterEvent);
- };
- this.onPointerUpOutside = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData = _this.trackingData(from.pointerId);
- var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
- var e = _this.createPointerEvent(from);
- if (pressTarget) {
- var currentTarget = pressTarget;
- while (currentTarget) {
- e.currentTarget = currentTarget;
- _this.notifyTarget(e, 'pointerupoutside');
- if (e.pointerType === 'touch') ; else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- _this.notifyTarget(e, e.button === 2 ? 'rightupoutside' : 'mouseupoutside');
- }
- if (Node.isNode(currentTarget)) {
- currentTarget = currentTarget.parentNode;
- }
- }
- delete trackingData.pressTargetsByButton[from.button];
- }
- _this.freeEvent(e);
- };
- this.onWheel = function (from) {
- // if (!(from instanceof FederatedWheelEvent)) {
- // return;
- // }
- var wheelEvent = _this.createWheelEvent(from);
- _this.dispatchEvent(wheelEvent);
- _this.freeEvent(wheelEvent);
- };
- this.onClick = function (from) {
- if (_this.context.config.useNativeClickEvent) {
- var e = _this.createPointerEvent(from);
- _this.dispatchEvent(e);
- _this.freeEvent(e);
- }
- };
- this.onPointerCancel = function (from) {
- var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
- _this.dispatchEvent(e);
- _this.freeEvent(e);
- };
- this.globalRuntime = globalRuntime;
- this.context = context;
- }
- var _proto = EventService.prototype;
- _proto.init = function init() {
- this.rootTarget = this.context.renderingContext.root.parentNode; // document
- this.addEventMapping('pointerdown', this.onPointerDown);
- this.addEventMapping('pointerup', this.onPointerUp);
- this.addEventMapping('pointermove', this.onPointerMove);
- this.addEventMapping('pointerout', this.onPointerOut);
- this.addEventMapping('pointerleave', this.onPointerOut);
- this.addEventMapping('pointercancel', this.onPointerCancel);
- this.addEventMapping('pointerover', this.onPointerOver);
- this.addEventMapping('pointerupoutside', this.onPointerUpOutside);
- this.addEventMapping('wheel', this.onWheel);
- this.addEventMapping('click', this.onClick);
- };
- _proto.destroy = function destroy() {
- this.emitter.removeAllListeners();
- this.mappingTable = {};
- this.mappingState = {};
- this.eventPool.clear();
- };
- _proto.client2Viewport = function client2Viewport(client) {
- var bbox = this.context.contextService.getBoundingClientRect();
- 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));
- };
- _proto.viewport2Client = function viewport2Client(canvas) {
- var bbox = this.context.contextService.getBoundingClientRect();
- 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));
- };
- _proto.viewport2Canvas = function viewport2Canvas(_ref) {
- var x = _ref.x,
- y = _ref.y;
- var canvas = this.rootTarget.defaultView;
- var camera = canvas.getCamera();
- var _this$context$config = this.context.config,
- width = _this$context$config.width,
- height = _this$context$config.height;
- var projectionMatrixInverse = camera.getPerspectiveInverse();
- var worldMatrix = camera.getWorldTransform();
- var vpMatrix = mat4.multiply(this.tmpMatrix, worldMatrix, projectionMatrixInverse);
- var viewport = vec3.set(this.tmpVec3, x / width * 2 - 1, (1 - y / height) * 2 - 1, 0);
- vec3.transformMat4(viewport, viewport, vpMatrix);
- return new Point(viewport[0], viewport[1]);
- };
- _proto.canvas2Viewport = function canvas2Viewport(canvasP) {
- var canvas = this.rootTarget.defaultView;
- var camera = canvas.getCamera();
- // World -> Clip
- var projectionMatrix = camera.getPerspective();
- var viewMatrix = camera.getViewTransform();
- var vpMatrix = mat4.multiply(this.tmpMatrix, projectionMatrix, viewMatrix);
- var clip = vec3.set(this.tmpVec3, canvasP.x, canvasP.y, 0);
- vec3.transformMat4(this.tmpVec3, this.tmpVec3, vpMatrix);
- // Clip -> NDC -> Viewport, flip Y
- var _this$context$config2 = this.context.config,
- width = _this$context$config2.width,
- height = _this$context$config2.height;
- return new Point((clip[0] + 1) / 2 * width, (1 - (clip[1] + 1) / 2) * height);
- };
- _proto.setPickHandler = function setPickHandler(pickHandler) {
- this.pickHandler = pickHandler;
- };
- _proto.addEventMapping = function addEventMapping(type, fn) {
- if (!this.mappingTable[type]) {
- this.mappingTable[type] = [];
- }
- this.mappingTable[type].push({
- fn: fn,
- priority: 0
- });
- this.mappingTable[type].sort(function (a, b) {
- return a.priority - b.priority;
- });
- };
- _proto.mapEvent = function mapEvent(e) {
- if (!this.rootTarget) {
- return;
- }
- var mappers = this.mappingTable[e.type];
- if (mappers) {
- for (var i = 0, j = mappers.length; i < j; i++) {
- mappers[i].fn(e);
- }
- } else {
- console.warn("[EventService]: Event mapping not defined for " + e.type);
- }
- };
- _proto.dispatchEvent = function dispatchEvent(e, type, skipPropagate) {
- // Canvas should skip
- if (!skipPropagate) {
- e.propagationStopped = false;
- e.propagationImmediatelyStopped = false;
- this.propagate(e, type);
- } else {
- // target phase
- e.eventPhase = e.AT_TARGET;
- var canvas = this.rootTarget.defaultView || null;
- e.currentTarget = canvas;
- this.notifyListeners(e, type);
- }
- this.emitter.emit(type || e.type, e);
- };
- _proto.propagate = function propagate(e, type) {
- if (!e.target) {
- return;
- }
- // [target, parent, root, Canvas]
- var composedPath = e.composedPath();
- // event flow: capture -> target -> bubbling
- // capture phase
- e.eventPhase = e.CAPTURING_PHASE;
- for (var i = composedPath.length - 1; i >= 1; i--) {
- e.currentTarget = composedPath[i];
- this.notifyTarget(e, type);
- if (e.propagationStopped || e.propagationImmediatelyStopped) return;
- }
- // target phase
- e.eventPhase = e.AT_TARGET;
- e.currentTarget = e.target;
- this.notifyTarget(e, type);
- if (e.propagationStopped || e.propagationImmediatelyStopped) return;
- // find current target in composed path
- var index = composedPath.indexOf(e.currentTarget);
- // bubbling phase
- e.eventPhase = e.BUBBLING_PHASE;
- for (var _i = index + 1; _i < composedPath.length; _i++) {
- e.currentTarget = composedPath[_i];
- this.notifyTarget(e, type);
- if (e.propagationStopped || e.propagationImmediatelyStopped) return;
- }
- };
- _proto.propagationPath = function propagationPath(target) {
- var propagationPath = [target];
- var canvas = this.rootTarget.defaultView || null;
- if (canvas && canvas === target) {
- propagationPath.unshift(canvas.document);
- return propagationPath;
- }
- for (var i = 0; i < PROPAGATION_LIMIT && target !== this.rootTarget; i++) {
- // if (Node.isNode(target) && !target.parentNode) {
- // throw new Error('Cannot find propagation path to disconnected target');
- // }
- if (Node.isNode(target) && target.parentNode) {
- // [target, parent, parent, root]
- propagationPath.push(target.parentNode);
- target = target.parentNode;
- }
- }
- if (canvas) {
- // @ts-ignore
- propagationPath.push(canvas);
- }
- return propagationPath;
- };
- _proto.hitTest = function hitTest(position) {
- var viewportX = position.viewportX,
- viewportY = position.viewportY;
- var _this$context$config3 = this.context.config,
- width = _this$context$config3.width,
- height = _this$context$config3.height;
- // outside canvas
- if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
- return null;
- }
- return this.pickHandler(position) || this.rootTarget ||
- // return Document
- null;
- }
- /**
- * whether the native event trigger came from Canvas,
- * should account for HTML shape
- */;
- _proto.isNativeEventFromCanvas = function isNativeEventFromCanvas(event) {
- var _event$nativeEvent;
- var $el = this.context.contextService.getDomElement();
- var target = (_event$nativeEvent = event.nativeEvent) === null || _event$nativeEvent === void 0 ? void 0 : _event$nativeEvent.target;
- if (target) {
- // from <canvas>
- if (target === $el) {
- return true;
- }
- // from <svg>
- if ($el && $el.contains) {
- return $el.contains(target);
- }
- }
- if (event.nativeEvent.composedPath) {
- return event.nativeEvent.composedPath().indexOf($el) > -1;
- }
- // account for Touch
- return false;
- }
- /**
- * Find HTML from composed path in native UI event.
- */;
- _proto.getExistedHTML = function getExistedHTML(event) {
- if (event.nativeEvent.composedPath) {
- for (var _iterator = _createForOfIteratorHelperLoose(event.nativeEvent.composedPath()), _step; !(_step = _iterator()).done;) {
- var eventTarget = _step.value;
- var existed = runtime.nativeHTMLMap.get(eventTarget);
- if (existed) {
- return existed;
- }
- }
- }
- return null;
- };
- _proto.pickTarget = function pickTarget(event) {
- return this.hitTest({
- clientX: event.clientX,
- clientY: event.clientY,
- viewportX: event.viewportX,
- viewportY: event.viewportY,
- x: event.canvasX,
- y: event.canvasY
- });
- };
- _proto.createPointerEvent = function createPointerEvent(from, type, target, fallbackTarget) {
- var event = this.allocateEvent(FederatedPointerEvent);
- this.copyPointerData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from;
- var existedHTML = this.getExistedHTML(event);
- event.target = target !== null && target !== void 0 ? target : existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event) || fallbackTarget;
- if (typeof type === 'string') {
- event.type = type;
- }
- return event;
- };
- _proto.createWheelEvent = function createWheelEvent(from) {
- var event = this.allocateEvent(FederatedWheelEvent);
- this.copyWheelData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from;
- var existedHTML = this.getExistedHTML(event);
- event.target = existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event);
- return event;
- };
- _proto.trackingData = function trackingData(id) {
- if (!this.mappingState.trackingData[id]) {
- this.mappingState.trackingData[id] = {
- pressTargetsByButton: {},
- clicksByButton: {},
- overTarget: null
- };
- }
- return this.mappingState.trackingData[id];
- };
- _proto.cloneWheelEvent = function cloneWheelEvent(from) {
- var event = this.allocateEvent(FederatedWheelEvent);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from.originalEvent;
- this.copyWheelData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.target = from.target;
- event.path = from.composedPath().slice();
- event.type = from.type;
- return event;
- };
- _proto.clonePointerEvent = function clonePointerEvent(from, type) {
- var event = this.allocateEvent(FederatedPointerEvent);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from.originalEvent;
- this.copyPointerData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.target = from.target;
- event.path = from.composedPath().slice();
- event.type = type !== null && type !== void 0 ? type : event.type;
- return event;
- };
- _proto.copyPointerData = function copyPointerData(from, to) {
- // if (
- // !(
- // from instanceof FederatedPointerEvent &&
- // to instanceof FederatedPointerEvent
- // )
- // )
- // return;
- to.pointerId = from.pointerId;
- to.width = from.width;
- to.height = from.height;
- to.isPrimary = from.isPrimary;
- to.pointerType = from.pointerType;
- to.pressure = from.pressure;
- to.tangentialPressure = from.tangentialPressure;
- to.tiltX = from.tiltX;
- to.tiltY = from.tiltY;
- to.twist = from.twist;
- };
- _proto.copyMouseData = function copyMouseData(from, to) {
- // if (
- // !(
- // from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent
- // )
- // )
- // return;
- to.altKey = from.altKey;
- to.button = from.button;
- to.buttons = from.buttons;
- to.ctrlKey = from.ctrlKey;
- to.metaKey = from.metaKey;
- to.shiftKey = from.shiftKey;
- to.client.copyFrom(from.client);
- to.movement.copyFrom(from.movement);
- to.canvas.copyFrom(from.canvas);
- to.screen.copyFrom(from.screen);
- to.global.copyFrom(from.global);
- to.offset.copyFrom(from.offset);
- };
- _proto.copyWheelData = function copyWheelData(from, to) {
- to.deltaMode = from.deltaMode;
- to.deltaX = from.deltaX;
- to.deltaY = from.deltaY;
- to.deltaZ = from.deltaZ;
- };
- _proto.copyData = function copyData(from, to) {
- to.isTrusted = from.isTrusted;
- to.timeStamp = performance.now();
- to.type = from.type;
- to.detail = from.detail;
- to.view = from.view;
- to.page.copyFrom(from.page);
- to.viewport.copyFrom(from.viewport);
- };
- _proto.allocateEvent = function allocateEvent(constructor) {
- if (!this.eventPool.has(constructor)) {
- this.eventPool.set(constructor, []);
- }
- // @ts-ignore
- var event = this.eventPool.get(constructor).pop() || new constructor(this);
- event.eventPhase = event.NONE;
- event.currentTarget = null;
- event.path = [];
- event.target = null;
- return event;
- };
- _proto.freeEvent = function freeEvent(event) {
- if (event.manager !== this) throw new Error('It is illegal to free an event not managed by this EventBoundary!');
- var constructor = event.constructor;
- if (!this.eventPool.has(constructor)) {
- this.eventPool.set(constructor, []);
- }
- // @ts-ignore
- this.eventPool.get(constructor).push(event);
- };
- _proto.notifyTarget = function notifyTarget(e, type) {
- var _type;
- type = (_type = type) !== null && _type !== void 0 ? _type : e.type;
- var key = e.eventPhase === e.CAPTURING_PHASE || e.eventPhase === e.AT_TARGET ? type + "capture" : type;
- this.notifyListeners(e, key);
- if (e.eventPhase === e.AT_TARGET) {
- this.notifyListeners(e, type);
- }
- };
- _proto.notifyListeners = function notifyListeners(e, type) {
- // hack EventEmitter, stops if the `propagationImmediatelyStopped` flag is set
- // @ts-ignore
- var emitter = e.currentTarget.emitter;
- // @ts-ignore
- var listeners = emitter._events[type];
- if (!listeners) return;
- if ('fn' in listeners) {
- if (listeners.once) {
- emitter.removeListener(type, listeners.fn, undefined, true);
- }
- listeners.fn.call(e.currentTarget || listeners.context, e);
- // listeners.fn.call(listeners.context, e);
- } else {
- for (var i = 0; i < listeners.length && !e.propagationImmediatelyStopped; i++) {
- if (listeners[i].once) {
- emitter.removeListener(type, listeners[i].fn, undefined, true);
- }
- listeners[i].fn.call(e.currentTarget || listeners[i].context, e);
- // listeners[i].fn.call(listeners[i].context, e);
- }
- }
- }
- /**
- * some detached nodes may exist in propagation path, need to skip them
- */;
- _proto.findMountedTarget = function findMountedTarget(propagationPath) {
- if (!propagationPath) {
- return null;
- }
- var currentTarget = propagationPath[propagationPath.length - 1];
- for (var i = propagationPath.length - 2; i >= 0; i--) {
- var target = propagationPath[i];
- if (target === this.rootTarget || Node.isNode(target) && target.parentNode === currentTarget) {
- currentTarget = propagationPath[i];
- } else {
- break;
- }
- }
- return currentTarget;
- };
- _proto.getCursor = function getCursor(target) {
- var tmp = target;
- while (tmp) {
- var cursor = Element.isElement(tmp) && tmp.getAttribute('cursor');
- if (cursor) {
- return cursor;
- }
- tmp = Node.isNode(tmp) && tmp.parentNode;
- }
- };
- return EventService;
- }();
- /**
- * used in following scenes:
- * - g `ctx.measureText`
- * - g-plugin-canvas-picker `ctx.isPointInPath`
- * - g-plugin-device-renderer `ctx.createLinearGradient` and generate texture
- *
- * @see https://blog.scottlogic.com/2020/03/19/offscreen-canvas.html
- */
- var OffscreenCanvasCreator = /*#__PURE__*/function () {
- function OffscreenCanvasCreator() {
- this.canvas = void 0;
- this.context = void 0;
- }
- var _proto = OffscreenCanvasCreator.prototype;
- _proto.getOrCreateCanvas = function getOrCreateCanvas(offscreenCanvas, contextAttributes) {
- if (this.canvas) {
- return this.canvas;
- }
- // user-defined offscreen canvas
- if (offscreenCanvas) {
- this.canvas = offscreenCanvas;
- this.context = this.canvas.getContext('2d', contextAttributes);
- } else {
- try {
- // OffscreenCanvas2D measureText can be up to 40% faster.
- this.canvas = new window.OffscreenCanvas(0, 0);
- this.context = this.canvas.getContext('2d', contextAttributes);
- if (!this.context || !this.context.measureText) {
- this.canvas = document.createElement('canvas');
- this.context = this.canvas.getContext('2d');
- }
- } catch (ex) {
- this.canvas = document.createElement('canvas');
- this.context = this.canvas.getContext('2d', contextAttributes);
- }
- }
- this.canvas.width = 10;
- this.canvas.height = 10;
- return this.canvas;
- };
- _proto.getOrCreateContext = function getOrCreateContext(offscreenCanvas, contextAttributes) {
- if (this.context) {
- return this.context;
- }
- this.getOrCreateCanvas(offscreenCanvas, contextAttributes);
- return this.context;
- };
- return OffscreenCanvasCreator;
- }();
- /**
- * why we need re-render
- */
- var RenderReason;
- (function (RenderReason) {
- RenderReason[RenderReason["CAMERA_CHANGED"] = 0] = "CAMERA_CHANGED";
- RenderReason[RenderReason["DISPLAY_OBJECT_CHANGED"] = 1] = "DISPLAY_OBJECT_CHANGED";
- RenderReason[RenderReason["NONE"] = 2] = "NONE";
- })(RenderReason || (RenderReason = {}));
- /**
- * Use frame renderer implemented by `g-canvas/svg/webgl`, in every frame we do followings:
- * * update & merge dirty rectangles
- * * begin frame
- * * filter by visible
- * * sort by z-index in scene graph
- * * culling with strategies registered in `g-canvas/webgl`
- * * end frame
- */
- var RenderingService = /*#__PURE__*/function () {
- function RenderingService(globalRuntime, context) {
- this.globalRuntime = void 0;
- this.context = void 0;
- this.inited = false;
- this.stats = {
- /**
- * total display objects in scenegraph
- */
- total: 0,
- /**
- * number of display objects need to render in current frame
- */
- rendered: 0
- };
- this.zIndexCounter = 0;
- this.hooks = {
- /**
- * called before any frame rendered
- */
- init: new SyncHook(),
- initAsync: new AsyncParallelHook(),
- /**
- * only dirty object which has sth changed will be rendered
- */
- dirtycheck: new SyncWaterfallHook(),
- /**
- * do culling
- */
- cull: new SyncWaterfallHook(),
- /**
- * called at beginning of each frame, won't get called if nothing to re-render
- */
- beginFrame: new SyncHook(),
- /**
- * called before every dirty object get rendered
- */
- beforeRender: new SyncHook(),
- /**
- * called when every dirty object rendering even it's culled
- */
- render: new SyncHook(),
- /**
- * called after every dirty object get rendered
- */
- afterRender: new SyncHook(),
- endFrame: new SyncHook(),
- destroy: new SyncHook(),
- /**
- * use async but faster method such as GPU-based picking in `g-plugin-device-renderer`
- */
- pick: new AsyncSeriesWaterfallHook(),
- /**
- * Unsafe but sync version of pick.
- */
- pickSync: new SyncWaterfallHook(),
- /**
- * used in event system
- */
- pointerDown: new SyncHook(),
- pointerUp: new SyncHook(),
- pointerMove: new SyncHook(),
- pointerOut: new SyncHook(),
- pointerOver: new SyncHook(),
- pointerWheel: new SyncHook(),
- pointerCancel: new SyncHook(),
- click: new SyncHook()
- };
- this.globalRuntime = globalRuntime;
- this.context = context;
- }
- var _proto = RenderingService.prototype;
- _proto.init = function init(callback) {
- var _this = this;
- var context = _extends({}, this.globalRuntime, this.context);
- // register rendering plugins
- this.context.renderingPlugins.forEach(function (plugin) {
- plugin.apply(context, runtime);
- });
- this.hooks.init.call();
- if (this.hooks.initAsync.getCallbacksNum() === 0) {
- this.inited = true;
- callback();
- } else {
- this.hooks.initAsync.promise().then(function () {
- _this.inited = true;
- callback();
- });
- }
- };
- _proto.getStats = function getStats() {
- return this.stats;
- }
- /**
- * Meet the following conditions:
- * * disable DirtyRectangleRendering
- * * camera changed
- */;
- _proto.disableDirtyRectangleRendering = function disableDirtyRectangleRendering() {
- var renderer = this.context.config.renderer;
- var _renderer$getConfig = renderer.getConfig(),
- enableDirtyRectangleRendering = _renderer$getConfig.enableDirtyRectangleRendering;
- return !enableDirtyRectangleRendering || this.context.renderingContext.renderReasons.has(RenderReason.CAMERA_CHANGED);
- };
- _proto.render = function render(canvasConfig, rerenderCallback) {
- var _this2 = this;
- this.stats.total = 0;
- this.stats.rendered = 0;
- this.zIndexCounter = 0;
- var renderingContext = this.context.renderingContext;
- this.globalRuntime.sceneGraphService.syncHierarchy(renderingContext.root);
- this.globalRuntime.sceneGraphService.triggerPendingEvents();
- if (renderingContext.renderReasons.size && this.inited) {
- this.renderDisplayObject(renderingContext.root, canvasConfig, renderingContext);
- this.hooks.beginFrame.call();
- renderingContext.renderListCurrentFrame.forEach(function (object) {
- _this2.hooks.beforeRender.call(object);
- _this2.hooks.render.call(object);
- _this2.hooks.afterRender.call(object);
- });
- this.hooks.endFrame.call();
- renderingContext.renderListCurrentFrame = [];
- renderingContext.renderReasons.clear();
- rerenderCallback();
- }
- // console.log('stats', this.stats);
- };
- _proto.renderDisplayObject = function renderDisplayObject(displayObject, canvasConfig, renderingContext) {
- var _this3 = this;
- var _canvasConfig$rendere = canvasConfig.renderer.getConfig(),
- enableDirtyCheck = _canvasConfig$rendere.enableDirtyCheck,
- enableCulling = _canvasConfig$rendere.enableCulling;
- // recalc style values
- if (this.globalRuntime.enableCSSParsing) {
- this.globalRuntime.styleValueRegistry.recalc(displayObject);
- }
- // TODO: relayout
- // dirtycheck first
- var objectChanged = enableDirtyCheck ? this.hooks.dirtycheck.call(displayObject) : displayObject;
- if (objectChanged) {
- var objectToRender = enableCulling ? this.hooks.cull.call(objectChanged, this.context.camera) : objectChanged;
- if (objectToRender) {
- this.stats.rendered++;
- renderingContext.renderListCurrentFrame.push(objectToRender);
- }
- }
- displayObject.renderable.dirty = false;
- displayObject.sortable.renderOrder = this.zIndexCounter++;
- this.stats.total++;
- // sort is very expensive, use cached result if possible
- var sortable = displayObject.sortable;
- if (sortable.dirty) {
- this.sort(displayObject, sortable);
- sortable.dirty = false;
- sortable.dirtyChildren = [];
- sortable.dirtyReason = undefined;
- }
- // recursive rendering its children
- (sortable.sorted || displayObject.childNodes).forEach(function (child) {
- _this3.renderDisplayObject(child, canvasConfig, renderingContext);
- });
- };
- _proto.sort = function sort(displayObject, sortable) {
- if (sortable.sorted && sortable.dirtyReason !== SortReason.Z_INDEX_CHANGED) {
- // avoid re-sorting the whole children list
- sortable.dirtyChildren.forEach(function (child) {
- var index = displayObject.childNodes.indexOf(child);
- if (index === -1) {
- // remove from sorted list
- var _index = sortable.sorted.indexOf(child);
- if (_index >= 0) {
- sortable.sorted.splice(_index, 1);
- }
- } else {
- if (sortable.sorted.length === 0) {
- sortable.sorted.push(child);
- } else {
- var _index2 = sortedIndex(sortable.sorted, child);
- sortable.sorted.splice(_index2, 0, child);
- }
- }
- });
- } else {
- sortable.sorted = displayObject.childNodes.slice().sort(sortByZIndex);
- }
- };
- _proto.destroy = function destroy() {
- this.inited = false;
- this.hooks.destroy.call();
- this.globalRuntime.sceneGraphService.clearPendingEvents();
- };
- _proto.dirtify = function dirtify() {
- // need re-render
- this.context.renderingContext.renderReasons.add(RenderReason.DISPLAY_OBJECT_CHANGED);
- };
- return RenderingService;
- }();
- var ATTRIBUTE_REGEXP = /\[\s*(.*)=(.*)\s*\]/;
- /**
- * support the following DOM API:
- * * getElementById
- * * getElementsByClassName
- * * getElementsByName
- * * getElementsByTag
- * * querySelector
- * * querySelectorAll
- */
- var DefaultSceneGraphSelector = /*#__PURE__*/function () {
- function DefaultSceneGraphSelector() {}
- var _proto = DefaultSceneGraphSelector.prototype;
- _proto.selectOne = function selectOne(query, root) {
- var _this = this;
- if (query.startsWith('.')) {
- return root.find(function (node) {
- // return !node.shadow && node.id === query.substring(1);
- return ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this.getIdOrClassname(query)) > -1;
- });
- } else if (query.startsWith('#')) {
- // getElementById('id')
- return root.find(function (node) {
- // return !node.shadow && node.id === query.substring(1);
- return node.id === _this.getIdOrClassname(query);
- });
- } else if (query.startsWith('[')) {
- var _this$getAttribute = this.getAttribute(query),
- name = _this$getAttribute.name,
- value = _this$getAttribute.value;
- if (name) {
- // getElementByName();
- return root.find(function (node) {
- return root !== node && (name === 'name' ? node.name === value : _this.attributeToString(node, name) === value);
- });
- } else {
- return null;
- }
- } else {
- // getElementsByTag('circle');
- return root.find(function (node) {
- return root !== node && node.nodeName === query;
- });
- }
- };
- _proto.selectAll = function selectAll(query, root) {
- var _this2 = this;
- // only support `[name="${name}"]` `.className` `#id`
- if (query.startsWith('.')) {
- // getElementsByClassName('className');
- // should not include itself
- return root.findAll(function (node) {
- return root !== node && ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this2.getIdOrClassname(query)) > -1;
- });
- } else if (query.startsWith('#')) {
- return root.findAll(function (node) {
- return root !== node && node.id === _this2.getIdOrClassname(query);
- });
- } else if (query.startsWith('[')) {
- var _this$getAttribute2 = this.getAttribute(query),
- name = _this$getAttribute2.name,
- value = _this$getAttribute2.value;
- if (name) {
- // getElementsByName();
- return root.findAll(function (node) {
- return root !== node && (name === 'name' ? node.name === value : _this2.attributeToString(node, name) === value);
- });
- } else {
- return [];
- }
- } else {
- // getElementsByTag('circle');
- return root.findAll(function (node) {
- return root !== node && node.nodeName === query;
- });
- }
- };
- _proto.is = function is(query, node) {
- // a simple `matches` implementation
- if (query.startsWith('.')) {
- return node.className === this.getIdOrClassname(query);
- } else if (query.startsWith('#')) {
- return node.id === this.getIdOrClassname(query);
- } else if (query.startsWith('[')) {
- var _this$getAttribute3 = this.getAttribute(query),
- name = _this$getAttribute3.name,
- value = _this$getAttribute3.value;
- return name === 'name' ? node.name === value : this.attributeToString(node, name) === value;
- } else {
- return node.nodeName === query;
- }
- };
- _proto.getIdOrClassname = function getIdOrClassname(query) {
- return query.substring(1);
- };
- _proto.getAttribute = function getAttribute(query) {
- var matches = query.match(ATTRIBUTE_REGEXP);
- var name = '';
- var value = '';
- if (matches && matches.length > 2) {
- name = matches[1].replace(/"/g, '');
- value = matches[2].replace(/"/g, '');
- }
- return {
- name: name,
- value: value
- };
- };
- _proto.attributeToString = function attributeToString(node, name) {
- if (!node.getAttribute) {
- return '';
- }
- var value = node.getAttribute(name);
- if (isNil(value)) {
- return '';
- }
- if (value.toString) {
- return value.toString();
- }
- return '';
- };
- return DefaultSceneGraphSelector;
- }();
- function markRenderableDirty(e) {
- var renderable = e.renderable;
- if (renderable) {
- renderable.renderBoundsDirty = true;
- renderable.boundsDirty = true;
- }
- }
- var reparentEvent = new MutationEvent(ElementEvent.REPARENT, null, '', '', '', 0, '', '');
- /**
- * update transform in scene graph
- *
- * @see https://community.khronos.org/t/scene-graphs/50542/7
- */
- var DefaultSceneGraphService = /*#__PURE__*/function () {
- function DefaultSceneGraphService(runtime) {
- var _this = this;
- this.runtime = void 0;
- this.pendingEvents = [];
- this.boundsChangedEvent = new CustomEvent(ElementEvent.BOUNDS_CHANGED);
- /**
- * rotate in world space
- */
- this.rotate = function () {
- var parentInvertRotation = quat$1.create();
- return function (element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = vec3.fromValues(degrees, y, z);
- }
- var transform = element.transformable;
- if (element.parentNode === null || !element.parentNode.transformable) {
- _this.rotateLocal(element, degrees);
- } else {
- var rotation = quat$1.create();
- quat$1.fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
- var rot = _this.getRotation(element);
- var parentRot = _this.getRotation(element.parentNode);
- quat$1.copy(parentInvertRotation, parentRot);
- quat$1.invert(parentInvertRotation, parentInvertRotation);
- quat$1.multiply(rotation, parentInvertRotation, rotation);
- quat$1.multiply(transform.localRotation, rotation, rot);
- quat$1.normalize(transform.localRotation, transform.localRotation);
- _this.dirtifyLocal(element, transform);
- }
- };
- }();
- /**
- * rotate in local space
- * @see @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw
- */
- this.rotateLocal = function () {
- var rotation = quat$1.create();
- return function (element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = vec3.fromValues(degrees, y, z);
- }
- var transform = element.transformable;
- quat$1.fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
- quat$1.mul(transform.localRotation, transform.localRotation, rotation);
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * set euler angles(degrees) in world space
- */
- this.setEulerAngles = function () {
- var invParentRot = quat$1.create();
- return function (element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = vec3.fromValues(degrees, y, z);
- }
- var transform = element.transformable;
- if (element.parentNode === null || !element.parentNode.transformable) {
- _this.setLocalEulerAngles(element, degrees);
- } else {
- quat$1.fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
- var parentRotation = _this.getRotation(element.parentNode);
- quat$1.copy(invParentRot, quat$1.invert(quat$1.create(), parentRotation));
- quat$1.mul(transform.localRotation, transform.localRotation, invParentRot);
- _this.dirtifyLocal(element, transform);
- }
- };
- }();
- /**
- * translate in local space
- *
- * @example
- * ```
- * translateLocal(x, y, z)
- * translateLocal(vec3(x, y, z))
- * ```
- */
- this.translateLocal = function () {
- return function (element, translation, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof translation === 'number') {
- translation = vec3.fromValues(translation, y, z);
- }
- var transform = element.transformable;
- if (vec3.equals(translation, vec3.create())) {
- return;
- }
- vec3.transformQuat(translation, translation, transform.localRotation);
- vec3.add(transform.localPosition, transform.localPosition, translation);
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * move to position in world space
- *
- * 对应 g 原版的 move/moveTo
- * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L684-L689
- */
- this.setPosition = function () {
- var parentInvertMatrix = mat4.create();
- var tmpPosition = vec3.create();
- return function (element, position) {
- var transform = element.transformable;
- tmpPosition[0] = position[0];
- tmpPosition[1] = position[1];
- tmpPosition[2] = position[2] || 0;
- if (vec3.equals(_this.getPosition(element), tmpPosition)) {
- return;
- }
- vec3.copy(transform.position, tmpPosition);
- if (element.parentNode === null || !element.parentNode.transformable) {
- vec3.copy(transform.localPosition, tmpPosition);
- } else {
- var parentTransform = element.parentNode.transformable;
- mat4.copy(parentInvertMatrix, parentTransform.worldTransform);
- mat4.invert(parentInvertMatrix, parentInvertMatrix);
- vec3.transformMat4(transform.localPosition, tmpPosition, parentInvertMatrix);
- }
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * move to position in local space
- */
- this.setLocalPosition = function () {
- var tmpPosition = vec3.create();
- return function (element, position) {
- var transform = element.transformable;
- tmpPosition[0] = position[0];
- tmpPosition[1] = position[1];
- tmpPosition[2] = position[2] || 0;
- if (vec3.equals(transform.localPosition, tmpPosition)) {
- return;
- }
- vec3.copy(transform.localPosition, tmpPosition);
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * translate in world space
- *
- * @example
- * ```
- * translate(x, y, z)
- * translate(vec3(x, y, z))
- * ```
- *
- * 对应 g 原版的 translate 2D
- * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L665-L676
- */
- this.translate = function () {
- var zeroVec3 = vec3.create();
- var tmpVec3 = vec3.create();
- var tr = vec3.create();
- return function (element, translation, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof translation === 'number') {
- translation = vec3.set(tmpVec3, translation, y, z);
- }
- if (vec3.equals(translation, zeroVec3)) {
- return;
- }
- vec3.add(tr, _this.getPosition(element), translation);
- _this.setPosition(element, tr);
- };
- }();
- this.setRotation = function () {
- var parentInvertRotation = quat$1.create();
- return function (element, rotation, y, z, w) {
- var transform = element.transformable;
- if (typeof rotation === 'number') {
- rotation = quat$1.fromValues(rotation, y, z, w);
- }
- if (element.parentNode === null || !element.parentNode.transformable) {
- _this.setLocalRotation(element, rotation);
- } else {
- var parentRot = _this.getRotation(element.parentNode);
- quat$1.copy(parentInvertRotation, parentRot);
- quat$1.invert(parentInvertRotation, parentInvertRotation);
- quat$1.multiply(transform.localRotation, parentInvertRotation, rotation);
- quat$1.normalize(transform.localRotation, transform.localRotation);
- _this.dirtifyLocal(element, transform);
- }
- };
- };
- this.displayObjectDependencyMap = new WeakMap();
- this.calcLocalTransform = function () {
- var tmpMat = mat4.create();
- var tmpPosition = vec3.create();
- var tmpQuat = quat$1.fromValues(0, 0, 0, 1);
- return function (transform) {
- var hasSkew = transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0;
- if (hasSkew) {
- mat4.fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, vec3.fromValues(1, 1, 1), transform.origin);
- // apply skew2D
- if (transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0) {
- var tmpMat4 = mat4.identity(tmpMat);
- tmpMat4[4] = Math.tan(transform.localSkew[0]);
- tmpMat4[1] = Math.tan(transform.localSkew[1]);
- mat4.multiply(transform.localTransform, transform.localTransform, tmpMat4);
- }
- var scaling = mat4.fromRotationTranslationScaleOrigin(tmpMat, tmpQuat, tmpPosition, transform.localScale, transform.origin);
- mat4.multiply(transform.localTransform, transform.localTransform, scaling);
- } else {
- // @see https://github.com/mattdesl/css-mat4/blob/master/index.js
- mat4.fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, transform.localScale, transform.origin);
- }
- };
- }();
- this.runtime = runtime;
- }
- var _proto = DefaultSceneGraphService.prototype;
- _proto.matches = function matches(query, root) {
- return this.runtime.sceneGraphSelector.is(query, root);
- };
- _proto.querySelector = function querySelector(query, root) {
- return this.runtime.sceneGraphSelector.selectOne(query, root);
- };
- _proto.querySelectorAll = function querySelectorAll(query, root) {
- return this.runtime.sceneGraphSelector.selectAll(query, root);
- // .filter((node) => !node.shadow);
- };
- _proto.attach = function attach(child, parent, index) {
- var _sortable$sorted, _child$style;
- var detached = false;
- if (child.parentNode) {
- detached = child.parentNode !== parent;
- this.detach(child);
- }
- child.parentNode = parent;
- if (!isNil(index)) {
- child.parentNode.childNodes.splice(index, 0, child);
- } else {
- child.parentNode.childNodes.push(child);
- }
- // parent needs re-sort
- var sortable = parent.sortable;
- 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)) {
- if (sortable.dirtyChildren.indexOf(child) === -1) {
- sortable.dirtyChildren.push(child);
- }
- // if (sortable) {
- // only child has z-Index
- sortable.dirty = true;
- sortable.dirtyReason = SortReason.ADDED;
- }
- // this.updateGraphDepth(child);
- var transform = child.transformable;
- if (transform) {
- this.dirtifyWorld(child, transform);
- }
- if (transform.frozen) {
- this.unfreezeParentToRoot(child);
- }
- if (detached) {
- child.dispatchEvent(reparentEvent);
- }
- };
- _proto.detach = function detach(child) {
- if (child.parentNode) {
- var _sortable$sorted2, _child$style2;
- var transform = child.transformable;
- // if (transform) {
- // const worldTransform = this.getWorldTransform(child, transform);
- // mat4.getScaling(transform.localScale, worldTransform);
- // mat4.getTranslation(transform.localPosition, worldTransform);
- // mat4.getRotation(transform.localRotation, worldTransform);
- // transform.localDirtyFlag = true;
- // }
- // parent needs re-sort
- var sortable = child.parentNode.sortable;
- // if (sortable) {
- 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)) {
- if (sortable.dirtyChildren.indexOf(child) === -1) {
- sortable.dirtyChildren.push(child);
- }
- sortable.dirty = true;
- sortable.dirtyReason = SortReason.REMOVED;
- }
- var index = child.parentNode.childNodes.indexOf(child);
- if (index > -1) {
- child.parentNode.childNodes.splice(index, 1);
- }
- if (transform) {
- this.dirtifyWorld(child, transform);
- }
- child.parentNode = null;
- }
- };
- _proto.getOrigin = function getOrigin(element) {
- return element.transformable.origin;
- }
- /**
- * same as pivot in Pixi.js
- *
- * @see https://stackoverflow.com/questions/40748452/how-to-change-css-transform-origin-but-preserve-transformation
- */;
- _proto.setOrigin = function setOrigin(element, origin, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof origin === 'number') {
- origin = [origin, y, z];
- }
- var transform = element.transformable;
- if (origin[0] === transform.origin[0] && origin[1] === transform.origin[1] && origin[2] === transform.origin[2]) {
- return;
- }
- var originVec = transform.origin;
- // const delta = vec3.subtract(vec3.create(), origin, originVec);
- // vec3.add(transform.localPosition, transform.localPosition, delta);
- // update origin
- originVec[0] = origin[0];
- originVec[1] = origin[1];
- originVec[2] = origin[2] || 0;
- this.dirtifyLocal(element, transform);
- };
- /**
- * set euler angles(degrees) in local space
- */
- _proto.setLocalEulerAngles = function setLocalEulerAngles(element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = vec3.fromValues(degrees, y, z);
- }
- var transform = element.transformable;
- quat$1.fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
- this.dirtifyLocal(element, transform);
- };
- /**
- * scale in local space
- */
- _proto.scaleLocal = function scaleLocal(element, scaling) {
- var transform = element.transformable;
- vec3.multiply(transform.localScale, transform.localScale, vec3.fromValues(scaling[0], scaling[1], scaling[2] || 1));
- this.dirtifyLocal(element, transform);
- };
- _proto.setLocalScale = function setLocalScale(element, scaling) {
- var transform = element.transformable;
- var updatedScaling = vec3.fromValues(scaling[0], scaling[1], scaling[2] || transform.localScale[2]);
- if (vec3.equals(updatedScaling, transform.localScale)) {
- return;
- }
- vec3.copy(transform.localScale, updatedScaling);
- this.dirtifyLocal(element, transform);
- };
- _proto.setLocalRotation = function setLocalRotation(element, rotation, y, z, w) {
- if (typeof rotation === 'number') {
- rotation = quat$1.fromValues(rotation, y, z, w);
- }
- var transform = element.transformable;
- quat$1.copy(transform.localRotation, rotation);
- this.dirtifyLocal(element, transform);
- };
- _proto.setLocalSkew = function setLocalSkew(element, skew, y) {
- if (typeof skew === 'number') {
- skew = vec2.fromValues(skew, y);
- }
- var transform = element.transformable;
- vec2.copy(transform.localSkew, skew);
- this.dirtifyLocal(element, transform);
- };
- _proto.dirtifyLocal = function dirtifyLocal(element, transform) {
- if (!transform.localDirtyFlag) {
- transform.localDirtyFlag = true;
- if (!transform.dirtyFlag) {
- this.dirtifyWorld(element, transform);
- }
- }
- };
- _proto.dirtifyWorld = function dirtifyWorld(element, transform) {
- if (!transform.dirtyFlag) {
- this.unfreezeParentToRoot(element);
- }
- this.dirtifyWorldInternal(element, transform);
- this.dirtifyToRoot(element, true);
- };
- _proto.triggerPendingEvents = function triggerPendingEvents() {
- var _this2 = this;
- var set = new Set();
- var trigger = function trigger(element, detail) {
- if (element.isConnected && !set.has(element.entity)) {
- _this2.boundsChangedEvent.detail = detail;
- _this2.boundsChangedEvent.target = element;
- if (element.isMutationObserved) {
- element.dispatchEvent(_this2.boundsChangedEvent);
- } else {
- element.ownerDocument.defaultView.dispatchEvent(_this2.boundsChangedEvent, true);
- }
- set.add(element.entity);
- }
- };
- this.pendingEvents.forEach(function (_ref) {
- var element = _ref[0],
- detail = _ref[1];
- if (detail.affectChildren) {
- element.forEach(function (e) {
- trigger(e, detail);
- });
- } else {
- trigger(element, detail);
- }
- });
- this.clearPendingEvents();
- set.clear();
- };
- _proto.clearPendingEvents = function clearPendingEvents() {
- this.pendingEvents = [];
- };
- _proto.dirtifyToRoot = function dirtifyToRoot(element, affectChildren) {
- if (affectChildren === void 0) {
- affectChildren = false;
- }
- var p = element;
- // only need to re-render itself
- if (p.renderable) {
- p.renderable.dirty = true;
- }
- while (p) {
- markRenderableDirty(p);
- p = p.parentNode;
- }
- if (affectChildren) {
- element.forEach(function (e) {
- markRenderableDirty(e);
- });
- }
- // inform dependencies
- this.informDependentDisplayObjects(element);
- // reuse the same custom event
- this.pendingEvents.push([element, {
- affectChildren: affectChildren
- }]);
- };
- _proto.updateDisplayObjectDependency = function updateDisplayObjectDependency(name, oldPath, newPath, object) {
- // clear ref to old clip path
- if (oldPath && oldPath !== newPath) {
- var oldDependencyMap = this.displayObjectDependencyMap.get(oldPath);
- if (oldDependencyMap && oldDependencyMap[name]) {
- var index = oldDependencyMap[name].indexOf(object);
- oldDependencyMap[name].splice(index, 1);
- }
- }
- if (newPath) {
- var newDependencyMap = this.displayObjectDependencyMap.get(newPath);
- if (!newDependencyMap) {
- this.displayObjectDependencyMap.set(newPath, {});
- newDependencyMap = this.displayObjectDependencyMap.get(newPath);
- }
- if (!newDependencyMap[name]) {
- newDependencyMap[name] = [];
- }
- newDependencyMap[name].push(object);
- }
- };
- _proto.informDependentDisplayObjects = function informDependentDisplayObjects(object) {
- var _this3 = this;
- var dependencyMap = this.displayObjectDependencyMap.get(object);
- if (dependencyMap) {
- Object.keys(dependencyMap).forEach(function (name) {
- dependencyMap[name].forEach(function (target) {
- _this3.dirtifyToRoot(target, true);
- target.dispatchEvent(new MutationEvent(ElementEvent.ATTR_MODIFIED, target, _this3, _this3, name, MutationEvent.MODIFICATION, _this3, _this3));
- if (target.isCustomElement && target.isConnected) {
- if (target.attributeChangedCallback) {
- target.attributeChangedCallback(name, _this3, _this3);
- }
- }
- });
- });
- }
- };
- _proto.getPosition = function getPosition(element) {
- var transform = element.transformable;
- return mat4.getTranslation(transform.position, this.getWorldTransform(element, transform));
- };
- _proto.getRotation = function getRotation(element) {
- var transform = element.transformable;
- return mat4.getRotation(transform.rotation, this.getWorldTransform(element, transform));
- };
- _proto.getScale = function getScale(element) {
- var transform = element.transformable;
- return mat4.getScaling(transform.scaling, this.getWorldTransform(element, transform));
- };
- _proto.getWorldTransform = function getWorldTransform(element, transform) {
- if (transform === void 0) {
- transform = element.transformable;
- }
- if (!transform.localDirtyFlag && !transform.dirtyFlag) {
- return transform.worldTransform;
- }
- if (element.parentNode && element.parentNode.transformable) {
- this.getWorldTransform(element.parentNode);
- }
- this.sync(element, transform);
- return transform.worldTransform;
- };
- _proto.getLocalPosition = function getLocalPosition(element) {
- return element.transformable.localPosition;
- };
- _proto.getLocalRotation = function getLocalRotation(element) {
- return element.transformable.localRotation;
- };
- _proto.getLocalScale = function getLocalScale(element) {
- return element.transformable.localScale;
- };
- _proto.getLocalSkew = function getLocalSkew(element) {
- return element.transformable.localSkew;
- };
- _proto.getLocalTransform = function getLocalTransform(element) {
- var transform = element.transformable;
- if (transform.localDirtyFlag) {
- this.calcLocalTransform(transform);
- transform.localDirtyFlag = false;
- }
- return transform.localTransform;
- };
- _proto.setLocalTransform = function setLocalTransform(element, transform) {
- var t = mat4.getTranslation(vec3.create(), transform);
- var r = mat4.getRotation(quat$1.create(), transform);
- var s = mat4.getScaling(vec3.create(), transform);
- this.setLocalScale(element, s);
- this.setLocalPosition(element, t);
- this.setLocalRotation(element, r);
- };
- _proto.resetLocalTransform = function resetLocalTransform(element) {
- this.setLocalScale(element, [1, 1, 1]);
- this.setLocalPosition(element, [0, 0, 0]);
- this.setLocalEulerAngles(element, [0, 0, 0]);
- this.setLocalSkew(element, [0, 0]);
- };
- _proto.getTransformedGeometryBounds = function getTransformedGeometryBounds(element, render, existedAABB) {
- if (render === void 0) {
- render = false;
- }
- var bounds = this.getGeometryBounds(element, render);
- if (!AABB.isEmpty(bounds)) {
- var aabb = existedAABB || new AABB();
- aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
- return aabb;
- } else {
- return null;
- }
- }
- /**
- * won't account for children
- */;
- _proto.getGeometryBounds = function getGeometryBounds(element, render) {
- if (render === void 0) {
- render = false;
- }
- var geometry = element.geometry;
- var bounds = render ? geometry.renderBounds : geometry.contentBounds || null;
- // return (bounds && new AABB(bounds.center, bounds.halfExtents)) || new AABB();
- return bounds || new AABB();
- }
- /**
- * account for children in world space
- */;
- _proto.getBounds = function getBounds(element, render) {
- var _this4 = this;
- if (render === void 0) {
- render = false;
- }
- var renderable = element.renderable;
- if (!renderable.boundsDirty && !render && renderable.bounds) {
- return renderable.bounds;
- }
- if (!renderable.renderBoundsDirty && render && renderable.renderBounds) {
- return renderable.renderBounds;
- }
- // reuse existed if possible
- var existedAABB = render ? renderable.renderBounds : renderable.bounds;
- // reset with geometry's aabb
- var aabb = this.getTransformedGeometryBounds(element, render, existedAABB);
- // merge children's aabbs
- var children = element.childNodes;
- children.forEach(function (child) {
- var childBounds = _this4.getBounds(child, render);
- if (childBounds) {
- if (!aabb) {
- aabb = existedAABB || new AABB();
- aabb.update(childBounds.center, childBounds.halfExtents);
- } else {
- aabb.add(childBounds);
- }
- }
- });
- if (render) {
- // FIXME: account for clip path
- var clipped = findClosestClipPathTarget(element);
- if (clipped) {
- // use bounds under world space
- var clipPathBounds = clipped.parsedStyle.clipPath.getBounds(render);
- if (!aabb) {
- aabb = clipPathBounds;
- } else if (clipPathBounds) {
- aabb = clipPathBounds.intersection(aabb);
- }
- }
- }
- if (!aabb) {
- aabb = new AABB();
- }
- if (aabb) {
- if (render) {
- renderable.renderBounds = aabb;
- } else {
- renderable.bounds = aabb;
- }
- }
- if (render) {
- renderable.renderBoundsDirty = false;
- } else {
- renderable.boundsDirty = false;
- }
- return aabb;
- }
- /**
- * account for children in local space
- */;
- _proto.getLocalBounds = function getLocalBounds(element) {
- if (element.parentNode) {
- var parentInvert = mat4.create();
- if (element.parentNode.transformable) {
- parentInvert = mat4.invert(mat4.create(), this.getWorldTransform(element.parentNode));
- }
- var bounds = this.getBounds(element);
- if (!AABB.isEmpty(bounds)) {
- var localBounds = new AABB();
- localBounds.setFromTransformedAABB(bounds, parentInvert);
- return localBounds;
- }
- }
- return this.getBounds(element);
- };
- _proto.getBoundingClientRect = function getBoundingClientRect(element) {
- var _element$ownerDocumen, _element$ownerDocumen2;
- var aabb;
- var bounds = this.getGeometryBounds(element);
- if (!AABB.isEmpty(bounds)) {
- aabb = new AABB();
- // apply transformation to aabb
- aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
- }
- // calc context's offset
- 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();
- if (aabb) {
- var _aabb$getMin = aabb.getMin(),
- left = _aabb$getMin[0],
- top = _aabb$getMin[1];
- var _aabb$getMax = aabb.getMax(),
- right = _aabb$getMax[0],
- bottom = _aabb$getMax[1];
- 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);
- }
- 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);
- };
- _proto.dirtifyWorldInternal = function dirtifyWorldInternal(element, transform) {
- var _this5 = this;
- if (!transform.dirtyFlag) {
- transform.dirtyFlag = true;
- transform.frozen = false;
- element.childNodes.forEach(function (child) {
- var childTransform = child.transformable;
- if (!childTransform.dirtyFlag) {
- _this5.dirtifyWorldInternal(child, childTransform);
- }
- });
- var renderable = element.renderable;
- if (renderable) {
- renderable.renderBoundsDirty = true;
- renderable.boundsDirty = true;
- renderable.dirty = true;
- }
- }
- };
- _proto.syncHierarchy = function syncHierarchy(element) {
- var transform = element.transformable;
- if (transform.frozen) {
- return;
- }
- transform.frozen = true;
- if (transform.localDirtyFlag || transform.dirtyFlag) {
- this.sync(element, transform);
- }
- var children = element.childNodes;
- for (var i = 0; i < children.length; i++) {
- this.syncHierarchy(children[i]);
- }
- };
- _proto.sync = function sync(element, transform) {
- if (transform.localDirtyFlag) {
- this.calcLocalTransform(transform);
- transform.localDirtyFlag = false;
- }
- if (transform.dirtyFlag) {
- var parent = element.parentNode;
- var parentTransform = parent && parent.transformable;
- if (parent === null || !parentTransform) {
- mat4.copy(transform.worldTransform, transform.localTransform);
- } else {
- // TODO: should we support scale compensation?
- // @see https://github.com/playcanvas/engine/issues/1077#issuecomment-359765557
- mat4.multiply(transform.worldTransform, parentTransform.worldTransform, transform.localTransform);
- }
- transform.dirtyFlag = false;
- }
- };
- _proto.unfreezeParentToRoot = function unfreezeParentToRoot(child) {
- var p = child.parentNode;
- while (p) {
- var transform = p.transformable;
- if (transform) {
- transform.frozen = false;
- }
- p = p.parentNode;
- }
- };
- return DefaultSceneGraphService;
- }();
- var TEXT_METRICS = {
- MetricsString: '|ÉqÅ',
- BaselineSymbol: 'M',
- BaselineMultiplier: 1.4,
- HeightMultiplier: 2,
- Newlines: [0x000a, 0x000d // carriage return
- ],
- BreakingSpaces: [0x0009, 0x0020, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2008, 0x2009, 0x200a, 0x205f, 0x3000 // ideographic space
- ]
- };
- var LATIN_REGEX = /[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00f6\u00f8-\u00ff!"#$%&'()*+,-./:;]/;
- // Line breaking rules in CJK (Kinsoku Shori)
- // Refer from https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
- var regexCannotStartZhCn = /[!%),.:;?\]}¢°·'""†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~]/;
- var regexCannotEndZhCn = /[$(£¥·'"〈《「『【〔〖〝﹙﹛$(.[{£¥]/;
- var regexCannotStartZhTw = /[!),.:;?\]}¢·–—'"•"、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、]/;
- var regexCannotEndZhTw = /[([{£¥'"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏]/;
- var regexCannotStartJaJp = /[)\]}〕〉》」』】〙〗〟'"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.]/;
- var regexCannotEndJaJp = /[([{〔〈《「『【〘〖〝'"⦅«—...‥〳〴〵]/;
- var regexCannotStartKoKr = /[!%),.:;?\]}¢°'"†‡℃〆〈《「『〕!%),.:;?]}]/;
- var regexCannotEndKoKr = /[$([{£¥'"々〇〉》」〔$([{⦆¥₩#]/;
- var regexCannotStart = new RegExp(regexCannotStartZhCn.source + "|" + regexCannotStartZhTw.source + "|" + regexCannotStartJaJp.source + "|" + regexCannotStartKoKr.source);
- var regexCannotEnd = new RegExp(regexCannotEndZhCn.source + "|" + regexCannotEndZhTw.source + "|" + regexCannotEndJaJp.source + "|" + regexCannotEndKoKr.source);
- /**
- * Borrow from pixi/packages/text/src/TextMetrics.ts
- */
- var TextService = /*#__PURE__*/function () {
- function TextService(runtime) {
- var _this = this;
- this.runtime = void 0;
- /**
- * font metrics cache
- */
- this.fontMetricsCache = {};
- this.shouldBreakByKinsokuShorui = function (char, nextChar) {
- if (_this.isBreakingSpace(nextChar)) return false;
- if (char) {
- // Line breaking rules in CJK (Kinsoku Shori)
- if (regexCannotEnd.exec(nextChar) || regexCannotStart.exec(char)) {
- return true;
- }
- }
- return false;
- };
- this.trimByKinsokuShorui = function (prev) {
- var next = [].concat(prev);
- var prevLine = next[next.length - 2];
- if (!prevLine) {
- return prev;
- }
- var lastChar = prevLine[prevLine.length - 1];
- next[next.length - 2] = prevLine.slice(0, -1);
- next[next.length - 1] = lastChar + next[next.length - 1];
- return next;
- };
- this.runtime = runtime;
- }
- var _proto = TextService.prototype;
- /**
- * Calculates the ascent, descent and fontSize of a given font-style.
- */
- _proto.measureFont = function measureFont(font, offscreenCanvas) {
- // as this method is used for preparing assets, don't recalculate things if we don't need to
- if (this.fontMetricsCache[font]) {
- return this.fontMetricsCache[font];
- }
- var properties = {
- ascent: 0,
- descent: 0,
- fontSize: 0
- };
- var canvas = this.runtime.offscreenCanvas.getOrCreateCanvas(offscreenCanvas);
- var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas, {
- willReadFrequently: true
- });
- context.font = font;
- var metricsString = TEXT_METRICS.MetricsString + TEXT_METRICS.BaselineSymbol;
- var width = Math.ceil(context.measureText(metricsString).width);
- var baseline = Math.ceil(context.measureText(TEXT_METRICS.BaselineSymbol).width);
- var height = TEXT_METRICS.HeightMultiplier * baseline;
- baseline = baseline * TEXT_METRICS.BaselineMultiplier | 0;
- // @ts-ignore
- canvas.width = width;
- // @ts-ignore
- canvas.height = height;
- context.fillStyle = '#f00';
- context.fillRect(0, 0, width, height);
- context.font = font;
- context.textBaseline = 'alphabetic';
- context.fillStyle = '#000';
- context.fillText(metricsString, 0, baseline);
- var imagedata = context.getImageData(0, 0, width || 1, height || 1).data;
- var pixels = imagedata.length;
- var line = width * 4;
- var i = 0;
- var idx = 0;
- var stop = false;
- // ascent. scan from top to bottom until we find a non red pixel
- for (i = 0; i < baseline; ++i) {
- for (var j = 0; j < line; j += 4) {
- if (imagedata[idx + j] !== 255) {
- stop = true;
- break;
- }
- }
- if (!stop) {
- idx += line;
- } else {
- break;
- }
- }
- properties.ascent = baseline - i;
- idx = pixels - line;
- stop = false;
- // descent. scan from bottom to top until we find a non red pixel
- for (i = height; i > baseline; --i) {
- for (var _j = 0; _j < line; _j += 4) {
- if (imagedata[idx + _j] !== 255) {
- stop = true;
- break;
- }
- }
- if (!stop) {
- idx -= line;
- } else {
- break;
- }
- }
- properties.descent = i - baseline;
- properties.fontSize = properties.ascent + properties.descent;
- this.fontMetricsCache[font] = properties;
- return properties;
- };
- _proto.measureText = function measureText(text, parsedStyle, offscreenCanvas) {
- var fontSize = parsedStyle.fontSize,
- wordWrap = parsedStyle.wordWrap,
- strokeHeight = parsedStyle.lineHeight,
- lineWidth = parsedStyle.lineWidth,
- textBaseline = parsedStyle.textBaseline,
- textAlign = parsedStyle.textAlign,
- letterSpacing = parsedStyle.letterSpacing,
- textPath = parsedStyle.textPath,
- textPathSide = parsedStyle.textPathSide,
- textPathStartOffset = parsedStyle.textPathStartOffset,
- _parsedStyle$leading = parsedStyle.leading,
- leading = _parsedStyle$leading === void 0 ? 0 : _parsedStyle$leading;
- var font = toFontString(parsedStyle);
- // if (runtime.enableCSSParsing) {
- var fontProperties = this.measureFont(font, offscreenCanvas);
- // fallback in case UA disallow canvas data extraction
- // (toDataURI, getImageData functions)
- if (fontProperties.fontSize === 0) {
- fontProperties.fontSize = fontSize;
- fontProperties.ascent = fontSize;
- }
- // } else {
- // fontProperties = {
- // fontSize,
- // };
- // }
- var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
- context.font = font;
- // no overflowing by default
- parsedStyle.isOverflowing = false;
- var outputText = wordWrap ? this.wordWrap(text, parsedStyle, offscreenCanvas) : text;
- var lines = outputText.split(/(?:\r\n|\r|\n)/);
- var lineWidths = new Array(lines.length);
- var maxLineWidth = 0;
- // account for textPath
- if (textPath) {
- var totalPathLength = textPath.getTotalLength();
- // const startingPoint = textPath.getPoint(0);
- for (var i = 0; i < lines.length; i++) {
- var width = context.measureText(lines[i]).width + (lines[i].length - 1) * letterSpacing;
- // for (
- // let i = reverse ? lines[0].length - 1 : 0;
- // reverse ? i >= 0 : i < lines[0].length;
- // reverse ? i-- : i++
- // ) {
- // graphemeInfo = lineBounds[i];
- // if (positionInPath > totalPathLength) {
- // positionInPath %= totalPathLength;
- // } else if (positionInPath < 0) {
- // positionInPath += totalPathLength;
- // }
- // // it would probably much faster to send all the grapheme position for a line
- // // and calculate path position/angle at once.
- // this.setGraphemeOnPath(
- // positionInPath,
- // graphemeInfo,
- // startingPoint
- // );
- // positionInPath += graphemeInfo.kernedWidth;
- // }
- }
- } else {
- for (var _i = 0; _i < lines.length; _i++) {
- // char width + letterSpacing
- var _lineWidth = context.measureText(lines[_i]).width + (lines[_i].length - 1) * letterSpacing;
- lineWidths[_i] = _lineWidth;
- maxLineWidth = Math.max(maxLineWidth, _lineWidth);
- }
- var _width = maxLineWidth + lineWidth;
- // if (dropShadow) {
- // width += dropShadowDistance;
- // }
- var lineHeight = strokeHeight || fontProperties.fontSize + lineWidth;
- var height = Math.max(lineHeight, fontProperties.fontSize + lineWidth) + (lines.length - 1) * (lineHeight + leading);
- // if (dropShadow) {
- // height += dropShadowDistance;
- // }
- lineHeight += leading;
- // handle vertical text baseline
- var offsetY = 0;
- if (textBaseline === 'middle') {
- offsetY = -height / 2;
- } else if (textBaseline === 'bottom' || textBaseline === 'alphabetic' || textBaseline === 'ideographic') {
- offsetY = -height;
- } else if (textBaseline === 'top' || textBaseline === 'hanging') {
- offsetY = 0;
- }
- return {
- font: font,
- width: _width,
- height: height,
- lines: lines,
- lineWidths: lineWidths,
- lineHeight: lineHeight,
- maxLineWidth: maxLineWidth,
- fontProperties: fontProperties,
- lineMetrics: lineWidths.map(function (width, i) {
- var offsetX = 0;
- // handle horizontal text align
- if (textAlign === 'center' || textAlign === 'middle') {
- offsetX -= width / 2;
- } else if (textAlign === 'right' || textAlign === 'end') {
- offsetX -= width;
- }
- return new Rectangle(offsetX - lineWidth / 2, offsetY + i * lineHeight, width + lineWidth, lineHeight);
- })
- };
- }
- };
- _proto.setGraphemeOnPath = function setGraphemeOnPath() {};
- _proto.wordWrap = function wordWrap(text, parsedStyle, offscreenCanvas) {
- var _this2 = this;
- var _parsedStyle$wordWrap = parsedStyle.wordWrapWidth,
- wordWrapWidth = _parsedStyle$wordWrap === void 0 ? 0 : _parsedStyle$wordWrap,
- letterSpacing = parsedStyle.letterSpacing,
- _parsedStyle$maxLines = parsedStyle.maxLines,
- maxLines = _parsedStyle$maxLines === void 0 ? Infinity : _parsedStyle$maxLines,
- textOverflow = parsedStyle.textOverflow;
- var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
- var maxWidth = wordWrapWidth + letterSpacing;
- var ellipsis = '';
- if (textOverflow === 'ellipsis') {
- ellipsis = '...';
- } else if (textOverflow && textOverflow !== 'clip') {
- ellipsis = textOverflow;
- }
- var lines = [];
- var currentIndex = 0;
- var currentWidth = 0;
- var cache = {};
- var calcWidth = function calcWidth(char) {
- return _this2.getFromCache(char, letterSpacing, cache, context);
- };
- var ellipsisWidth = Array.from(ellipsis).reduce(function (prev, cur) {
- return prev + calcWidth(cur);
- }, 0);
- var chars = Array.from(text);
- for (var i = 0; i < chars.length; i++) {
- var char = chars[i];
- var prevChar = text[i - 1];
- var nextChar = text[i + 1];
- var charWidth = calcWidth(char);
- if (this.isNewline(char)) {
- currentIndex++;
- // exceed maxLines, break immediately
- if (currentIndex >= maxLines) {
- parsedStyle.isOverflowing = true;
- break;
- }
- currentWidth = 0;
- lines[currentIndex] = '';
- continue;
- }
- if (currentWidth > 0 && currentWidth + charWidth > maxWidth) {
- if (currentIndex + 1 >= maxLines) {
- parsedStyle.isOverflowing = true;
- // If there is not enough space to display the string itself, it is clipped.
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#values
- if (ellipsisWidth > 0 && ellipsisWidth <= maxWidth) {
- // Backspace from line's end.
- var currentLineLength = lines[currentIndex].length;
- var lastLineWidth = 0;
- var lastLineIndex = currentLineLength;
- for (var _i2 = 0; _i2 < currentLineLength; _i2++) {
- var width = calcWidth(lines[currentIndex][_i2]);
- if (lastLineWidth + width + ellipsisWidth > maxWidth) {
- lastLineIndex = _i2;
- break;
- }
- lastLineWidth += width;
- }
- lines[currentIndex] = (lines[currentIndex] || '').slice(0, lastLineIndex) + ellipsis;
- }
- break;
- }
- currentIndex++;
- currentWidth = 0;
- lines[currentIndex] = '';
- if (this.isBreakingSpace(char)) {
- continue;
- }
- if (!this.canBreakInLastChar(char)) {
- lines = this.trimToBreakable(lines);
- currentWidth = this.sumTextWidthByCache(lines[currentIndex] || '', cache);
- }
- if (this.shouldBreakByKinsokuShorui(char, nextChar)) {
- lines = this.trimByKinsokuShorui(lines);
- currentWidth += calcWidth(prevChar || '');
- }
- }
- currentWidth += charWidth;
- lines[currentIndex] = (lines[currentIndex] || '') + char;
- }
- return lines.join('\n');
- };
- _proto.isBreakingSpace = function isBreakingSpace(char) {
- if (typeof char !== 'string') {
- return false;
- }
- return TEXT_METRICS.BreakingSpaces.indexOf(char.charCodeAt(0)) >= 0;
- };
- _proto.isNewline = function isNewline(char) {
- if (typeof char !== 'string') {
- return false;
- }
- return TEXT_METRICS.Newlines.indexOf(char.charCodeAt(0)) >= 0;
- };
- _proto.trimToBreakable = function trimToBreakable(prev) {
- var next = [].concat(prev);
- var prevLine = next[next.length - 2];
- var index = this.findBreakableIndex(prevLine);
- if (index === -1 || !prevLine) return next;
- var trimmedChar = prevLine.slice(index, index + 1);
- var isTrimmedWithSpace = this.isBreakingSpace(trimmedChar);
- var trimFrom = index + 1;
- var trimTo = index + (isTrimmedWithSpace ? 0 : 1);
- next[next.length - 1] += prevLine.slice(trimFrom, prevLine.length);
- next[next.length - 2] = prevLine.slice(0, trimTo);
- return next;
- };
- _proto.canBreakInLastChar = function canBreakInLastChar(char) {
- if (char && LATIN_REGEX.test(char)) return false;
- return true;
- };
- _proto.sumTextWidthByCache = function sumTextWidthByCache(text, cache) {
- return text.split('').reduce(function (sum, c) {
- if (!cache[c]) throw Error('cannot count the word without cache');
- return sum + cache[c];
- }, 0);
- };
- _proto.findBreakableIndex = function findBreakableIndex(line) {
- for (var i = line.length - 1; i >= 0; i--) {
- if (!LATIN_REGEX.test(line[i])) return i;
- }
- return -1;
- };
- _proto.getFromCache = function getFromCache(key, letterSpacing, cache, context) {
- var width = cache[key];
- if (typeof width !== 'number') {
- var spacing = key.length * letterSpacing;
- width = context.measureText(key).width + spacing;
- cache[key] = width;
- }
- return width;
- };
- return TextService;
- }();
- var _this = undefined;
- var runtime = {};
- /**
- * Replace with IoC container
- */
- var geometryUpdaterFactory = function () {
- var _ref;
- var rectUpdater = new RectUpdater();
- var polylineUpdater = new PolylineUpdater();
- 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;
- }();
- var CSSPropertySyntaxFactory = function () {
- var _ref2;
- var color = new CSSPropertyColor();
- var length = new CSSPropertyLengthOrPercentage();
- 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;
- }();
- var getGlobalThis = function getGlobalThis() {
- if (typeof globalThis !== 'undefined') return globalThis;
- if (typeof self !== 'undefined') return self;
- if (typeof window !== 'undefined') return window;
- // @ts-ignore
- if (typeof global !== 'undefined') return global;
- if (typeof _this !== 'undefined') return _this;
- throw new Error('Unable to locate global `this`');
- };
- /**
- * Camera
- * `g-camera-api` will provide an advanced implementation
- */
- runtime.CameraContribution = Camera;
- /**
- * `g-web-animations-api` will provide an AnimationTimeline
- */
- runtime.AnimationTimeline = null;
- runtime.EasingFunction = null;
- runtime.offscreenCanvas = new OffscreenCanvasCreator();
- runtime.nativeHTMLMap = new WeakMap();
- runtime.sceneGraphSelector = new DefaultSceneGraphSelector();
- runtime.sceneGraphService = new DefaultSceneGraphService(runtime);
- runtime.textService = new TextService(runtime);
- runtime.geometryUpdaterFactory = geometryUpdaterFactory;
- runtime.CSSPropertySyntaxFactory = CSSPropertySyntaxFactory;
- runtime.styleValueRegistry = new DefaultStyleValueRegistry();
- runtime.layoutRegistry = null;
- runtime.globalThis = getGlobalThis();
- runtime.enableCSSParsing = true;
- runtime.enableDataset = false;
- runtime.enableStyleSyntax = true;
- var AbstractRendererPlugin = /*#__PURE__*/function () {
- function AbstractRendererPlugin() {
- this.context = void 0;
- this.plugins = [];
- }
- var _proto = AbstractRendererPlugin.prototype;
- _proto.addRenderingPlugin = function addRenderingPlugin(plugin) {
- this.plugins.push(plugin);
- this.context.renderingPlugins.push(plugin);
- };
- _proto.removeAllRenderingPlugins = function removeAllRenderingPlugins() {
- var _this = this;
- this.plugins.forEach(function (plugin) {
- var index = _this.context.renderingPlugins.indexOf(plugin);
- if (index >= 0) {
- _this.context.renderingPlugins.splice(index, 1);
- }
- });
- };
- return AbstractRendererPlugin;
- }();
- var AbstractRenderer = /*#__PURE__*/function () {
- function AbstractRenderer(config) {
- this.plugins = [];
- this.config = void 0;
- this.config = _extends({
- /**
- * only dirty object will cause re-render
- */
- enableDirtyCheck: true,
- enableCulling: false,
- /**
- * enable auto rendering by default
- */
- enableAutoRendering: true,
- /**
- * enable dirty rectangle rendering by default
- */
- enableDirtyRectangleRendering: true,
- enableDirtyRectangleRenderingDebug: false
- }, config);
- }
- var _proto2 = AbstractRenderer.prototype;
- _proto2.registerPlugin = function registerPlugin(plugin) {
- var index = this.plugins.findIndex(function (p) {
- return p === plugin;
- });
- if (index === -1) {
- this.plugins.push(plugin);
- }
- };
- _proto2.unregisterPlugin = function unregisterPlugin(plugin) {
- var index = this.plugins.findIndex(function (p) {
- return p === plugin;
- });
- if (index > -1) {
- this.plugins.splice(index, 1);
- }
- };
- _proto2.getPlugins = function getPlugins() {
- return this.plugins;
- };
- _proto2.getPlugin = function getPlugin(name) {
- return this.plugins.find(function (plugin) {
- return plugin.name === name;
- });
- };
- _proto2.getConfig = function getConfig() {
- return this.config;
- };
- _proto2.setConfig = function setConfig(config) {
- Object.assign(this.config, config);
- };
- return AbstractRenderer;
- }();
- /**
- * apply following rules:
- * 1. `visibility` in scenegraph node
- * 2. other custom culling strategies, eg. frustum culling
- */
- var CullingPlugin = /*#__PURE__*/function () {
- function CullingPlugin(strategies) {
- this.strategies = void 0;
- this.strategies = strategies;
- }
- var _proto = CullingPlugin.prototype;
- _proto.apply = function apply(context) {
- var camera = context.camera,
- renderingService = context.renderingService,
- renderingContext = context.renderingContext;
- var strategies = this.strategies;
- renderingService.hooks.cull.tap(CullingPlugin.tag, function (object) {
- if (object) {
- var cullable = object.cullable;
- // cullable.visible = true;
- // const renderBounds = object.getRenderBounds();
- // if (AABB.isEmpty(renderBounds)) {
- // cullable.visible = false;
- // } else {
- // const isShape2D = shape2D.indexOf(object.nodeName as Shape) > -1;
- // const [p0, p1, p2, p3] = camera.getFrustum().planes;
- // tmpAABB.setMinMax([-p1.distance, -p3.distance, 0], [p0.distance, p2.distance, 0]);
- // cullable.visible = isShape2D ? renderBounds.intersects(tmpAABB) : true;
- // }
- if (strategies.length === 0) {
- cullable.visible = renderingContext.unculledEntities.indexOf(object.entity) > -1;
- } else {
- // eg. implemented by g-webgl(frustum culling)
- cullable.visible = strategies.every(function (strategy) {
- return strategy.isVisible(camera, object);
- });
- }
- if (!object.isCulled() && object.isVisible()) {
- return object;
- } else {
- // if (this.renderingContext.renderListLastFrame.indexOf(object) > -1) {
- object.dispatchEvent(new CustomEvent(ElementEvent.CULLED));
- // }
- }
- return null;
- }
- return object;
- });
- renderingService.hooks.afterRender.tap(CullingPlugin.tag, function (object) {
- object.cullable.visibilityPlaneMask = -1;
- });
- };
- return CullingPlugin;
- }();
- CullingPlugin.tag = 'Culling';
- /**
- * Filter dirty renderables and calculate the "dirty rectangle" which will be clear when frame began
- */
- var DirtyCheckPlugin = /*#__PURE__*/function () {
- function DirtyCheckPlugin() {}
- var _proto = DirtyCheckPlugin.prototype;
- _proto.apply = function apply(context) {
- var renderingService = context.renderingService;
- renderingService.hooks.dirtycheck.tap(DirtyCheckPlugin.tag, function (object) {
- if (object) {
- var renderable = object.renderable;
- var isDirty = renderable.dirty || renderingService.disableDirtyRectangleRendering();
- if (isDirty) {
- return object;
- } else {
- return null;
- }
- }
- return object;
- });
- };
- return DirtyCheckPlugin;
- }();
- DirtyCheckPlugin.tag = 'DirtyCheck';
- /**
- * support mouse & touch events
- * @see https://github.com/pixijs/pixi.js/blob/dev/packages/interaction/README.md
- *
- * also provide some extra events such as `drag`
- */
- var EventPlugin = /*#__PURE__*/function () {
- function EventPlugin() {
- var _this = this;
- this.autoPreventDefault = false;
- this.rootPointerEvent = new FederatedPointerEvent(null);
- this.rootWheelEvent = new FederatedWheelEvent(null);
- this.context = void 0;
- this.onPointerMove = function (nativeEvent) {
- var _this$context$renderi, _this$context$renderi2;
- 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;
- if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
- var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator = _createForOfIteratorHelperLoose(normalizedEvents), _step; !(_step = _iterator()).done;) {
- var normalizedEvent = _step.value;
- var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- _this.context.eventService.mapEvent(event);
- }
- _this.setCursor(_this.context.eventService.cursor);
- };
- this.onClick = function (nativeEvent) {
- var _this$context$renderi3, _this$context$renderi4;
- 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;
- var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator2 = _createForOfIteratorHelperLoose(normalizedEvents), _step2; !(_step2 = _iterator2()).done;) {
- var normalizedEvent = _step2.value;
- var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- _this.context.eventService.mapEvent(event);
- }
- _this.setCursor(_this.context.eventService.cursor);
- };
- }
- var _proto = EventPlugin.prototype;
- _proto.apply = function apply(context) {
- var _this2 = this;
- this.context = context;
- var renderingService = context.renderingService;
- var canvas = this.context.renderingContext.root.ownerDocument.defaultView;
- this.context.eventService.setPickHandler(function (position) {
- var _this2$context$render = _this2.context.renderingService.hooks.pickSync.call({
- position: position,
- picked: [],
- topmost: true // we only concern the topmost element
- }),
- picked = _this2$context$render.picked;
- return picked[0] || null;
- });
- renderingService.hooks.pointerWheel.tap(EventPlugin.tag, function (nativeEvent) {
- var wheelEvent = _this2.normalizeWheelEvent(nativeEvent);
- _this2.context.eventService.mapEvent(wheelEvent);
- });
- renderingService.hooks.pointerDown.tap(EventPlugin.tag, function (nativeEvent) {
- if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
- var events = _this2.normalizeToPointerEvent(nativeEvent, canvas);
- if (_this2.autoPreventDefault && events[0].isNormalized) {
- var cancelable = nativeEvent.cancelable || !('cancelable' in nativeEvent);
- if (cancelable) {
- nativeEvent.preventDefault();
- }
- }
- for (var _iterator3 = _createForOfIteratorHelperLoose(events), _step3; !(_step3 = _iterator3()).done;) {
- var event = _step3.value;
- var federatedEvent = _this2.bootstrapEvent(_this2.rootPointerEvent, event, canvas, nativeEvent);
- _this2.context.eventService.mapEvent(federatedEvent);
- }
- _this2.setCursor(_this2.context.eventService.cursor);
- });
- renderingService.hooks.pointerUp.tap(EventPlugin.tag, function (nativeEvent) {
- if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
- // account for element in SVG
- var $element = _this2.context.contextService.getDomElement();
- var outside = 'outside';
- try {
- outside = $element && nativeEvent.target && nativeEvent.target !== $element && $element.contains && !$element.contains(nativeEvent.target) ? 'outside' : '';
- } catch (e) {
- // nativeEvent.target maybe not Node, such as Window
- // @see https://github.com/antvis/G/issues/1235
- }
- var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator4 = _createForOfIteratorHelperLoose(normalizedEvents), _step4; !(_step4 = _iterator4()).done;) {
- var normalizedEvent = _step4.value;
- var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- event.type += outside;
- _this2.context.eventService.mapEvent(event);
- }
- _this2.setCursor(_this2.context.eventService.cursor);
- });
- renderingService.hooks.pointerMove.tap(EventPlugin.tag, this.onPointerMove);
- renderingService.hooks.pointerOver.tap(EventPlugin.tag, this.onPointerMove);
- renderingService.hooks.pointerOut.tap(EventPlugin.tag, this.onPointerMove);
- renderingService.hooks.click.tap(EventPlugin.tag, this.onClick);
- renderingService.hooks.pointerCancel.tap(EventPlugin.tag, function (nativeEvent) {
- var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator5 = _createForOfIteratorHelperLoose(normalizedEvents), _step5; !(_step5 = _iterator5()).done;) {
- var normalizedEvent = _step5.value;
- var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- _this2.context.eventService.mapEvent(event);
- }
- _this2.setCursor(_this2.context.eventService.cursor);
- });
- };
- _proto.getViewportXY = function getViewportXY(nativeEvent) {
- var x;
- var y;
- /**
- * Should account for CSS Transform applied on container.
- * @see https://github.com/antvis/G/issues/1161
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/offsetX
- */
- var offsetX = nativeEvent.offsetX,
- offsetY = nativeEvent.offsetY,
- clientX = nativeEvent.clientX,
- clientY = nativeEvent.clientY;
- if (this.context.config.supportsCSSTransform && !isNil(offsetX) && !isNil(offsetY)) {
- x = offsetX;
- y = offsetY;
- } else {
- var point = this.context.eventService.client2Viewport(new Point(clientX, clientY));
- x = point.x;
- y = point.y;
- }
- return {
- x: x,
- y: y
- };
- };
- _proto.bootstrapEvent = function bootstrapEvent(event, normalizedEvent, view, nativeEvent) {
- event.view = view;
- event.originalEvent = null;
- event.nativeEvent = nativeEvent;
- event.pointerId = normalizedEvent.pointerId;
- event.width = normalizedEvent.width;
- event.height = normalizedEvent.height;
- event.isPrimary = normalizedEvent.isPrimary;
- event.pointerType = normalizedEvent.pointerType;
- event.pressure = normalizedEvent.pressure;
- event.tangentialPressure = normalizedEvent.tangentialPressure;
- event.tiltX = normalizedEvent.tiltX;
- event.tiltY = normalizedEvent.tiltY;
- event.twist = normalizedEvent.twist;
- this.transferMouseData(event, normalizedEvent);
- var _this$getViewportXY = this.getViewportXY(normalizedEvent),
- x = _this$getViewportXY.x,
- y = _this$getViewportXY.y;
- event.viewport.x = x;
- event.viewport.y = y;
- var _this$context$eventSe = this.context.eventService.viewport2Canvas(event.viewport),
- canvasX = _this$context$eventSe.x,
- canvasY = _this$context$eventSe.y;
- event.canvas.x = canvasX;
- event.canvas.y = canvasY;
- event.global.copyFrom(event.canvas);
- event.offset.copyFrom(event.canvas);
- event.isTrusted = nativeEvent.isTrusted;
- if (event.type === 'pointerleave') {
- event.type = 'pointerout';
- }
- if (event.type.startsWith('mouse')) {
- event.type = event.type.replace('mouse', 'pointer');
- }
- if (event.type.startsWith('touch')) {
- event.type = TOUCH_TO_POINTER[event.type] || event.type;
- }
- return event;
- };
- _proto.normalizeWheelEvent = function normalizeWheelEvent(nativeEvent) {
- var event = this.rootWheelEvent;
- this.transferMouseData(event, nativeEvent);
- event.deltaMode = nativeEvent.deltaMode;
- event.deltaX = nativeEvent.deltaX;
- event.deltaY = nativeEvent.deltaY;
- event.deltaZ = nativeEvent.deltaZ;
- var _this$getViewportXY2 = this.getViewportXY(nativeEvent),
- x = _this$getViewportXY2.x,
- y = _this$getViewportXY2.y;
- event.viewport.x = x;
- event.viewport.y = y;
- var _this$context$eventSe2 = this.context.eventService.viewport2Canvas(event.viewport),
- canvasX = _this$context$eventSe2.x,
- canvasY = _this$context$eventSe2.y;
- event.canvas.x = canvasX;
- event.canvas.y = canvasY;
- event.global.copyFrom(event.canvas);
- event.offset.copyFrom(event.canvas);
- event.nativeEvent = nativeEvent;
- event.type = nativeEvent.type;
- return event;
- }
- /**
- * Transfers base & mouse event data from the nativeEvent to the federated event.
- */;
- _proto.transferMouseData = function transferMouseData(event, nativeEvent) {
- event.isTrusted = nativeEvent.isTrusted;
- event.srcElement = nativeEvent.srcElement;
- event.timeStamp = performance.now();
- event.type = nativeEvent.type;
- event.altKey = nativeEvent.altKey;
- event.metaKey = nativeEvent.metaKey;
- event.shiftKey = nativeEvent.shiftKey;
- event.ctrlKey = nativeEvent.ctrlKey;
- event.button = nativeEvent.button;
- event.buttons = nativeEvent.buttons;
- event.client.x = nativeEvent.clientX;
- event.client.y = nativeEvent.clientY;
- event.movement.x = nativeEvent.movementX;
- event.movement.y = nativeEvent.movementY;
- event.page.x = nativeEvent.pageX;
- event.page.y = nativeEvent.pageY;
- event.screen.x = nativeEvent.screenX;
- event.screen.y = nativeEvent.screenY;
- event.relatedTarget = null;
- };
- _proto.setCursor = function setCursor(cursor) {
- this.context.contextService.applyCursorStyle(cursor || this.context.config.cursor || 'default');
- };
- _proto.normalizeToPointerEvent = function normalizeToPointerEvent(event, canvas) {
- var normalizedEvents = [];
- if (canvas.isTouchEvent(event)) {
- for (var i = 0; i < event.changedTouches.length; i++) {
- var touch = event.changedTouches[i];
- // use changedTouches instead of touches since touchend has no touches
- // @see https://stackoverflow.com/a/10079076
- if (isUndefined(touch.button)) touch.button = 0;
- if (isUndefined(touch.buttons)) touch.buttons = 1;
- if (isUndefined(touch.isPrimary)) {
- touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
- }
- if (isUndefined(touch.width)) touch.width = touch.radiusX || 1;
- if (isUndefined(touch.height)) touch.height = touch.radiusY || 1;
- if (isUndefined(touch.tiltX)) touch.tiltX = 0;
- if (isUndefined(touch.tiltY)) touch.tiltY = 0;
- if (isUndefined(touch.pointerType)) touch.pointerType = 'touch';
- // @see https://developer.mozilla.org/zh-CN/docs/Web/API/Touch/identifier
- if (isUndefined(touch.pointerId)) touch.pointerId = touch.identifier || 0;
- if (isUndefined(touch.pressure)) touch.pressure = touch.force || 0.5;
- if (isUndefined(touch.twist)) touch.twist = 0;
- if (isUndefined(touch.tangentialPressure)) touch.tangentialPressure = 0;
- touch.isNormalized = true;
- touch.type = event.type;
- normalizedEvents.push(touch);
- }
- } else if (canvas.isMouseEvent(event)) {
- var tempEvent = event;
- if (isUndefined(tempEvent.isPrimary)) tempEvent.isPrimary = true;
- if (isUndefined(tempEvent.width)) tempEvent.width = 1;
- if (isUndefined(tempEvent.height)) tempEvent.height = 1;
- if (isUndefined(tempEvent.tiltX)) tempEvent.tiltX = 0;
- if (isUndefined(tempEvent.tiltY)) tempEvent.tiltY = 0;
- if (isUndefined(tempEvent.pointerType)) tempEvent.pointerType = 'mouse';
- if (isUndefined(tempEvent.pointerId)) tempEvent.pointerId = MOUSE_POINTER_ID;
- if (isUndefined(tempEvent.pressure)) tempEvent.pressure = 0.5;
- if (isUndefined(tempEvent.twist)) tempEvent.twist = 0;
- if (isUndefined(tempEvent.tangentialPressure)) tempEvent.tangentialPressure = 0;
- tempEvent.isNormalized = true;
- normalizedEvents.push(tempEvent);
- } else {
- normalizedEvents.push(event);
- }
- return normalizedEvents;
- };
- return EventPlugin;
- }();
- EventPlugin.tag = 'Event';
- // group is not a 2d shape
- var shape2D = [Shape.CIRCLE, Shape.ELLIPSE, Shape.IMAGE, Shape.RECT, Shape.LINE, Shape.POLYLINE, Shape.POLYGON, Shape.TEXT, Shape.PATH, Shape.HTML];
- var FrustumCullingStrategy = /*#__PURE__*/function () {
- function FrustumCullingStrategy() {}
- var _proto = FrustumCullingStrategy.prototype;
- _proto.isVisible = function isVisible(camera, object) {
- var _object$parentNode, _object$parentNode$cu;
- // return true;
- var cullable = object.cullable;
- if (!cullable.enable) {
- return true;
- }
- var renderBounds = object.getRenderBounds();
- if (AABB.isEmpty(renderBounds)) {
- return false;
- }
- // get VP matrix from camera
- var frustum = camera.getFrustum();
- 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;
- cullable.visibilityPlaneMask = this.computeVisibilityWithPlaneMask(object, renderBounds, parentVisibilityPlaneMask || Mask.INDETERMINATE, frustum.planes);
- cullable.visible = cullable.visibilityPlaneMask !== Mask.OUTSIDE;
- return cullable.visible;
- }
- /**
- *
- * @see「Optimized View Frustum Culling Algorithms for Bounding Boxes」
- * @see https://github.com/antvis/GWebGPUEngine/issues/3
- *
- * * 基础相交测试 the basic intersection test
- * * 标记 masking @see https://cesium.com/blog/2015/08/04/fast-hierarchical-culling/
- * * TODO: 平面一致性测试 the plane-coherency test
- * * TODO: 支持 mesh 指定自身的剔除策略,参考 Babylon.js @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
- *
- * @param aabb aabb
- * @param parentPlaneMask mask of parent
- * @param planes planes of frustum
- */;
- _proto.computeVisibilityWithPlaneMask = function computeVisibilityWithPlaneMask(object, aabb, parentPlaneMask, planes) {
- if (parentPlaneMask === Mask.OUTSIDE || parentPlaneMask === Mask.INSIDE) {
- // 父节点完全位于视锥内或者外部,直接返回
- return parentPlaneMask;
- }
- // Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
- // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
- var mask = Mask.INSIDE;
- var isShape2D = shape2D.indexOf(object.nodeName) > -1;
- // Use viewport culling for 2D shapes
- // @see https://github.com/antvis/g/issues/914
- for (var k = 0, len = planes.length; k < len; ++k) {
- // For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.
- var flag = 1 << k;
- if ((parentPlaneMask & flag) === 0) {
- // 父节点处于当前面内部,可以跳过
- continue;
- }
- // skip near & far planes when testing 2D shapes
- if (isShape2D && (k === 4 || k === 5)) {
- continue;
- }
- // p-vertex n-vertex <-|plane p-vertex n-vertex
- // 使用 p-vertex 和 n-vertex 加速,避免进行平面和 aabb 全部顶点的相交检测
- var _planes$k = planes[k],
- normal = _planes$k.normal,
- distance = _planes$k.distance;
- if (vec3.dot(normal, aabb.getPositiveFarPoint(planes[k])) + distance < 0) {
- return Mask.OUTSIDE;
- }
- if (vec3.dot(normal, aabb.getNegativeFarPoint(planes[k])) + distance < 0) {
- // 和当前面相交,对应位置为1,继续检测下一个面
- mask |= flag;
- }
- }
- return mask;
- };
- return FrustumCullingStrategy;
- }();
- var PrepareRendererPlugin = /*#__PURE__*/function () {
- function PrepareRendererPlugin() {
- this.rBush = void 0;
- /**
- * sync to RBush later
- */
- this.toSync = new Set();
- }
- var _proto = PrepareRendererPlugin.prototype;
- // private isFirstTimeRendering = true;
- // private syncing = false;
- _proto.apply = function apply(context) {
- var _this = this;
- var renderingService = context.renderingService,
- renderingContext = context.renderingContext,
- rBushRoot = context.rBushRoot;
- var canvas = renderingContext.root.ownerDocument.defaultView;
- this.rBush = rBushRoot;
- var handleAttributeChanged = function handleAttributeChanged(e) {
- var object = e.target;
- object.renderable.dirty = true;
- renderingService.dirtify();
- };
- var handleBoundsChanged = function handleBoundsChanged(e) {
- var affectChildren = e.detail.affectChildren;
- var object = e.target;
- if (affectChildren) {
- object.forEach(function (node) {
- _this.toSync.add(node);
- });
- }
- var p = object;
- while (p) {
- if (p.renderable) {
- _this.toSync.add(p);
- }
- p = p.parentElement;
- }
- // this.pushToSync(e.composedPath().slice(0, -2) as DisplayObject[]);
- renderingService.dirtify();
- };
- var handleMounted = function handleMounted(e) {
- var object = e.target;
- if (runtime.enableCSSParsing) {
- // recalc style values
- runtime.styleValueRegistry.recalc(object);
- }
- runtime.sceneGraphService.dirtifyToRoot(object);
- renderingService.dirtify();
- };
- var handleUnmounted = function handleUnmounted(e) {
- var object = e.target;
- var rBushNode = object.rBushNode;
- if (rBushNode.aabb) {
- _this.rBush.remove(rBushNode.aabb);
- }
- _this.toSync.delete(object);
- runtime.sceneGraphService.dirtifyToRoot(object);
- renderingService.dirtify();
- };
- renderingService.hooks.init.tap(PrepareRendererPlugin.tag, function () {
- canvas.addEventListener(ElementEvent.MOUNTED, handleMounted);
- canvas.addEventListener(ElementEvent.UNMOUNTED, handleUnmounted);
- canvas.addEventListener(ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
- canvas.addEventListener(ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
- });
- renderingService.hooks.destroy.tap(PrepareRendererPlugin.tag, function () {
- canvas.removeEventListener(ElementEvent.MOUNTED, handleMounted);
- canvas.removeEventListener(ElementEvent.UNMOUNTED, handleUnmounted);
- canvas.removeEventListener(ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
- canvas.removeEventListener(ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
- _this.toSync.clear();
- });
- renderingService.hooks.endFrame.tap(PrepareRendererPlugin.tag, function () {
- // if (this.isFirstTimeRendering) {
- // this.isFirstTimeRendering = false;
- // this.syncing = true;
- // // @see https://github.com/antvis/G/issues/1117
- // setTimeout(() => {
- // this.syncRTree();
- // console.log('fcp...');
- // });
- // } else {
- // console.log('next...');
- _this.syncRTree();
- // }
- });
- };
- _proto.syncRTree = function syncRTree() {
- var _this2 = this;
- // if (this.syncing) {
- // return;
- // }
- // bounds changed, need re-inserting its children
- var bulk = [];
- Array.from(this.toSync)
- // some objects may be removed since last frame
- .filter(function (object) {
- return object.isConnected;
- }).forEach(function (node) {
- var rBushNode = node.rBushNode;
- // clear dirty node
- if (rBushNode && rBushNode.aabb) {
- _this2.rBush.remove(rBushNode.aabb);
- }
- var renderBounds = node.getRenderBounds();
- if (renderBounds) {
- var _renderBounds$getMin = renderBounds.getMin(),
- minX = _renderBounds$getMin[0],
- minY = _renderBounds$getMin[1];
- var _renderBounds$getMax = renderBounds.getMax(),
- maxX = _renderBounds$getMax[0],
- maxY = _renderBounds$getMax[1];
- if (!rBushNode.aabb) {
- rBushNode.aabb = {};
- }
- rBushNode.aabb.displayObject = node;
- rBushNode.aabb.minX = minX;
- rBushNode.aabb.minY = minY;
- rBushNode.aabb.maxX = maxX;
- rBushNode.aabb.maxY = maxY;
- }
- if (rBushNode.aabb) {
- // TODO: NaN occurs when width/height of Rect is 0
- if (!isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.minX) && !isNaN(rBushNode.aabb.minY)) {
- bulk.push(rBushNode.aabb);
- }
- }
- });
- // use bulk inserting, which is ~2-3 times faster
- // @see https://github.com/mourner/rbush#bulk-inserting-data
- this.rBush.load(bulk);
- bulk.length = 0;
- this.toSync.clear();
- // this.syncing = false;
- };
- return PrepareRendererPlugin;
- }();
- PrepareRendererPlugin.tag = 'Prepare';
- function isCanvas(value) {
- return !!value.document;
- }
- var CanvasEvent;
- (function (CanvasEvent) {
- CanvasEvent["READY"] = "ready";
- CanvasEvent["BEFORE_RENDER"] = "beforerender";
- CanvasEvent["RERENDER"] = "rerender";
- CanvasEvent["AFTER_RENDER"] = "afterrender";
- CanvasEvent["BEFORE_DESTROY"] = "beforedestroy";
- CanvasEvent["AFTER_DESTROY"] = "afterdestroy";
- CanvasEvent["RESIZE"] = "resize";
- CanvasEvent["DIRTY_RECTANGLE"] = "dirtyrectangle";
- CanvasEvent["RENDERER_CHANGED"] = "rendererchanged";
- })(CanvasEvent || (CanvasEvent = {}));
- var DEFAULT_CAMERA_Z = 500;
- var DEFAULT_CAMERA_NEAR = 0.1;
- var DEFAULT_CAMERA_FAR = 1000;
- /**
- * reuse custom event preventing from re-create them in every frame
- */
- var mountedEvent = new CustomEvent(ElementEvent.MOUNTED);
- var unmountedEvent = new CustomEvent(ElementEvent.UNMOUNTED);
- var beforeRenderEvent = new CustomEvent(CanvasEvent.BEFORE_RENDER);
- var rerenderEvent = new CustomEvent(CanvasEvent.RERENDER);
- var afterRenderEvent = new CustomEvent(CanvasEvent.AFTER_RENDER);
- /**
- * can be treated like Window in DOM
- * provide some extra methods like `window`, such as:
- * * `window.requestAnimationFrame`
- * * `window.devicePixelRatio`
- *
- * prototype chains: Canvas(Window) -> EventTarget
- */
- var Canvas = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose(Canvas, _EventTarget);
- function Canvas(config) {
- var _this;
- _this = _EventTarget.call(this) || this;
- // create document
- /**
- * window.document
- */
- _this.document = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
- */
- _this.customElements = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
- */
- _this.requestAnimationFrame = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
- */
- _this.cancelAnimationFrame = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
- */
- _this.devicePixelRatio = void 0;
- /**
- * whether the runtime supports PointerEvent?
- * if not, the event system won't trigger pointer events like `pointerdown`
- */
- _this.supportsPointerEvents = void 0;
- /**
- * whether the runtime supports TouchEvent?
- * if not, the event system won't trigger touch events like `touchstart`
- */
- _this.supportsTouchEvents = void 0;
- /**
- * is this native event a TouchEvent?
- */
- _this.isTouchEvent = void 0;
- /**
- * is this native event a MouseEvent?
- */
- _this.isMouseEvent = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element
- */
- _this.Element = DisplayObject;
- /**
- * rAF in auto rendering
- */
- _this.frameId = void 0;
- _this.inited = false;
- _this.readyPromise = void 0;
- _this.resolveReadyPromise = void 0;
- _this.context = {};
- _this.document = new Document();
- _this.document.defaultView = _assertThisInitialized(_this);
- // create registry of custom elements
- _this.customElements = new CustomElementRegistry();
- var container = config.container,
- canvas = config.canvas,
- offscreenCanvas = config.offscreenCanvas,
- width = config.width,
- height = config.height,
- devicePixelRatio = config.devicePixelRatio,
- renderer = config.renderer,
- background = config.background,
- cursor = config.cursor,
- document = config.document,
- requestAnimationFrame = config.requestAnimationFrame,
- cancelAnimationFrame = config.cancelAnimationFrame,
- createImage = config.createImage,
- supportsPointerEvents = config.supportsPointerEvents,
- supportsTouchEvents = config.supportsTouchEvents,
- supportsCSSTransform = config.supportsCSSTransform,
- useNativeClickEvent = config.useNativeClickEvent,
- alwaysTriggerPointerEventOnCanvas = config.alwaysTriggerPointerEventOnCanvas,
- isTouchEvent = config.isTouchEvent,
- isMouseEvent = config.isMouseEvent;
- cleanExistedCanvas(container, _assertThisInitialized(_this));
- var canvasWidth = width;
- var canvasHeight = height;
- var dpr = devicePixelRatio;
- // use user-defined <canvas> or OffscreenCanvas
- if (canvas) {
- // infer width & height with dpr
- dpr = devicePixelRatio || isBrowser && window.devicePixelRatio || 1;
- dpr = dpr >= 1 ? Math.ceil(dpr) : 1;
- canvasWidth = width || getWidth(canvas) || canvas.width / dpr;
- canvasHeight = height || getHeight(canvas) || canvas.height / dpr;
- }
- /**
- * implements `Window` interface
- */
- _this.devicePixelRatio = dpr;
- _this.requestAnimationFrame = requestAnimationFrame !== null && requestAnimationFrame !== void 0 ? requestAnimationFrame : raf.bind(runtime.globalThis);
- _this.cancelAnimationFrame = cancelAnimationFrame !== null && cancelAnimationFrame !== void 0 ? cancelAnimationFrame : caf.bind(runtime.globalThis);
- /**
- * limits query
- */
- // the following feature-detect from hammer.js
- // @see https://github.com/hammerjs/hammer.js/blob/master/src/inputjs/input-consts.js#L5
- _this.supportsTouchEvents = supportsTouchEvents !== null && supportsTouchEvents !== void 0 ? supportsTouchEvents : 'ontouchstart' in runtime.globalThis;
- _this.supportsPointerEvents = supportsPointerEvents !== null && supportsPointerEvents !== void 0 ? supportsPointerEvents : !!runtime.globalThis.PointerEvent;
- _this.isTouchEvent = isTouchEvent !== null && isTouchEvent !== void 0 ? isTouchEvent : function (event) {
- return _this.supportsTouchEvents && event instanceof runtime.globalThis.TouchEvent;
- };
- _this.isMouseEvent = isMouseEvent !== null && isMouseEvent !== void 0 ? isMouseEvent : function (event) {
- return !runtime.globalThis.MouseEvent || event instanceof runtime.globalThis.MouseEvent && (!_this.supportsPointerEvents || !(event instanceof runtime.globalThis.PointerEvent));
- };
- _this.initRenderingContext({
- container: container,
- canvas: canvas,
- width: canvasWidth,
- height: canvasHeight,
- renderer: renderer,
- offscreenCanvas: offscreenCanvas,
- devicePixelRatio: dpr,
- cursor: cursor || 'default',
- background: background || 'transparent',
- createImage: createImage,
- document: document,
- supportsCSSTransform: supportsCSSTransform,
- useNativeClickEvent: useNativeClickEvent,
- alwaysTriggerPointerEventOnCanvas: alwaysTriggerPointerEventOnCanvas
- });
- _this.initDefaultCamera(canvasWidth, canvasHeight);
- _this.initRenderer(renderer, true);
- return _this;
- }
- var _proto = Canvas.prototype;
- _proto.initRenderingContext = function initRenderingContext(mergedConfig) {
- this.context.config = mergedConfig;
- // bind rendering context, shared by all renderers
- this.context.renderingContext = {
- /**
- * the root node in scene graph
- */
- root: this.document.documentElement,
- renderListCurrentFrame: [],
- unculledEntities: [],
- renderReasons: new Set(),
- force: false,
- dirty: false
- };
- };
- _proto.initDefaultCamera = function initDefaultCamera(width, height) {
- var _this2 = this;
- // set a default ortho camera
- var camera = new runtime.CameraContribution();
- 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);
- // keep ref since it will use raf in camera animation
- camera.canvas = this;
- // redraw when camera changed
- camera.eventEmitter.on(CameraEvent.UPDATED, function () {
- _this2.context.renderingContext.renderReasons.add(RenderReason.CAMERA_CHANGED);
- });
- // bind camera
- this.context.camera = camera;
- };
- _proto.getConfig = function getConfig() {
- return this.context.config;
- }
- /**
- * get the root displayObject in scenegraph
- * @alias this.document.documentElement
- */;
- _proto.getRoot = function getRoot() {
- return this.document.documentElement;
- }
- /**
- * get the camera of canvas
- */;
- _proto.getCamera = function getCamera() {
- return this.context.camera;
- };
- _proto.getContextService = function getContextService() {
- return this.context.contextService;
- };
- _proto.getEventService = function getEventService() {
- return this.context.eventService;
- };
- _proto.getRenderingService = function getRenderingService() {
- return this.context.renderingService;
- };
- _proto.getRenderingContext = function getRenderingContext() {
- return this.context.renderingContext;
- };
- _proto.getStats = function getStats() {
- return this.getRenderingService().getStats();
- }
- // /**
- // * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
- // */
- // getComputedStyle(node: DisplayObject) {
- // return node.computedStyle;
- // }
- ;
- /**
- * `cleanUp` means clean all the internal services of Canvas which happens when calling `canvas.destroy()`.
- */
- _proto.destroy = function destroy(cleanUp, skipTriggerEvent) {
- if (cleanUp === void 0) {
- cleanUp = true;
- }
- if (skipTriggerEvent === void 0) {
- skipTriggerEvent = false;
- }
- if (!skipTriggerEvent) {
- this.dispatchEvent(new CustomEvent(CanvasEvent.BEFORE_DESTROY));
- }
- if (this.frameId) {
- var cancelRAF = this.getConfig().cancelAnimationFrame || cancelAnimationFrame;
- cancelRAF(this.frameId);
- }
- // unmount all children
- var root = this.getRoot();
- this.unmountChildren(root);
- if (cleanUp) {
- // destroy Document
- this.document.destroy();
- this.getEventService().destroy();
- }
- // destroy services
- this.getRenderingService().destroy();
- this.getContextService().destroy();
- // clear root after renderservice destroyed
- if (cleanUp && this.context.rBushRoot) {
- // clear rbush
- this.context.rBushRoot.clear();
- this.context.rBushRoot = null;
- this.context.renderingContext.root = null;
- }
- if (!skipTriggerEvent) {
- this.dispatchEvent(new CustomEvent(CanvasEvent.AFTER_DESTROY));
- }
- }
- /**
- * compatible with G 3.0
- * @deprecated
- * @alias resize
- */;
- _proto.changeSize = function changeSize(width, height) {
- this.resize(width, height);
- };
- _proto.resize = function resize(width, height) {
- // update canvas' config
- var canvasConfig = this.context.config;
- canvasConfig.width = width;
- canvasConfig.height = height;
- // resize context
- this.getContextService().resize(width, height);
- // resize camera
- var camera = this.context.camera;
- var projectionMode = camera.getProjectionMode();
- camera.setPosition(width / 2, height / 2, DEFAULT_CAMERA_Z).setFocalPoint(width / 2, height / 2, 0);
- if (projectionMode === CameraProjectionMode.ORTHOGRAPHIC) {
- camera.setOrthographic(width / -2, width / 2, height / 2, height / -2, camera.getNear(), camera.getFar());
- } else {
- camera.setAspect(width / height);
- }
- this.dispatchEvent(new CustomEvent(CanvasEvent.RESIZE, {
- width: width,
- height: height
- }));
- }
- // proxy to document.documentElement
- ;
- _proto.appendChild = function appendChild(child, index) {
- return this.document.documentElement.appendChild(child, index);
- };
- _proto.insertBefore = function insertBefore(newChild, refChild) {
- return this.document.documentElement.insertBefore(newChild, refChild);
- };
- _proto.removeChild = function removeChild(child) {
- return this.document.documentElement.removeChild(child);
- }
- /**
- * Remove all children which can be appended to its original parent later again.
- */;
- _proto.removeChildren = function removeChildren() {
- this.document.documentElement.removeChildren();
- }
- /**
- * Recursively destroy all children which can not be appended to its original parent later again.
- * But the canvas remains running which means display objects can be appended later.
- */;
- _proto.destroyChildren = function destroyChildren() {
- this.document.documentElement.destroyChildren();
- };
- _proto.render = function render() {
- var _this3 = this;
- this.dispatchEvent(beforeRenderEvent);
- var renderingService = this.getRenderingService();
- renderingService.render(this.getConfig(), function () {
- // trigger actual rerender event
- // @see https://github.com/antvis/G/issues/1268
- _this3.dispatchEvent(rerenderEvent);
- });
- this.dispatchEvent(afterRenderEvent);
- };
- _proto.run = function run() {
- var _this4 = this;
- var tick = function tick() {
- _this4.render();
- _this4.frameId = _this4.requestAnimationFrame(tick);
- };
- tick();
- };
- _proto.initRenderer = function initRenderer(renderer, firstContentfullPaint) {
- var _this5 = this;
- if (firstContentfullPaint === void 0) {
- firstContentfullPaint = false;
- }
- if (!renderer) {
- throw new Error('Renderer is required.');
- }
- // reset
- this.inited = false;
- this.readyPromise = undefined;
- // FIXME: should re-create here?
- this.context.rBushRoot = new RBush();
- // reset rendering plugins
- this.context.renderingPlugins = [];
- this.context.renderingPlugins.push(new EventPlugin(), new PrepareRendererPlugin(), new DirtyCheckPlugin(), new CullingPlugin([new FrustumCullingStrategy()]));
- //
- this.loadRendererContainerModule(renderer);
- // init context service
- this.context.contextService = new this.context.ContextService(_extends({}, runtime, this.context));
- // init rendering service
- this.context.renderingService = new RenderingService(runtime, this.context);
- // init event service
- this.context.eventService = new EventService(runtime, this.context);
- this.context.eventService.init();
- if (this.context.contextService.init) {
- this.context.contextService.init();
- this.initRenderingService(renderer, firstContentfullPaint, true);
- } else {
- this.context.contextService.initAsync().then(function () {
- _this5.initRenderingService(renderer, firstContentfullPaint);
- });
- }
- };
- _proto.initRenderingService = function initRenderingService(renderer, firstContentfullPaint, async) {
- var _this6 = this;
- if (firstContentfullPaint === void 0) {
- firstContentfullPaint = false;
- }
- if (async === void 0) {
- async = false;
- }
- this.context.renderingService.init(function () {
- _this6.inited = true;
- if (firstContentfullPaint) {
- if (async) {
- _this6.requestAnimationFrame(function () {
- _this6.dispatchEvent(new CustomEvent(CanvasEvent.READY));
- });
- } else {
- _this6.dispatchEvent(new CustomEvent(CanvasEvent.READY));
- }
- if (_this6.readyPromise) {
- _this6.resolveReadyPromise();
- }
- } else {
- _this6.dispatchEvent(new CustomEvent(CanvasEvent.RENDERER_CHANGED));
- }
- if (!firstContentfullPaint) {
- _this6.getRoot().forEach(function (node) {
- var renderable = node.renderable;
- if (renderable) {
- renderable.renderBoundsDirty = true;
- renderable.boundsDirty = true;
- renderable.dirty = true;
- }
- });
- }
- // keep current scenegraph unchanged, just trigger mounted event
- _this6.mountChildren(_this6.getRoot());
- if (renderer.getConfig().enableAutoRendering) {
- _this6.run();
- }
- });
- };
- _proto.loadRendererContainerModule = function loadRendererContainerModule(renderer) {
- var _this7 = this;
- // load other container modules provided by g-canvas/g-svg/g-webgl
- var plugins = renderer.getPlugins();
- plugins.forEach(function (plugin) {
- plugin.context = _this7.context;
- plugin.init(runtime);
- });
- };
- _proto.setRenderer = function setRenderer(renderer) {
- // update canvas' config
- var canvasConfig = this.getConfig();
- if (canvasConfig.renderer === renderer) {
- return;
- }
- var oldRenderer = canvasConfig.renderer;
- canvasConfig.renderer = renderer;
- // keep all children undestroyed
- this.destroy(false, true);
- // destroy all plugins, reverse will mutate origin array
- [].concat(oldRenderer === null || oldRenderer === void 0 ? void 0 : oldRenderer.getPlugins()).reverse().forEach(function (plugin) {
- plugin.destroy(runtime);
- });
- this.initRenderer(renderer);
- };
- _proto.setCursor = function setCursor(cursor) {
- var canvasConfig = this.getConfig();
- canvasConfig.cursor = cursor;
- this.getContextService().applyCursorStyle(cursor);
- };
- _proto.unmountChildren = function unmountChildren(parent) {
- var _this8 = this;
- // unmountChildren recursively
- parent.childNodes.forEach(function (child) {
- _this8.unmountChildren(child);
- });
- if (this.inited) {
- if (parent.isMutationObserved) {
- parent.dispatchEvent(unmountedEvent);
- } else {
- unmountedEvent.target = parent;
- this.dispatchEvent(unmountedEvent, true);
- }
- // skip document.documentElement
- if (parent !== this.document.documentElement) {
- parent.ownerDocument = null;
- }
- parent.isConnected = false;
- }
- // trigger after unmounted
- if (parent.isCustomElement) {
- if (parent.disconnectedCallback) {
- parent.disconnectedCallback();
- }
- }
- };
- _proto.mountChildren = function mountChildren(parent) {
- var _this9 = this;
- if (this.inited) {
- if (!parent.isConnected) {
- parent.ownerDocument = this.document;
- parent.isConnected = true;
- if (parent.isMutationObserved) {
- parent.dispatchEvent(mountedEvent);
- } else {
- mountedEvent.target = parent;
- this.dispatchEvent(mountedEvent, true);
- }
- }
- } else {
- 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);
- }
- // recursively mount children
- parent.childNodes.forEach(function (child) {
- _this9.mountChildren(child);
- });
- // trigger after mounted
- if (parent.isCustomElement) {
- if (parent.connectedCallback) {
- parent.connectedCallback();
- }
- }
- };
- _proto.client2Viewport = function client2Viewport(client) {
- return this.getEventService().client2Viewport(client);
- };
- _proto.viewport2Client = function viewport2Client(canvas) {
- return this.getEventService().viewport2Client(canvas);
- };
- _proto.viewport2Canvas = function viewport2Canvas(viewport) {
- return this.getEventService().viewport2Canvas(viewport);
- };
- _proto.canvas2Viewport = function canvas2Viewport(canvas) {
- return this.getEventService().canvas2Viewport(canvas);
- }
- /**
- * @deprecated
- * @alias client2Viewport
- */;
- _proto.getPointByClient = function getPointByClient(clientX, clientY) {
- return this.client2Viewport({
- x: clientX,
- y: clientY
- });
- }
- /**
- * @deprecated
- * @alias viewport2Client
- */;
- _proto.getClientByPoint = function getClientByPoint(x, y) {
- return this.viewport2Client({
- x: x,
- y: y
- });
- };
- _createClass(Canvas, [{
- key: "ready",
- get: function get() {
- var _this10 = this;
- if (!this.readyPromise) {
- this.readyPromise = new Promise(function (resolve) {
- _this10.resolveReadyPromise = function () {
- resolve(_this10);
- };
- });
- if (this.inited) {
- this.resolveReadyPromise();
- }
- }
- return this.readyPromise;
- }
- }]);
- return Canvas;
- }(EventTarget);
- 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 };
|